text
stringlengths
1
7.76k
source
stringlengths
17
81
384 INPUT/OUTPUT CHAP. 5 system must do the same thing in software. This means that it must first acquire a list of bad sectors, either by reading them from the disk, or simply testing the entire disk itself. Once it knows which sectors are bad, it can build remapping tables. If the operating system wants to use the approach of Fig. 5-26(c), it must shift the data in sectors 7 through 29 up one sector. If the operating system is handling the remapping, it must make sure that bad sectors do not occur in any files and also do not occur in the free list or bitmap. One way to do this is to create a secret file consisting of all the bad sectors. If this file is not entered into the file system, users will not accidentally read it (or worse yet, free it). However, there is still another problem: backups. If the disk is backed up file by file, it is important that the backup utility not try to copy the bad block file. To prevent this, the operating system has to hide the bad block file so well that even a backup utility cannot find it. If the disk is backed up sector by sector rather than file by file, it will be difficult, if not impossible, to prevent read errors during back- up. The only hope is that the backup program has enough smarts to give up after 10 failed reads and continue with the next sector. Bad sectors are not the only source of errors. Seek errors caused by mechanical problems in the arm also occur. The controller keeps track of the arm position in- ternally. To perform a seek, it issues a command to the arm motor to move the arm to the new cylinder. When the arm gets to its destination, the controller reads the actual cylinder number from the preamble of the next sector. If the arm is in the wrong place, a seek error has occurred. Most hard disk controllers correct seek errors automatically, but most of the old floppy controllers used in the 1980s and 1990s just set an error bit and left the rest to the driver. The driver handled this error by issuing a recalibrate command, to move the arm as far out as it would go and reset the controller’s internal idea of the current cylinder to 0. Usually this solved the problem. If it did not, the drive had to be repaired. As we have just seen, the controller is really a specialized little computer, com- plete with software, variables, buffers, and occasionally, bugs. Sometimes an unu- sual sequence of events, such as an interrupt on one drive occurring simultaneously with a recalibrate command for another drive will trigger a bug and cause the con- troller to go into a loop or lose track of what it was doing. Controller designers us- ually plan for the worst and provide a pin on the chip which, when asserted, forces the controller to forget whatever it was doing and reset itself. If all else fails, the disk driver can set a bit to invoke this signal and reset the controller. If that does not help, all the driver can do is print a message and give up. Recalibrating a disk makes a funny noise but otherwise normally is not disturb- ing. However, there is one situation where recalibration is a problem: systems with real-time constraints. When a video is being played off (or served from) a hard disk, or files from a hard disk are being burned onto a Blu-ray disc, it is essential that the bits arrive from the hard disk at a uniform rate. Under these circumstances,
clipped_os_Page_384_Chunk6601
SEC. 5.4 DISKS 385 recalibrations insert gaps into the bit stream and are unacceptable. Special drives, called AV disks (Audio Visual disks), which never recalibrate are available for such applications. Anecdotally, a highly convincing demonstration of how advanced disk con- trollers have become was given by the Dutch hacker Jeroen Domburg, who hacked a modern disk controller to make it run custom code. It turns out the disk controller is equipped with a fairly powerful multicore (!) ARM processor and has easily enough resources to run Linux. If the bad guys hack your hard drive in this way, they will be able to see and modify all data you transfer to and from the disk. Even reinstalling the operating from scratch will not remove the infection, as the disk controller itself is malicious and serves as a permanent backdoor. Alternatively, you can collect a stack of broken hard drives from your local recycling center and build your own cluster computer for free. 5.4.5 Stable Storage As we have seen, disks sometimes make errors. Good sectors can suddenly be- come bad sectors. Whole drives can die unexpectedly. RAIDs protect against a few sectors going bad or even a drive falling out. However, they do not protect against write errors laying down bad data in the first place. They also do not pro- tect against crashes during writes corrupting the original data without replacing them by newer data. For some applications, it is essential that data never be lost or corrupted, even in the face of disk and CPU errors. Ideally, a disk should simply work all the time with no errors. Unfortunately, that is not achievable. What is achievable is a disk subsystem that has the following property: when a write is issued to it, the disk ei- ther correctly writes the data or it does nothing, leaving the existing data intact. Such a system is called stable storage and is implemented in software (Lampson and Sturgis, 1979). The goal is to keep the disk consistent at all costs. Below we will describe a slight variant of the original idea. Before describing the algorithm, it is important to have a clear model of the possible errors. The model assumes that when a disk writes a block (one or more sectors), either the write is correct or it is incorrect and this error can be detected on a subsequent read by examining the values of the ECC fields. In principle, guaranteed error detection is never possible because with a, say, 16-byte ECC field guarding a 512-byte sector, there are 24096 data values and only 2144 ECC values. Thus if a block is garbled during writing but the ECC is not, there are billions upon billions of incorrect combinations that yield the same ECC. If any of them occur, the error will not be detected. On the whole, the probability of random data having the proper 16-byte ECC is about 2−144, which is small enough that we will call it zero, even though it is really not. The model also assumes that a correctly written sector can spontaneously go bad and become unreadable. However, the assumption is that such events are so
clipped_os_Page_385_Chunk6602
386 INPUT/OUTPUT CHAP. 5 rare that having the same sector go bad on a second (independent) drive during a reasonable time interval (e.g., 1 day) is small enough to ignore. The model also assumes the CPU can fail, in which case it just stops. Any disk write in progress at the moment of failure also stops, leading to incorrect data in one sector and an incorrect ECC that can later be detected. Under all these condi- tions, stable storage can be made 100% reliable in the sense of writes either work- ing correctly or leaving the old data in place. Of course, it does not protect against physical disasters, such as an earthquake happening and the computer falling 100 meters into a fissure and landing in a pool of boiling magma. It is tough to recover from this condition in software. Stable storage uses a pair of identical disks with the corresponding blocks working together to form one error-free block. In the absence of errors, the corres- ponding blocks on both drives are the same. Either one can be read to get the same result. To achieve this goal, the following three operations are defined: 1. Stable writes. A stable write consists of first writing the block on drive 1, then reading it back to verify that it was written correctly. If it was not, the write and reread are done again up to n times until they work. After n consecutive failures, the block is remapped onto a spare and the operation repeated until it succeeds, no matter how many spares have to be tried. After the write to drive 1 has succeeded, the corresponding block on drive 2 is written and reread, repeatedly if need be, until it, too, finally succeeds. In the absence of CPU crashes, when a stable write completes, the block has correctly been written onto both drives and verified on both of them. 2. Stable reads. A stable read first reads the block from drive 1. If this yields an incorrect ECC, the read is tried again, up to n times. If all of these give bad ECCs, the corresponding block is read from drive 2. Given the fact that a successful stable write leaves two good copies of the block behind, and our assumption that the probability of the same block spontaneously going bad on both drives in a reasonable time in- terval is negligible, a stable read always succeeds. 3. Crash recovery. After a crash, a recovery program scans both disks comparing corresponding blocks. If a pair of blocks are both good and the same, nothing is done. If one of them has an ECC error, the bad block is overwritten with the corresponding good block. If a pair of blocks are both good but different, the block from drive 1 is written onto drive 2. In the absence of CPU crashes, this scheme always works because stable writes always write two valid copies of every block and spontaneous errors are as- sumed never to occur on both corresponding blocks at the same time. What about
clipped_os_Page_386_Chunk6603
SEC. 5.4 DISKS 387 in the presence of CPU crashes during stable writes? It depends on precisely when the crash occurs. There are fiv e possibilities, as depicted in Fig. 5-27. Old 1 Old 2 Disk 1 Old 2 Disk New 1 Old 2 Disk New 1 2 Disk New 1 New 2 Disk Crash Crash Crash Crash Crash (a) (b) (c) (d) (e) ECC error Figure 5-27. Analysis of the influence of crashes on stable writes. In Fig. 5-27(a), the CPU crash happens before either copy of the block is writ- ten. During recovery, neither will be changed and the old value will continue to exist, which is allowed. In Fig. 5-27(b), the CPU crashes during the write to drive 1, destroying the contents of the block. However the recovery program detects this error and restores the block on drive 1 from drive 2. Thus the effect of the crash is wiped out and the old state is fully restored. In Fig. 5-27(c), the CPU crash happens after drive 1 is written but before drive 2 is written. The point of no return has been passed here: the recovery program copies the block from drive 1 to drive 2. The write succeeds. Fig. 5-27(d) is like Fig. 5-27(b): during recovery, the good block overwrites the bad block. Again, the final value of both blocks is the new one. Finally, in Fig. 5-27(e) the recovery program sees that both blocks are the same, so neither is changed and the write succeeds here, too. Various optimizations and improvements are possible to this scheme. For starters, comparing all the blocks pairwise after a crash is doable, but expensive. A huge improvement is to keep track of which block was being written during a sta- ble write so that only one block has to be checked during recovery. Some com- puters have a small amount of nonvolatile RAM, which is a special CMOS memo- ry powered by a lithium battery. Such batteries last for years, possibly even the whole life of the computer. Unlike main memory, which is lost after a crash, non- volatile RAM is not lost after a crash. The time of day is normally kept here (and incremented by a special circuit), which is why computers still know what time it is even after having been unplugged. Suppose that a few bytes of nonvolatile RAM are available for operating sys- tem purposes. The stable write can put the number of the block it is about to update in nonvolatile RAM before starting the write. After successfully completing the stable write, the block number in nonvolatile RAM is overwritten with an invalid
clipped_os_Page_387_Chunk6604
388 INPUT/OUTPUT CHAP. 5 block number, for example, −1. Under these conditions, after a crash the recovery program can check the nonvolatile RAM to see if a stable write happened to be in progress during the crash, and if so, which block was being written when the crashed happened. The two copies of the block can then be checked for correctness and consistency. If nonvolatile RAM is not available, it can be simulated as follows. At the start of a stable write, a fixed disk block on drive 1 is overwritten with the number of the block to be stably written. This block is then read back to verify it. After get- ting it correct, the corresponding block on drive 2 is written and verified. When the stable write completes correctly, both blocks are overwritten with an invalid block number and verified. Again here, after a crash it is easy to determine whether or not a stable write was in progress during the crash. Of course, this technique re- quires eight extra disk operations to write a stable block, so it should be used exceedingly sparingly. One last point is worth making. We assumed that only one spontaneous decay of a good block to a bad block happens per block pair per day. If enough days go by, the other one might go bad, too. Therefore, once a day a complete scan of both disks must be done, repairing any damage. That way, every morning both disks are always identical. Even if both blocks in a pair go bad within a period of a few days, all errors are repaired correctly. 5.5 CLOCKS Clocks (also called timers) are essential to the operation of any multipro- grammed system for a variety of reasons. They maintain the time of day and pre- vent one process from monopolizing the CPU, among other things. The clock soft- ware can take the form of a device driver, even though a clock is neither a block device, like a disk, nor a character device, like a mouse. Our examination of clocks will follow the same pattern as in the previous section: first a look at clock hard- ware and then a look at the clock software. 5.5.1 Clock Hardware Tw o types of clocks are commonly used in computers, and both are quite dif- ferent from the clocks and watches used by people. The simpler clocks are tied to the 110- or 220-volt power line and cause an interrupt on every voltage cycle, at 50 or 60 Hz. These clocks used to dominate, but are rare nowadays. The other kind of clock is built out of three components: a crystal oscillator, a counter, and a holding register, as shown in Fig. 5-28. When a piece of quartz crystal is properly cut and mounted under tension, it can be made to generate a periodic signal of very great accuracy, typically in the range of several hundred megahertz to a few gigahertz, depending on the crystal chosen. Using electronics,
clipped_os_Page_388_Chunk6605
SEC. 5.5 CLOCKS 389 this base signal can be multiplied by a small integer to get frequencies up to several gigahertz or even more. At least one such circuit is usually found in any computer, providing a synchronizing signal to the computer’s various circuits. This signal is fed into the counter to make it count down to zero. When the counter gets to zero, it causes a CPU interrupt. Crystal oscillator Counter is decremented at each pulse Holding register is used to load the counter Figure 5-28. A programmable clock. Programmable clocks typically have sev eral modes of operation. In one-shot mode, when the clock is started, it copies the value of the holding register into the counter and then decrements the counter at each pulse from the crystal. When the counter gets to zero, it causes an interrupt and stops until it is explicitly started again by the software. In square-wave mode, after getting to zero and causing the interrupt, the holding register is automatically copied into the counter, and the whole process is repeated again indefinitely. These periodic interrupts are called clock ticks. The advantage of the programmable clock is that its interrupt frequency can be controlled by software. If a 500-MHz crystal is used, then the counter is pulsed ev ery 2 nsec. With (unsigned) 32-bit registers, interrupts can be programmed to oc- cur at intervals from 2 nsec to 8.6 sec. Programmable clock chips usually contain two or three independently programmable clocks and have many other options as well (e.g., counting up instead of down, interrupts disabled, and more). To prevent the current time from being lost when the computer’s power is turned off, most computers have a battery-powered backup clock, implemented with the kind of low-power circuitry used in digital watches. The battery clock can be read at startup. If the backup clock is not present, the software may ask the user for the current date and time. There is also a standard way for a networked system to get the current time from a remote host. In any case the time is then translated into the number of clock ticks since 12 A.M. UTC (Universal Coordinated Time) (formerly known as Greenwich Mean Time) on Jan. 1, 1970, as UNIX does, or since some other benchmark moment. The origin of time for Windows is Jan. 1, 1980. At ev ery clock tick, the real time is incremented by one count. Usually util- ity programs are provided to manually set the system clock and the backup clock and to synchronize the two clocks.
clipped_os_Page_389_Chunk6606
390 INPUT/OUTPUT CHAP. 5 5.5.2 Clock Software All the clock hardware does is generate interrupts at known intervals. Every- thing else involving time must be done by the software, the clock driver. The exact duties of the clock driver vary among operating systems, but usually include most of the following: 1. Maintaining the time of day. 2. Preventing processes from running longer than they are allowed to. 3. Accounting for CPU usage. 4. Handling the alar m system call made by user processes. 5. Providing watchdog timers for parts of the system itself. 6. Doing profiling, monitoring, and statistics gathering. The first clock function, maintaining the time of day (also called the real time) is not difficult. It just requires incrementing a counter at each clock tick, as men- tioned before. The only thing to watch out for is the number of bits in the time-of- day counter. With a clock rate of 60 Hz, a 32-bit counter will overflow in just over 2 years. Clearly the system cannot store the real time as the number of ticks since Jan. 1, 1970 in 32 bits. Three approaches can be taken to solve this problem. The first way is to use a 64-bit counter, although doing so makes maintaining the counter more expensive since it has to be done many times a second. The second way is to maintain the time of day in seconds, rather than in ticks, using a subsidiary counter to count ticks until a whole second has been accumulated. Because 232 seconds is more than 136 years, this method will work until the twenty-second century. The third approach is to count in ticks, but to do that relative to the time the system was booted, rather than relative to a fixed external moment. When the back- up clock is read or the user types in the real time, the system boot time is calcu- lated from the current time-of-day value and stored in memory in any convenient form. Later, when the time of day is requested, the stored time of day is added to the counter to get the current time of day. All three approaches are shown in Fig. 5-29. The second clock function is preventing processes from running too long. Whenever a process is started, the scheduler initializes a counter to the value of that process’ quantum in clock ticks. At every clock interrupt, the clock driver decrements the quantum counter by 1. When it gets to zero, the clock driver calls the scheduler to set up another process. The third clock function is doing CPU accounting. The most accurate way to do it is to start a second timer, distinct from the main system timer, whenever a process is started up. When that process is stopped, the timer can be read out to tell
clipped_os_Page_390_Chunk6607
SEC. 5.5 CLOCKS 391 (a) (b) (c) Time of day in ticks Time of day in seconds Counter in ticks System boot time in seconds Number of ticks in current second 64 bits 32 bits 32 bits Figure 5-29. Three ways to maintain the time of day. how long the process has run. To do things right, the second timer should be saved when an interrupt occurs and restored afterward. A less accurate, but simpler, way to do accounting is to maintain a pointer to the process table entry for the currently running process in a global variable. At ev ery clock tick, a field in the current process’ entry is incremented. In this way, ev ery clock tick is ‘‘charged’’ to the process running at the time of the tick. A minor problem with this strategy is that if many interrupts occur during a process’ run, it is still charged for a full tick, even though it did not get much work done. Properly accounting for the CPU during interrupts is too expensive and is rarely done. In many systems, a process can request that the operating system give it a warning after a certain interval. The warning is usually a signal, interrupt, message, or something similar. One application requiring such warnings is networking, in which a packet not acknowledged within a certain time interval must be retrans- mitted. Another application is computer-aided instruction, where a student not pro- viding a response within a certain time is told the answer. If the clock driver had enough clocks, it could set a separate clock for each re- quest. This not being the case, it must simulate multiple virtual clocks with a single physical clock. One way is to maintain a table in which the signal time for all pending timers is kept, as well as a variable giving the time of the next one. When- ev er the time of day is updated, the driver checks to see if the closest signal has oc- curred. If it has, the table is searched for the next one to occur. If many signals are expected, it is more efficient to simulate multiple clocks by chaining all the pending clock requests together, sorted on time, in a linked list, as shown in Fig. 5-30. Each entry on the list tells how many clock ticks following the previous one to wait before causing a signal. In this example, signals are pending for 4203, 4207, 4213, 4215, and 4216. In Fig. 5-30, the next interrupt occurs in 3 ticks. On each tick, Next signal is decremented. When it gets to 0, the signal corresponding to the first item on the list is caused, and that item is removed from the list. Then Next signal is set to the value in the entry now at the head of the list, in this example, 4.
clipped_os_Page_391_Chunk6608
392 INPUT/OUTPUT CHAP. 5 Current time Next signal Clock header 3 4 6 2 1 X 4200 3 Figure 5-30. Simulating multiple timers with a single clock. Note that during a clock interrupt, the clock driver has several things to do— increment the real time, decrement the quantum and check for 0, do CPU ac- counting, and decrement the alarm counter. Howev er, each of these operations has been carefully arranged to be very fast because they hav e to be repeated many times a second. Parts of the operating system also need to set timers. These are called watch- dog timers and are frequently used (especially in embedded devices) to detect problems such as hangs. For instance, a watchdog timer may reset a system that stops running. While the system is running, it regularly resets the timer, so that it never expires. In that case, expiration of the timer proves that the system has not run for a long time, and leads to corrective action—such as a full-system reset. The mechanism used by the clock driver to handle watchdog timers is the same as for user signals. The only difference is that when a timer goes off, instead of causing a signal, the clock driver calls a procedure supplied by the caller. The pro- cedure is part of the caller’s code. The called procedure can do whatever is neces- sary, even causing an interrupt, although within the kernel interrupts are often inconvenient and signals do not exist. That is why the watchdog mechanism is pro- vided. It is worth nothing that the watchdog mechanism works only when the clock driver and the procedure to be called are in the same address space. The last thing in our list is profiling. Some operating systems provide a mech- anism by which a user program can have the system build up a histogram of its program counter, so it can see where it is spending its time. When profiling is a possibility, at every tick the driver checks to see if the current process is being pro- filed, and if so, computes the bin number (a range of addresses) corresponding to the current program counter. It then increments that bin by one. This mechanism can also be used to profile the system itself. 5.5.3 Soft Timers Most computers have a second programmable clock that can be set to cause timer interrupts at whatever rate a program needs. This timer is in addition to the main system timer whose functions were described above. As long as the interrupt frequency is low, there is no problem using this second timer for application-spe- cific purposes. The trouble arrives when the frequency of the application-specific
clipped_os_Page_392_Chunk6609
SEC. 5.5 CLOCKS 393 timer is very high. Below we will briefly describe a software-based timer scheme that works well under many circumstances, even at fairly high frequencies. The idea is due to Aron and Druschel (1999). For more details, please see their paper. Generally, there are two ways to manage I/O: interrupts and polling. Interrupts have low latency, that is, they happen immediately after the event itself with little or no delay. On the other hand, with modern CPUs, interrupts have a substantial overhead due to the need for context switching and their influence on the pipeline, TLB, and cache. The alternative to interrupts is to have the application poll for the event expect- ed itself. Doing this avoids interrupts, but there may be substantial latency because an event may happen directly after a poll, in which case it waits almost a whole polling interval. On the average, the latency is half the polling interval. Interrupt latency today is barely better than that of computers in the 1970s. On most minicomputers, for example, an interrupt took four bus cycles: to stack the program counter and PSW and to load a new program counter and PSW. Now- adays dealing with the pipeline, MMU, TLB, and cache adds a great deal to the overhead. These effects are likely to get worse rather than better in time, thus can- celing out faster clock rates. Unfortunately, for certain applications, we want nei- ther the overhead of interrupts nor the latency of polling. Soft timers avoid interrupts. Instead, whenever the kernel is running for some other reason, just before it returns to user mode it checks the real-time clock to see if a soft timer has expired. If it has expired, the scheduled event (e.g., packet trans- mission or checking for an incoming packet) is performed, with no need to switch into kernel mode since the system is already there. After the work has been per- formed, the soft timer is reset to go off again. All that has to be done is copy the current clock value to the timer and add the timeout interval to it. Soft timers stand or fall with the rate at which kernel entries are made for other reasons. These reasons include: 1. System calls. 2. TLB misses. 3. Page faults. 4. I/O interrupts. 5. The CPU going idle. To see how often these events happen, Aron and Druschel made measurements with several CPU loads, including a fully loaded Web server, a Web server with a compute-bound background job, playing real-time audio from the Internet, and recompiling the UNIX kernel. The average entry rate into the kernel varied from 2 to 18 μsec, with about half of these entries being system calls. Thus to a first-order approximation, having a soft timer go off, say, every 10 μsec is doable, albeit with
clipped_os_Page_393_Chunk6610
394 INPUT/OUTPUT CHAP. 5 an occasional missed deadline. Being 10 μsec late from time to time is often better than having interrupts eat up 35% of the CPU. Of course, there will be periods when there are no system calls, TLB misses, or page faults, in which case no soft timers will go off. To put an upper bound on these intervals, the second hardware timer can be set to go off, say, every 1 msec. If the application can live with only 1000 activations per second for occasional in- tervals, then the combination of soft timers and a low-frequency hardware timer may be better than either pure interrupt-driven I/O or pure polling. 5.6 USER INTERFACES: KEYBOARD, MOUSE, MONITOR Every general-purpose computer has a keyboard and monitor (and sometimes a mouse) to allow people to interact with it. Although the keyboard and monitor are technically separate devices, they work closely together. On mainframes, there are frequently many remote users, each with a device containing a keyboard and an at- tached display as a unit. These devices have historically been called terminals. People frequently still use that term, even when discussing personal computer keyboards and monitors (mostly for lack of a better term). 5.6.1 Input Software User input comes primarily from the keyboard and mouse (or somtimes touch screens), so let us look at those. On a personal computer, the keyboard contains an embedded microprocessor which usually communicates through a specialized serial port with a controller chip on the parentboard (although increasingly keyboards are connected to a USB port). An interrupt is generated whenever a key is struck and a second one is generated whenever a key is released. At each of these keyboard interrupts, the keyboard driver extracts the information about what happens from the I/O port associated with the keyboard. Everything else happens in software and is pretty much independent of the hardware. Most of the rest of this section can be best understood when thinking of typing commands to a shell window (command-line interface). This is how programmers commonly work. We will discuss graphical interfaces below. Some devices, in particular touch screens, are used for input and output. We hav e made an (arbi- trary) choice to discuss them in the section on output devices. We will discuss graphical interfaces later in this chapter. Keyboard Software The number in the I/O register is the key number, called the scan code, not the ASCII code. Normal keyboards have fewer than 128 keys, so only 7 bits are need- ed to represent the key number. The eighth bit is set to 0 on a key press and to 1 on
clipped_os_Page_394_Chunk6611
SEC. 5.6 USER INTERFACES: KEYBOARD, MOUSE, MONITOR 395 a key release. It is up to the driver to keep track of the status of each key (up or down). So all the hardware does is give press and release interrupts. Software does the rest. When the A key is struck, for example, the scan code (30) is put in an I/O reg- ister. It is up to the driver to determine whether it is lowercase, uppercase, CTRL- A, ALT-A, CTRL-ALT-A, or some other combination. Since the driver can tell which keys hav e been struck but not yet released (e.g., SHIFT), it has enough information to do the job. For example, the key sequence DEPRESS SHIFT, DEPRESS A, RELEASE A, RELEASE SHIFT indicates an uppercase A. However, the key sequence DEPRESS SHIFT, DEPRESS A, RELEASE SHIFT, RELEASE A also indicates an uppercase A. Although this keyboard interface puts the full bur- den on the software, it is extremely flexible. For example, user programs may be interested in whether a digit just typed came from the top row of keys or the numeric keypad on the side. In principle, the driver can provide this information. Tw o possible philosophies can be adopted for the driver. In the first one, the driver’s job is just to accept input and pass it upward unmodified. A program read- ing from the keyboard gets a raw sequence of ASCII codes. (Giving user programs the scan codes is too primitive, as well as being highly keyboard dependent.) This philosophy is well suited to the needs of sophisticated screen editors such as emacs, which allow the user to bind an arbitrary action to any character or se- quence of characters. It does, however, mean that if the user types dste instead of date and then corrects the error by typing three backspaces and ate, followed by a carriage return, the user program will be given all 11 ASCII codes typed, as fol- lows: d s t e ←←←a t e CR Not all programs want this much detail. Often they just want the corrected input, not the exact sequence of how it was produced. This observation leads to the second philosophy: the driver handles all the intraline editing and just delivers cor- rected lines to the user programs. The first philosophy is character oriented; the second one is line oriented. Originally they were referred to as raw mode and cooked mode, respectively. The POSIX standard uses the less-picturesque term canonical mode to describe line-oriented mode. Noncanonical mode is equiv- alent to raw mode, although many details of the behavior can be changed. POSIX- compatible systems provide several library functions that support selecting either mode and changing many parameters. If the keyboard is in canonical (cooked) mode, characters must be stored until an entire line has been accumulated, because the user may subsequently decide to erase part of it. Even if the keyboard is in raw mode, the program may not yet have
clipped_os_Page_395_Chunk6612
396 INPUT/OUTPUT CHAP. 5 requested input, so the characters must be buffered to allow type ahead. Either a dedicated buffer can be used or buffers can be allocated from a pool. The former puts a fixed limit on type ahead; the latter does not. This issue arises most acutely when the user is typing to a shell window (command-line window in Windows) and has just issued a command (such as a compilation) that has not yet completed. Subsequent characters typed have to be buffered because the shell is not ready to read them. System designers who do not permit users to type far ahead ought to be tarred and feathered, or worse yet, be forced to use their own system. Although the keyboard and monitor are logically separate devices, many users have grown accustomed to seeing the characters they hav e just typed appear on the screen. This process is called echoing. Echoing is complicated by the fact that a program may be writing to the screen while the user is typing (again, think about typing to a shell window). At the very least, the keyboard driver has to figure out where to put the new input without its being overwritten by program output. Echoing also gets complicated when more than 80 characters have to be dis- played in a window with 80-character lines (or some other number). Depending on the application, wrapping around to the next line may be appropriate. Some drivers just truncate lines to 80 characters by throwing away all characters beyond column 80. Another problem is tab handling. It is usually up to the driver to compute where the cursor is currently located, taking into account both output from pro- grams and output from echoing, and compute the proper number of spaces to be echoed. Now we come to the problem of device equivalence. Logically, at the end of a line of text, one wants a carriage return, to move the cursor back to column 1, and a line feed, to advance to the next line. Requiring users to type both at the end of each line would not sell well. It is up to the device driver to convert whatever comes in to the format used by the operating system. In UNIX, the Enter key is converted to a line feed for internal storage; in Windows it is converted to a car- riage return followed by a line feed. If the standard form is just to store a line feed (the UNIX convention), then carriage returns (created by the Enter key) should be turned into line feeds. If the internal format is to store both (the Windows convention), then the driver should generate a line feed when it gets a carriage return and a carriage return when it gets a line feed. No matter what the internal convention, the monitor may require both a line feed and a carriage return to be echoed in order to get the screen updated properly. On a multiuser system such as a mainframe, different users may have different types of terminals connected to it and it is up to the keyboard driver to get all the different carriage-return/line-feed combinations converted to the internal system standard and arrange for all echoing to be done right. When operating in canonical mode, some of the input characters have special meanings. Figure 5-31 shows all of the special characters required by the POSIX
clipped_os_Page_396_Chunk6613
SEC. 5.6 USER INTERFACES: KEYBOARD, MOUSE, MONITOR 397 standard. The defaults are all control characters that should not conflict with text input or codes used by programs; all except the last two can be changed under pro- gram control. Character POSIX name Comment CTRL-H ERASE Backspace one character CTRL-U KILL Erase entire line being typed CTRL-V LNEXT Inter pret next character literally CTRL-S STOP Stop output CTRL-Q START Star t output DEL INTR Interr upt process (SIGINT) CTRL-\ QUIT Force core dump (SIGQUIT) CTRL-D EOF End of file CTRL-M CR Carr iage retur n (unchangeable) CTRL-J NL Line feed (unchangeable) Figure 5-31. Characters that are handled specially in canonical mode. The ERASE character allows the user to rub out the character just typed. It is usually the backspace (CTRL-H). It is not added to the character queue but instead removes the previous character from the queue. It should be echoed as a sequence of three characters, backspace, space, and backspace, in order to remove the previ- ous character from the screen. If the previous character was a tab, erasing it de- pends on how it was processed when it was typed. If it is immediately expanded into spaces, some extra information is needed to determine how far to back up. If the tab itself is stored in the input queue, it can be removed and the entire line just output again. In most systems, backspacing will only erase characters on the cur- rent line. It will not erase a carriage return and back up into the previous line. When the user notices an error at the start of the line being typed in, it is often convenient to erase the entire line and start again. The KILL character erases the entire line. Most systems make the erased line vanish from the screen, but a few older ones echo it plus a carriage return and line feed because some users like to see the old line. Consequently, how to echo KILL is a matter of taste. As with ERASE it is usually not possible to go further back than the current line. When a block of characters is killed, it may or may not be worth the trouble for the driver to return buffers to the pool, if one is used. Sometimes the ERASE or KILL characters must be entered as ordinary data. The LNEXT character serves as an escape character. In UNIX CTRL-V is the de- fault. As an example, older UNIX systems often used the @ sign for KILL, but the Internet mail system uses addresses of the form linda@cs.washington.edu. Some- one who feels more comfortable with older conventions might redefine KILL as @, but then need to enter an @ sign literally to address email. This can be done by typing CTRL-V @. The CTRL-V itself can be entered literally by typing CTRL-V
clipped_os_Page_397_Chunk6614
398 INPUT/OUTPUT CHAP. 5 twice consecutively. After seeing a CTRL-V, the driver sets a flag saying that the next character is exempt from special processing. The LNEXT character itself is not entered in the character queue. To allow users to stop a screen image from scrolling out of view, control codes are provided to freeze the screen and restart it later. In UNIX these are STOP, (CTRL-S) and START, (CTRL-Q), respectively. They are not stored but are used to set and clear a flag in the keyboard data structure. Whenever output is attempted, the flag is inspected. If it is set, no output occurs. Usually, echoing is also sup- pressed along with program output. It is often necessary to kill a runaway program being debugged. The INTR (DEL) and QUIT (CTRL-\) characters can be used for this purpose. In UNIX, DEL sends the SIGINT signal to all the processes started up from that keyboard. Implementing DEL can be quite tricky because UNIX was designed from the be- ginning to handle multiple users at the same time. Thus in the general case, there may be many processes running on behalf of many users, and the DEL key must signal only the user’s own processes. The hard part is getting the information from the driver to the part of the system that handles signals, which, after all, has not asked for this information. CTRL-\ is similar to DEL, except that it sends the SIGQUIT signal, which forces a core dump if not caught or ignored. When either of these keys is struck, the driver should echo a carriage return and line feed and discard all accumulated input to allow for a fresh start. The default value for INTR is often CTRL-C instead of DEL, since many programs use DEL interchangeably with the backspace for editing. Another special character is EOF (CTRL-D), which in UNIX causes any pend- ing read requests for the terminal to be satisfied with whatever is available in the buffer, even if the buffer is empty. Typing CTRL-D at the start of a line causes the program to get a read of 0 bytes, which is conventionally interpreted as end-of-file and causes most programs to act the same way as they would upon seeing end-of- file on an input file. Mouse Software Most PCs have a mouse, or sometimes a trackball, which is just a mouse lying on its back. One common type of mouse has a rubber ball inside that protrudes through a hole in the bottom and rotates as the mouse is moved over a rough sur- face. As the ball rotates, it rubs against rubber rollers placed on orthogonal shafts. Motion in the east-west direction causes the shaft parallel to the y-axis to rotate; motion in the north-south direction causes the shaft parallel to the x-axis to rotate. Another popular type is the optical mouse, which is equipped with one or more light-emitting diodes and photodetectors on the bottom. Early ones had to operate on a special mousepad with a rectangular grid etched onto it so the mouse could count lines crossed. Modern optical mice have an image-processing chip in them
clipped_os_Page_398_Chunk6615
SEC. 5.6 USER INTERFACES: KEYBOARD, MOUSE, MONITOR 399 and make continuous low-resolution photos of the surface under them, looking for changes from image to image. Whenever a mouse has moved a certain minimum distance in either direction or a button is depressed or released, a message is sent to the computer. The mini- mum distance is about 0.1 mm (although it can be set in software). Some people call this unit a mickey. Mice (or occasionally, mouses) can have one, two, or three buttons, depending on the designers’ estimate of the users’ intellectual ability to keep track of more than one button. Some mice have wheels that can send addi- tional data back to the computer. Wireless mice are the same as wired mice except that instead of sending their data back to the computer over a wire, they use low-power radios, for example, using the Bluetooth standard. The message to the computer contains three items: Δx, Δy, buttons. The first item is the change in x position since the last message. Then comes the change in y position since the last message. Finally, the status of the buttons is included. The format of the message depends on the system and the number of buttons the mouse has. Usually, it takes 3 bytes. Most mice report back a maximum of 40 times/sec, so the mouse may have moved multiple mickeys since the last report. Note that the mouse indicates only changes in position, not absolute position itself. If the mouse is picked up and put down gently without causing the ball to rotate, no messages will be sent. Many GUIs distinguish between single clicks and double clicks of a mouse button. If two clicks are close enough in space (mickeys) and also close enough in time (milliseconds), a double click is signaled. The maximum for ‘‘close enough’’ is up to the software, with both parameters usually being user settable. 5.6.2 Output Software Now let us consider output software. First we will look at simple output to a text window, which is what programmers normally prefer to use. Then we will consider graphical user interfaces, which other users often prefer. Text Windows Output is simpler than input when the output is sequentially in a single font, size, and color. For the most part, the program sends characters to the current win- dow and they are displayed there. Usually, a block of characters, for example, a line, is written in one system call. Screen editors and many other sophisticated programs need to be able to update the screen in complex ways such as replacing one line in the middle of the screen. To accommodate this need, most output drivers support a series of com- mands to move the cursor, insert and delete characters or lines at the cursor, and so on. These commands are often called escape sequences. In the heyday of the dumb 25 × 80 ASCII terminal, there were hundreds of terminal types, each with its
clipped_os_Page_399_Chunk6616
400 INPUT/OUTPUT CHAP. 5 own escape sequences. As a consequence, it was difficult to write software that worked on more than one terminal type. One solution, which was introduced in Berkeley UNIX, was a terminal data- base called termcap. This software package defined a number of basic actions, such as moving the cursor to (row, column). To move the cursor to a particular lo- cation, the software, say, an editor, used a generic escape sequence which was then converted to the actual escape sequence for the terminal being written to. In this way, the editor worked on any terminal that had an entry in the termcap database. Much UNIX software still works this way, even on personal computers. Eventually, the industry saw the need for standardizing the escape sequence, so an ANSI standard was developed. Some of the values are shown in Fig. 5-32. Escape sequence Meaning ESC [ n A Move up n lines ESC [ n B Move down n lines ESC [ n C Move right n spaces ESC [ n D Move left n spaces ESC [ m ; n H Move cursor to (m,n) ESC [ s J Clear screen from cursor (0 to end, 1 from start, 2 all) ESC [ s K Clear line from cursor (0 to end, 1 from start, 2 all) ESC [ n L Inser t n lines at cursor ESC [ n M Delete n lines at cursor ESC [ n P Delete n chars at cursor ESC [ n @ Inser t n chars at cursor ESC [ n m Enable rendition n (0 = normal, 4 = bold, 5 = blinking, 7 = rev erse) ESC M Scroll the screen backward if the cursor is on the top line Figure 5-32. The ANSI escape sequences accepted by the terminal driver on out- put. ESC denotes the ASCII escape character (0x1B), and n, m, and s are optio- nal numeric parameters. Consider how these escape sequences might be used by a text editor. Suppose that the user types a command telling the editor to delete all of line 3 and then close up the gap between lines 2 and 4. The editor might send the following escape sequence over the serial line to the terminal: ESC [ 3 ; 1 H ESC [ 0 K ESC [ 1 M (where the spaces are used above only to separate the symbols; they are not trans- mitted). This sequence moves the cursor to the start of line 3, erases the entire line, and then deletes the now-empty line, causing all the lines starting at 5 to move up one line. Then what was line 4 becomes line 3; what was line 5 becomes line 4, and so on. Analogous escape sequences can be used to add text to the middle of the display. Words can be added or removed in a similar way.
clipped_os_Page_400_Chunk6617
SEC. 5.6 USER INTERFACES: KEYBOARD, MOUSE, MONITOR 401 The X Window System Nearly all UNIX systems base their user interface on the X Window System (often just called X), developed at M.I.T. as part of project Athena in the 1980s. It is very portable and runs entirely in user space. It was originally intended for con- necting a large number of remote user terminals with a central compute server, so it is logically split into client software and host software, which can potentially run on different computers. On modern personal computers, both parts can run on the same machine. On Linux systems, the popular Gnome and KDE desktop environ- ments run on top of X. When X is running on a machine, the software that collects input from the keyboard and mouse and writes output to the screen is called the X server. It has to keep track of which window is currently selected (where the mouse pointer is), so it knows which client to send any new keyboard input to. It communicates with running programs (possible over a network) called X clients. It sends them keyboard and mouse input and accepts display commands from them. It may seem odd that the X server is always inside the user’s computer while the X client may be off on a remote compute server, but just think of the X server’s main job: displaying bits on the screen, so it makes sense to be near the user. From the program’s point of view, it is a client telling the server to do things, like display text and geometric figures. The server (in the local PC) just does what it is told, as do all servers. The arrangement of client and server is shown in Fig. 5-33 for the case where the X client and X server are on different machines. But when running Gnome or KDE on a single machine, the client is just some application program using the X library talking to the X server on the same machine (but using a TCP connection over sockets, the same as it would do in the remote case). The reason it is possible to run the X Window System on top of UNIX (or an- other operating system) on a single machine or over a network is that what X really defines is the X protocol between the X client and the X server, as shown in Fig. 5-33. It does not matter whether the client and server are on the same ma- chine, separated by 100 meters over a local area network, or are thousands of kilo- meters apart and connected by the Internet. The protocol and operation of the sys- tem is identical in all cases. X is just a windowing system. It is not a complete GUI. To get a complete GUI, others layer of software are run on top of it. One layer is Xlib, which is a set of library procedures for accessing the X functionality. These procedures form the basis of the X Window System and are what we will examine below, but they are too primitive for most user programs to access directly. For example, each mouse click is reported separately, so that determining that two clicks really form a double click has to be handled above Xlib. To make programming with X easier, a toolkit consisting of the Intrinsics is supplied as part of X. This layer manages buttons, scroll bars, and other GUI
clipped_os_Page_401_Chunk6618
402 INPUT/OUTPUT CHAP. 5 Remote host Window manager Application program Motif Intrinsics Xlib X client UNIX Hardware X server UNIX Hardware Window User space Kernel space X protocol Network Figure 5-33. Clients and servers in the M.I.T. X Window System. elements, called widgets. To make a true GUI interface, with a uniform look and feel, another layer is needed (or several of them). One example is Motif, shown in Fig. 5-33, which is the basis of the Common Desktop Environment used on Solaris and other commercial UNIX systems Most applications make use of calls to Motif rather than Xlib. Gnome and KDE have a similar structure to Fig. 5-33, only with different libraries. Gnome uses the GTK+ library and KDE uses the Qt library. Whether having two GUIs is better than one is debatable. Also worth noting is that window management is not part of X itself. The de- cision to leave it out was fully intentional. Instead, a separate X client process, cal- led a window manager, controls the creation, deletion, and movement of windows on the screen. To manage windows, it sends commands to the X server telling it what to do. It often runs on the same machine as the X client, but in theory can run anywhere. This modular design, consisting of several layers and multiple programs, makes X highly portable and flexible. It has been ported to most versions of UNIX, including Solaris, all variants of BSD, AIX, Linux, and so on, making it possible for application developers to have a standard user interface for multiple platforms. It has also been ported to other operating systems. In contrast, in Win- dows, the windowing and GUI systems are mixed together in the GDI and located in the kernel, which makes them harder to maintain, and of, course, not portable. Now let us take a brief look at X as viewed from the Xlib level. When an X program starts, it opens a connection to one or more X servers—let us call them workstations even though they might be collocated on the same machine as the X
clipped_os_Page_402_Chunk6619
SEC. 5.6 USER INTERFACES: KEYBOARD, MOUSE, MONITOR 403 program itself. X considers this connection to be reliable in the sense that lost and duplicate messages are handled by the networking software and it does not have to worry about communication errors. Usually, TCP/IP is used between the client and server. Four kinds of messages go over the connection: 1. Drawing commands from the program to the workstation. 2. Replies by the workstation to program queries. 3. Keyboard, mouse, and other event announcements. 4. Error messages. Most drawing commands are sent from the program to the workstation as one- way messages. No reply is expected. The reason for this design is that when the client and server processes are on different machines, it may take a substantial period of time for the command to reach the server and be carried out. Blocking the application program during this time would slow it down unnecessarily. On the other hand, when the program needs information from the workstation, it simply has to wait until the reply comes back. Like Windows, X is highly event driven. Events flow from the workstation to the program, usually in response to some human action such as keyboard strokes, mouse movements, or a window being uncovered. Each event message is 32 bytes, with the first byte giving the event type and the next 31 bytes providing additional information. Several dozen kinds of events exist, but a program is sent only those ev ents that it has said it is willing to handle. For example, if a program does not want to hear about key releases, it is not sent any key-release events. As in Win- dows, events are queued, and programs read events from the input queue. However, unlike Windows, the operating system never calls procedures within the applica- tion program on its own. It does not even know which procedure handles which ev ent. A key concept in X is the resource. A resource is a data structure that holds certain information. Application programs create resources on workstations. Re- sources can be shared among multiple processes on the workstation. Resources tend to be short-lived and do not survive workstation reboots. Typical resources in- clude windows, fonts, colormaps (color palettes), pixmaps (bitmaps), cursors, and graphic contexts. The latter are used to associate properties with windows and are similar in concept to device contexts in Windows. A rough, incomplete skeleton of an X program is shown in Fig. 5-34. It begins by including some required headers and then declaring some variables. It then connects to the X server specified as the parameter to XOpenDisplay. Then it allo- cates a window resource and stores a handle to it in win. In practice, some ini- tialization would happen here. After that it tells the window manager that the new window exists so the window manager can manage it.
clipped_os_Page_403_Chunk6620
404 INPUT/OUTPUT CHAP. 5 #include <X11/Xlib.h> #include <X11/Xutil.h> main(int argc, char *argv[]) { Display disp; /* ser ver identifier */ Window win; /* window identifier */ GC gc; /* graphic context identifier */ XEvent event; /* storage for one event */ int running = 1; disp = XOpenDisplay("display name"); /* connect to the X server */ win = XCreateSimpleWindow(disp, ... ); /* allocate memory for new window */ XSetStandardProper ties(disp, ...); /* announces window to window mgr */ gc = XCreateGC(disp, win, 0, 0); /* create graphic context */ XSelectInput(disp, win, ButtonPressMask | KeyPressMask | ExposureMask); XMapRaised(disp, win); /* display window; send Expose event */ while (running) { XNextEvent(disp, &ev ent); /* get next event */ switch (event.type) { case Expose: ...; break; /* repaint window */ case ButtonPress: ...; break; /* process mouse click */ case Keypress: ...; break; /* process keyboard input */ } } XFreeGC(disp, gc); /* release graphic context */ XDestroyWindow(disp, win); /* deallocate window’s memor y space */ XCloseDisplay(disp); /* tear down networ k connection */ } Figure 5-34. A skeleton of an X Window application program. The call to XCreateGC creates a graphic context in which properties of the window are stored. In a more complete program, they might be initialized here. The next statement, the call to XSelectInput, tells the X server which events the program is prepared to handle. In this case it is interested in mouse clicks, keystrokes, and windows being uncovered. In practice, a real program would be interested in other events as well. Finally, the call to XMapRaised maps the new window onto the screen as the uppermost window. At this point the window be- comes visible on the screen. The main loop consists of two statements and is logically much simpler than the corresponding loop in Windows. The first statement here gets an event and the second one dispatches on the event type for processing. When some event indicates that the program has finished, running is set to 0 and the loop terminates. Before exiting, the program releases the graphic context, window, and connection.
clipped_os_Page_404_Chunk6621
SEC. 5.6 USER INTERFACES: KEYBOARD, MOUSE, MONITOR 405 It is worth mentioning that not everyone likes a GUI. Many programmers pre- fer a traditional command-line oriented interface of the type discussed in Sec. 5.6.1 above. X handles this via a client program called xterm. This program emulates a venerable VT102 intelligent terminal, complete with all the escape sequences. Thus editors such as vi and emacs and other software that uses termcap work in these windows without modification. Graphical User Interfaces Most personal computers offer a GUI (Graphical User Interface). The acronym GUI is pronounced ‘‘gooey.’’ The GUI was invented by Douglas Engelbart and his research group at the Stanford Research Institute. It was then copied by researchers at Xerox PARC. One fine day, Steve Jobs, cofounder of Apple, was touring PARC and saw a GUI on a Xerox computer and said something to the effect of ‘‘Holy mackerel. This is the future of computing.’’ The GUI gav e him the idea for a new computer, which became the Apple Lisa. The Lisa was too expensive and was a commercial failure, but its successor, the Macintosh, was a huge success. When Microsoft got a Macintosh prototype so it could develop Microsoft Office on it, it begged Apple to license the interface to all comers so it would be- come the new industry standard. (Microsoft made much more money from Office than from MS-DOS, so it was willing to abandon MS-DOS to have a better plat- form for Office.) The Apple executive in charge of the Macintosh, Jean-Louis Gasse´e, refused and Steve Jobs was no longer around to overrule him. Eventually, Microsoft got a license for elements of the interface. This formed the basis of Windows. When Windows began to catch on, Apple sued Microsoft, claiming Microsoft had exceeded the license, but the judge disagreed and Windows went on to overtake the Macintosh. If Gasse´e had agreed with the many people within Apple who also wanted to license the Macintosh software to everyone and his uncle, Apple would have become insanely rich on licensing fees alone and Win- dows would not exist now. Leaving aside touch-enabled interfaces for the moment, a GUI has four essen- tial elements, denoted by the characters WIMP. These letters stand for Windows, Icons, Menus, and Pointing device, respectively. Windows are rectangular blocks of screen area used to run programs. Icons are little symbols that can be clicked on to cause some action to happen. Menus are lists of actions from which one can be chosen. Finally, a pointing device is a mouse, trackball, or other hardware device used to move a cursor around the screen to select items. The GUI software can be implemented in either user-level code, as is done in UNIX systems, or in the operating system itself, as in the case in Windows. Input for GUI systems still uses the keyboard and mouse, but output almost al- ways goes to a special hardware board called a graphics adapter. A graphics adapter contains a special memory called video RAM that holds the images that
clipped_os_Page_405_Chunk6622
406 INPUT/OUTPUT CHAP. 5 appear on the screen. Graphics adapters often have powerful 32- or 64-bit CPUs and up to 4 GB of their own RAM, separate from the computer’s main memory. Each graphics adapter supports some number of screen sizes. Common sizes (horizontal × vertical in pixels) are 1280 × 960, 1600 × 1200, 1920 ×1080, 2560 × 1600, and 3840 × 2160. Many resolutions in practice are in the ratio of 4:3, which fits the aspect ratio of NTSC and PAL television sets and thus gives square pixels on the same monitors used for television sets. Higher resolutions are intended for wide-screen monitors whose aspect ratio matches them. At a resolution of just 1920 × 1080 (the size of full HD videos), a color display with 24 bits per pixel re- quires about 6.2 MB of RAM just to hold the image, so with 256 MB or more, the graphics adapter can hold many images at once. If the full screen is refreshed 75 times/sec, the video RAM must be capable of delivering data continuously at 445 MB/sec. Output software for GUIs is a massive topic. Many 1500-page books have been written about the Windows GUI alone (e.g., Petzold, 2013; Rector and New- comer, 1997; and Simon, 1997). Clearly, in this section, we can only scratch the surface and present a few of the underlying concepts. To make the discussion con- crete, we will describe the Win32 API, which is supported by all 32-bit versions of Windows. The output software for other GUIs is roughly comparable in a general sense, but the details are very different. The basic item on the screen is a rectangular area called a window. A win- dow’s position and size are uniquely determined by giving the coordinates (in pix- els) of two diagonally opposite corners. A window may contain a title bar, a menu bar, a tool bar, a vertical scroll bar, and a horizontal scroll bar. A typical window is shown in Fig. 5-35. Note that the Windows coordinate system puts the origin in the upper left-hand corner and has y increase downward, which is different from the Cartesian coordinates used in mathematics. When a window is created, the parameters specify whether it can be moved by the user, resized by the user, or scrolled (by dragging the thumb on the scroll bar) by the user. The main window produced by most programs can be moved, resized, and scrolled, which has enormous consequences for the way Windows programs are written. In particular, programs must be informed about changes to the size of their windows and must be prepared to redraw the contents of their windows at any time, even when they least expect it. As a consequence, Windows programs are message oriented. User actions in- volving the keyboard or mouse are captured by Windows and converted into mes- sages to the program owning the window being addressed. Each program has a message queue to which messages relating to all its windows are sent. The main loop of the program consists of fishing out the next message and processing it by calling an internal procedure for that message type. In some cases, Windows itself may call these procedures directly, bypassing the message queue. This model is quite different from the UNIX model of procedural code that makes system calls to interact with the operating system. X, however, is event oriented.
clipped_os_Page_406_Chunk6623
SEC. 5.6 USER INTERFACES: KEYBOARD, MOUSE, MONITOR 407 Thumb Title bar File Edit View Tools Options Help Client area (200, 100) (0, 0) (0, 767) Menu bar Tool bar Window Scroll bar (1023, 767) (1023, 0) 12 6 9 3 4 8 5 7 1 11 2 10 Figure 5-35. A sample window located at (200, 100) on an XGA display. To make this programming model clearer, consider the example of Fig. 5-36. Here we see the skeleton of a main program for Windows. It is not complete and does no error checking, but it shows enough detail for our purposes. It starts by in- cluding a header file, windows.h, which contains many macros, data types, con- stants, function prototypes, and other information needed by Windows programs. The main program starts with a declaration giving its name and parameters. The WINAPI macro is an instruction to the compiler to use a certain parameter-pas- sing convention and will not be of further concern to us. The first parameter, h, is an instance handle and is used to identify the program to the rest of the system. To some extent, Win32 is object oriented, which means that the system contains ob- jects (e.g., programs, files, and windows) that have some state and associated code, called methods, that operate on that state. Objects are referred to using handles, and in this case, h identifies the program. The second parameter is present only for reasons of backward compatibility. It is no longer actually used. The third parame- ter, szCmd, is a zero-terminated string containing the command line that started the program, even if it was not started from a command line. The fourth parameter,
clipped_os_Page_407_Chunk6624
408 INPUT/OUTPUT CHAP. 5 #include <windows.h> int WINAPI WinMain(HINSTANCE h, HINSTANCE, hprev, char *szCmd, int iCmdShow) { WNDCLASS wndclass; /* class object for this window */ MSG msg; /* incoming messages are stored here */ HWND hwnd; /* handle (pointer) to the window object */ /* Initialize wndclass */ wndclass.lpfnWndProc = WndProc; /* tells which procedure to call */ wndclass.lpszClassName = "Program name"; /* text for title bar */ wndclass.hIcon = LoadIcon(NULL, IDI APPLICATION); /* load program icon */ wndclass.hCursor = LoadCursor(NULL, IDC ARROW); /* load mouse cursor */ RegisterClass(&wndclass); /* tell Windows about wndclass */ hwnd = CreateWindow ( ... ) /* allocate storage for the window */ ShowWindow(hwnd, iCmdShow); /* display the window on the screen */ UpdateWindow(hwnd); /* tell the window to paint itself */ while (GetMessage(&msg, NULL, 0, 0)) { /* get message from queue */ Tr anslateMessage(&msg); /* translate the message */ DispatchMessage(&msg); /* send msg to the appropriate procedure */ } retur n(msg.wParam); } long CALLBACK WndProc(HWND hwnd, UINT message, UINT wParam, long lParam) { /* Declarations go here. */ switch (message) { case WM CREATE: ... ; retur n ... ; /* create window */ case WM PAINT: ... ; retur n ... ; /* repaint contents of window */ case WM DESTROY : ... ; retur n ... ; /* destroy window */ } retur n(DefWindowProc(hwnd, message, wParam, lParam)); /* default */ } Figure 5-36. A skeleton of a Windows main program. iCmdShow, tells whether the program’s initial window should occupy the entire screen, part of the screen, or none of the screen (task bar only). This declaration illustrates a widely used Microsoft convention called Hungar- ian notation. The name is a play on Polish notation, the postfix system invented by the Polish logician J. Lukasiewicz for representing algebraic formulas without using precedence or parentheses. Hungarian notation was invented by a Hungarian programmer at Microsoft, Charles Simonyi, and uses the first few characters of an identifier to specify the type. The allowed letters and types include c (character), w (word, now meaning an unsigned 16-bit integer), i (32-bit signed integer), l (long,
clipped_os_Page_408_Chunk6625
SEC. 5.6 USER INTERFACES: KEYBOARD, MOUSE, MONITOR 409 also a 32-bit signed integer), s (string), sz (string terminated by a zero byte), p (pointer), fn (function), and h (handle). Thus szCmd is a zero-terminated string and iCmdShow is an integer, for example. Many programmers believe that en- coding the type in variable names this way has little value and makes Windows code hard to read. Nothing analogous to this convention is present in UNIX. Every window must have an associated class object that defines its properties. In Fig. 5-36, that class object is wndclass. An object of type WNDCLASS has 10 fields, four of which are initialized in Fig. 5-36. In an actual program, the other six would be initialized as well. The most important field is lpfnWndProc, which is a long (i.e., 32-bit) pointer to the function that handles the messages directed to this window. The other fields initialized here tell which name and icon to use in the title bar, and which symbol to use for the mouse cursor. After wndclass has been initialized, RegisterClass is called to pass it to Win- dows. In particular, after this call Windows knows which procedure to call when various events occur that do not go through the message queue. The next call, Cre- ateWindow, allocates memory for the window’s data structure and returns a handle for referencing it later. The program then makes two more calls in a row, to put the window’s outline on the screen, and finally fill it in completely. At this point we come to the program’s main loop, which consists of getting a message, having certain translations done to it, and then passing it back to Win- dows to have Windows invoke WndProc to process it. To answer the question of whether this whole mechanism could have been made simpler, the answer is yes, but it was done this way for historical reasons and we are now stuck with it. Following the main program is the procedure WndProc, which handles the various messages that can be sent to the window. The use of CALLBACK here, like WINAPI above, specifies the calling sequence to use for parameters. The first pa- rameter is the handle of the window to use. The second parameter is the message type. The third and fourth parameters can be used to provide additional infor- mation when needed. Message types WM CREATE and WM DESTROY are sent at the start and end of the program, respectively. They giv e the program the opportunity, for example, to allocate memory for data structures and then return it. The third message type, WM PAINT, is an instruction to the program to fill in the window. It is called not only when the window is first drawn, but often during program execution as well. In contrast to text-based systems, in Windows a pro- gram cannot assume that whatever it draws on the screen will stay there until it re- moves it. Other windows can be dragged on top of this one, menus can be pulled down over it, dialog boxes and tool tips can cover part of it, and so on. When these items are removed, the window has to be redrawn. The way Windows tells a pro- gram to redraw a window is to send it a WM PAINT message. As a friendly ges- ture, it also provides information about what part of the window has been overwrit- ten, in case it is easier or faster to regenerate that part of the window instead of redrawing the whole thing from scratch.
clipped_os_Page_409_Chunk6626
410 INPUT/OUTPUT CHAP. 5 There are two ways Windows can get a program to do something. One way is to post a message to its message queue. This method is used for keyboard input, mouse input, and timers that have expired. The other way, sending a message to the window, inv olves having Windows directly call WndProc itself. This method is used for all other events. Since Windows is notified when a message is fully proc- essed, it can refrain from making a new call until the previous one is finished. In this way race conditions are avoided. There are many more message types. To avoid erratic behavior should an un- expected message arrive, the program should call DefWindowProc at the end of WndProc to let the default handler take care of the other cases. In summary, a Windows program normally creates one or more windows with a class object for each one. Associated with each program is a message queue and a set of handler procedures. Ultimately, the program’s behavior is driven by the in- coming events, which are processed by the handler procedures. This is a very dif- ferent model of the world than the more procedural view that UNIX takes. Drawing to the screen is handled by a package consisting of hundreds of pro- cedures that are bundled together to form the GDI (Graphics Device Interface). It can handle text and graphics and is designed to be platform and device indepen- dent. Before a program can draw (i.e., paint) in a window, it needs to acquire a de- vice context, which is an internal data structure containing properties of the win- dow, such as the font, text color, background color, and so on. Most GDI calls use the device context, either for drawing or for getting or setting the properties. Various ways exist to acquire the device context. A simple example of its acquisition and use is hdc = GetDC(hwnd); Te xtOut(hdc, x, y, psText, iLength); ReleaseDC(hwnd, hdc); The first statement gets a handle to a device content, hdc. The second one uses the device context to write a line of text on the screen, specifying the (x, y) coordinates of where the string starts, a pointer to the string itself, and its length. The third call releases the device context to indicate that the program is through drawing for the moment. Note that hdc is used in a way analogous to a UNIX file descriptor. Also note that ReleaseDC contains redundant information (the use of hdc uniquely specifies a window). The use of redundant information that has no actual value is common in Windows. Another interesting note is that when hdc is acquired in this way, the program can write only in the client area of the window, not in the title bar and other parts of it. Internally, in the device context’s data structure, a clipping region is main- tained. Any drawing outside the clipping region is ignored. However, there is an- other way to acquire a device context, GetWindowDC, which sets the clipping re- gion to the entire window. Other calls restrict the clipping region in other ways. Having multiple calls that do almost the same thing is characteristic of Windows.
clipped_os_Page_410_Chunk6627
SEC. 5.6 USER INTERFACES: KEYBOARD, MOUSE, MONITOR 411 A complete treatment of the GDI is out of the question here. For the interested reader, the references cited above provide additional information. Nevertheless, given how important it is, a few words about the GDI are probably worthwhile. GDI has various procedure calls to get and release device contexts, obtain infor- mation about device contexts, get and set device context attributes (e.g., the back- ground color), manipulate GDI objects such as pens, brushes, and fonts, each of which has its own attributes. Finally, of course, there are a large number of GDI calls to actually draw on the screen. The drawing procedures fall into four categories: drawing lines and curves, drawing filled areas, managing bitmaps, and displaying text. We saw an example of drawing text above, so let us take a quick look at one of the others. The call Rectangle(hdc, xleft, ytop, xright, ybottom); draws a filled rectangle whose corners are (xleft, ytop) and (xright, ybottom). For example, Rectangle(hdc, 2, 1, 6, 4); will draw the rectangle shown in Fig. 5-37. The line width and color and fill color are taken from the device context. Other GDI calls are similar in flavor. 0 0 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 Figure 5-37. An example rectangle drawn using Rectangle. Each box represents one pixel. Bitmaps The GDI procedures are examples of vector graphics. They are used to place geometric figures and text on the screen. They can be scaled easily to larger or smaller screens (provided the number of pixels on the screen is the same). They are also relatively device independent. A collection of calls to GDI procedures can be assembled in a file that can describe a complex drawing. Such a file is called a
clipped_os_Page_411_Chunk6628
412 INPUT/OUTPUT CHAP. 5 Windows metafile and is widely used to transmit drawings from one Windows pro- gram to another. Such files have extension .wmf. Many Windows programs allow the user to copy (part of) a drawing and put it on the Windows clipboard. The user can then go to another program and paste the contents of the clipboard into another document. One way of doing this is for the first program to represent the drawing as a Windows metafile and put it on the clip- board in .wmf format. Other ways also exist. Not all the images that computers manipulate can be generated using vector graphics. Photographs and videos, for example, do not use vector graphics. In- stead, these items are scanned in by overlaying a grid on the image. The average red, green, and blue values of each grid square are then sampled and saved as the value of one pixel. Such a file is called a bitmap. There are extensive facilities in Windows for manipulating bitmaps. Another use for bitmaps is for text. One way to represent a particular character in some font is as a small bitmap. Adding text to the screen then becomes a matter of moving bitmaps. One general way to use bitmaps is through a procedure called BitBlt. It is cal- led as follows: BitBlt(dsthdc, dx, dy, wid, ht, srchdc, sx, sy, rasterop); In its simplest form, it copies a bitmap from a rectangle in one window to a rectan- gle in another window (or the same one). The first three parameters specify the destination window and position. Then come the width and height. Next come the source window and position. Note that each window has its own coordinate sys- tem, with (0, 0) in the upper left-hand corner of the window. The last parameter will be described below. The effect of BitBlt(hdc2, 1, 2, 5, 7, hdc1, 2, 2, SRCCOPY); is shown in Fig. 5-38. Notice carefully that the entire 5 × 7 area of the letter A has been copied, including the background color. BitBlt can do more than just copy bitmaps. The last parameter gives the possi- bility of performing Boolean operations to combine the source bitmap and the destination bitmap. For example, the source can be ORed into the destination to merge with it. It can also be EXCLUSIVE ORed into it, which maintains the char- acteristics of both source and destination. A problem with bitmaps is that they do not scale. A character that is in a box of 8 × 12 on a display of 640 × 480 will look reasonable. However, if this bitmap is copied to a printed page at 1200 dots/inch, which is 10,200 bits × 13,200 bits, the character width (8 pixels) will be 8/1200 inch or 0.17 mm. In addition, copying between devices with different color properties or between monochrome and color does not work well. For this reason, Windows also supports a data structure called a DIB (Device Independent Bitmap). Files using this format use the extension .bmp. These files
clipped_os_Page_412_Chunk6629
SEC. 5.6 USER INTERFACES: KEYBOARD, MOUSE, MONITOR 413 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 Window 1 Window 2 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 0 2 4 6 8 Window 1 Window 2 (a) (b) Figure 5-38. Copying bitmaps using BitBlt. (a) Before. (b) After. have file and information headers and a color table before the pixels. This infor- mation makes it easier to move bitmaps between dissimilar devices. Fonts In versions of Windows before 3.1, characters were represented as bitmaps and copied onto the screen or printer using BitBlt. The problem with that, as we just saw, is that a bitmap that makes sense on the screen is too small for the printer. Also, a different bitmap is needed for each character in each size. In other words, given the bitmap for A in 10-point type, there is no way to compute it for 12-point type. Because every character of every font might be needed for sizes ranging from 4 point to 120 point, a vast number of bitmaps were needed. The whole system was just too cumbersome for text. The solution was the introduction of TrueType fonts, which are not bitmaps but outlines of the characters. Each TrueType character is defined by a sequence of points around its perimeter. All the points are relative to the (0, 0) origin. Using this system, it is easy to scale the characters up or down. All that has to be done is to multiply each coordinate by the same scale factor. In this way, a TrueType char- acter can be scaled up or down to any point size, even fractional point sizes. Once at the proper size, the points can be connected using the well-known follow-the- dots algorithm taught in kindergarten (note that modern kindergartens use splines for smoother results). After the outline has been completed, the character can be filled in. An example of some characters scaled to three different point sizes is given in Fig. 5-39. Once the filled character is available in mathematical form, it can be rasterized, that is, converted to a bitmap at whatever resolution is desired. By first scaling and then rasterizing, we can be sure that the characters displayed on the screen or printed on the printer will be as close as possible, differing only in quantization
clipped_os_Page_413_Chunk6630
414 INPUT/OUTPUT CHAP. 5 20 pt: 53 pt: 81 pt: Figure 5-39. Some examples of character outlines at different point sizes. error. To improve the quality still more, it is possible to embed hints in each char- acter telling how to do the rasterization. For example, both serifs on the top of the letter T should be identical, something that might not otherwise be the case due to roundoff error. Hints improve the final appearance. Touch Screens More and more the screen is used as an input device also. Especially on smart- phones, tablets and other ultra-portable devices it is convenient to tap and swipe aw ay at the screen with your finger (or a stylus). The user experience is different and more intuitive than with a mouse-like device, since the user interacts directly with the objects on the screen. Research has shown that even orangutans and other primates like little children are capable of operating touch-based devices. A touch device is not necessarily a screen. Touch devices fall into two cate- gories: opaque and transparent. A typical opaque touch device is the touchpad on a notebook computer. An example of a transparent device is the touch screen on a smartphone or tablet. In this section, however, we limit ourselves to touch screens. Like many things that have come into fashion in the computer industry, touch screens are not exactly new. As early as 1965, E.A. Johnson of the British Royal Radar Establishment described a (capacitive) touch display that, while crude, served as precursor of the displays we find today. Most modern touch screens are either resistive or capacitive. Resistive screens have a flexible plastic surface on top. The plastic in itself is nothing too special, except that is more scratch resistant than your garden variety
clipped_os_Page_414_Chunk6631
SEC. 5.6 USER INTERFACES: KEYBOARD, MOUSE, MONITOR 415 plastic. However, a thin film of ITO (Indium Tin Oxide) or some similar con- ducive material) is printed in thin lines onto the surface’s underside. Beneath it, but not quite touching it, is a second surface also coated with a layer of ITO. On the top surface, the charge runs in the vertical direction and there are conductive con- nections at the top and bottom. In the bottom layer the charge runs horizontally and there are connections on the left and right. When you touch the screen, you dent the plastic so that the top layer of ITO touches the bottom layer. To find out the exact position of the finger or stylus touching it, all you need to do is measure the resistance in both directions at all the horizontal positions of the bottom and all the vertical positions of the top layer. Capacitive Screens have two hard surfaces, typically glass, each coated with ITO. A typical configuration is to have ITO added to each surface in parallel lines, where the lines in the top layer are perpendicular to those in the bottom layer. For instance, the top layer may be coated in thin lines in a vertical direction, while the bottom layer has a similarly striped pattern in the horizontal direction. The two charged surfaces, separated by air, form a grid of really small capacitors. Voltages are applied alternately to the horizontal and vertical lines, while the voltage values, which are affected by the capacitance of each intersection, are read out on the other ones. When you put your finger onto the screen, you change the local capacitance. By very accurately measuring the miniscule voltage changes everywhere, it is pos- sible to discover the location of the finger on the screen. This operation is repeated many times per second with the coordinates touched fed to the device driver as a stream of (x, y) pairs. Further processing, such as determining whether pointing, pinching, expanding, or swiping is taking place is done by the operating system. What is nice about resistive screens is that the pressure determines the outcome of the measurements. In other words, it will work even if you are wearing gloves in cold weather. This is not true of capacitive screens, unless you wear special gloves. For instance, you can sew a conductive thread (like silver-plated nylon) through the fingertips of the gloves, or if you are not a needling person, buy them ready-made. Alternatively, you cut off the tips of your gloves and be done in 10 seconds. What is not so nice about resistive screens is that they typically cannot support multitouch, a technique that detects multiple touches at the same time. It allows you to manipulate objects on the screen with two or more fingers. People (and per- haps also orangutans) like multitouch because it enables them to use pinch-and-ex- pand gestures with two fingers to enlarge or shrink a picture or document. Imagine that the two fingers are at (3, 3) and (8, 8). As a result, the resistive screen may notice a change in resistance on the x = 3 and x = 8 vertical lines, and the y = 3 and y = 8 horizontal lines. Now consider a different scenario with the fingers at (3, 8) and (8, 3), which are the opposite corners of the rectangle whose corners are (3, 3), (8, 3), (8, 8), and (3, 8). The resistance in precisely the same lines has changed, so the software has no way of telling which of the two scenarios holds. This problem is called ghosting. Because capacitive screens send a stream of (x, y) coordinates, they are more adept at supporting multitouch.
clipped_os_Page_415_Chunk6632
416 INPUT/OUTPUT CHAP. 5 Manipulating a touch screen with just a single finger is still fairly WIMPy— you just replace the mouse pointer with your stylus or index finger. Multitouch is a bit more complicated. Touching the screen with fiv e fingers is like pushing fiv e mouse pointers across the screen at the same time and clearly changes things for the window manager. Multitouch screens have become ubiquitous and increasingly sensitive and accurate. Nevertheless, it is unclear whether the Five Point Palm Exploding Heart Technique has any effect on the CPU. 5.7 THIN CLIENTS Over the years, the main computing paradigm has oscillated between cent- ralized and decentralized computing. The first computers, such as the ENIAC, were, in fact, personal computers, albeit large ones, because only one person could use one at once. Then came timesharing systems, in which many remote users at simple terminals shared a big central computer. Next came the PC era, in which the users had their own personal computers again. While the decentralized PC model has advantages, it also has some severe disadvantages that are only beginning to be taken seriously. Probably the biggest problem is that each PC has a large hard disk and complex software that must be maintained. For example, when a new release of the operating system comes out, a great deal of work has to be done to perform the upgrade on each machine sepa- rately. At most corporations, the labor costs of doing this kind of software mainte- nance dwarf the actual hardware and software costs. For home users, the labor is technically free, but few people are capable of doing it correctly and fewer still enjoy doing it. With a centralized system, only one or a few machines have to be updated and those machines have a staff of experts to do the work. A related issue is that users should make regular backups of their gigabyte file systems, but few of them do. When disaster strikes, a great deal of moaning and wringing of hands tends to follow. With a centralized system, backups can be made ev ery night by automated tape robots. Another advantage is that resource sharing is easier with centralized systems. A system with 256 remote users, each with 256 MB of RAM, will have most of that RAM idle most of the time. With a centralized system with 64 GB of RAM, it never happens that some user temporarily needs a lot of RAM but cannot get it be- cause it is on someone else’s PC. The same argument holds for disk space and other resources. Finally, we are starting to see a shift from PC-centric computing to Web-cen- tric computing. One area where this shift is very far along is email. People used to get their email delivered to their home machine and read it there. Nowadays, many people log into Gmail, Hotmail, or Yahoo and read their mail there. The next step is for people to log into other Websites to do word processing, build spreadsheets,
clipped_os_Page_416_Chunk6633
SEC. 5.7 THIN CLIENTS 417 and other things that used to require PC software. It is even possible that eventually the only software people run on their PC is a Web browser, and maybe not even that. It is probably a fair conclusion to say that most users want high-performance interactive computing but do not really want to administer a computer. This has led researchers to reexamine timesharing using dumb terminals (now politely called thin clients) that meet modern terminal expectations. X was a step in this direc- tion and dedicated X terminals were popular for a little while but they fell out of favor because they cost as much as PCs, could do less, and still needed some soft- ware maintenance. The holy grail would be a high-performance interactive com- puting system in which the user machines had no software at all. Interestingly enough, this goal is achievable. One of the best known thin clients is the Chromebook. It is pushed actively by Google, but with a wide variety of manufacturers providing a wide variety of models. The notebook runs ChromeOS which is based on Linux and the Chrome Web browser and is assumed to be online all the time. Most other software is hosted on the Web in the form of Web Apps, making the software stack on the Chromebook itself considerably thinner than in most traditional notebooks. On the other hand, a system that runs a full Linux stack, and a Chrome browser, it is not exactly anorexic either. 5.8 POWER MANAGEMENT The first general-purpose electronic computer, the ENIAC, had 18,000 vacuum tubes and consumed 140,000 watts of power. As a result, it ran up a nontrivial electricity bill. After the invention of the transistor, power usage dropped dramati- cally and the computer industry lost interest in power requirements. However, now- adays power management is back in the spotlight for several reasons, and the oper- ating system is playing a role here. Let us start with desktop PCs. A desktop PC often has a 200-watt power sup- ply (which is typically 85% efficient, that is, loses 15% of the incoming energy to heat). If 100 million of these machines are turned on at once worldwide, together they use 20,000 megawatts of electricity. This is the total output of 20 aver- age-sized nuclear power plants. If power requirements could be cut in half, we could get rid of 10 nuclear power plants. From an environmental point of view, get- ting rid of 10 nuclear power plants (or an equivalent number of fossil-fuel plants) is a big win and well worth pursuing. The other place where power is a big issue is on battery-powered computers, including notebooks, handhelds, and Webpads, among others. The heart of the problem is that the batteries cannot hold enough charge to last very long, a few hours at most. Furthermore, despite massive research efforts by battery companies, computer companies, and consumer electronics companies, progress is glacial. To
clipped_os_Page_417_Chunk6634
418 INPUT/OUTPUT CHAP. 5 an industry used to a doubling of performance every 18 months (Moore’s law), having no progress at all seems like a violation of the laws of physics, but that is the current situation. As a consequence, making computers use less energy so existing batteries last longer is high on everyone’s agenda. The operating system plays a major role here, as we will see below. At the lowest level, hardware vendors are trying to make their electronics more energy efficient. Techniques used include reducing transistor size, employing dy- namic voltage scaling, using low-swing and adiabatic buses, and similar techni- ques. These are outside the scope of this book, but interested readers can find a good survey in a paper by Venkatachalam and Franz (2005). There are two general approaches to reducing energy consumption. The first one is for the operating system to turn off parts of the computer (mostly I/O de- vices) when they are not in use because a device that is off uses little or no energy. The second one is for the application program to use less energy, possibly degrad- ing the quality of the user experience, in order to stretch out battery time. We will look at each of these approaches in turn, but first we will say a little bit about hard- ware design with respect to power usage. 5.8.1 Hardware Issues Batteries come in two general types: disposable and rechargeable. Disposable batteries (most commonly AAA, AA, and D cells) can be used to run handheld de- vices, but do not have enough energy to power notebook computers with large bright screens. A rechargeable battery, in contrast, can store enough energy to power a notebook for a few hours. Nickel cadmium batteries used to dominate here, but they gav e way to nickel metal hydride batteries, which last longer and do not pollute the environment quite as badly when they are eventually discarded. Lithium ion batteries are even better, and may be recharged without first being fully drained, but their capacities are also severely limited. The general approach most computer vendors take to battery conservation is to design the CPU, memory, and I/O devices to have multiple states: on, sleeping, hibernating, and off. To use the device, it must be on. When the device will not be needed for a short time, it can be put to sleep, which reduces energy consumption. When it is not expected to be needed for a longer interval, it can be made to hiber- nate, which reduces energy consumption even more. The trade-off here is that get- ting a device out of hibernation often takes more time and energy than getting it out of sleep state. Finally, when a device is off, it does nothing and consumes no power. Not all devices have all these states, but when they do, it is up to the oper- ating system to manage the state transitions at the right moments. Some computers have two or even three power buttons. One of these may put the whole computer in sleep state, from which it can be awakened quickly by typ- ing a character or moving the mouse. Another may put the computer into hiberna- tion, from which wakeup takes far longer. In both cases, these buttons typically do
clipped_os_Page_418_Chunk6635
SEC. 5.8 POWER MANAGEMENT 419 nothing except send a signal to the operating system, which does the rest in soft- ware. In some countries, electrical devices must, by law, hav e a mechanical power switch that breaks a circuit and removes power from the device, for safety reasons. To comply with this law, another switch may be needed. Power management brings up a number of questions that the operating system has to deal with. Many of them relate to resource hibernation—selectively and temporarily turning off devices, or at least reducing their power consumption when they are idle. Questions that must be answered include these: Which devices can be controlled? Are they on/off, or are there intermediate states? How much power is saved in the low-power states? Is energy expended to restart the device? Must some context be saved when going to a low-power state? How long does it take to go back to full power? Of course, the answers to these questions vary from device to device, so the operating system must be able to deal with a range of possibilities. Various researchers have examined notebook computers to see where the pow- er goes. Li et al. (1994) measured various workloads and came to the conclusions shown in Fig. 5-40. Lorch and Smith (1998) made measurements on other ma- chines and came to the conclusions shown in Fig. 5-40. Weiser et al. (1994) also made measurements but did not publish the numerical values. They simply stated that the top three energy sinks were the display, hard disk, and CPU, in that order. While these numbers do not agree closely, possibly because the different brands of computers measured indeed have different energy requirements, it seems clear that the display, hard disk, and CPU are obvious targets for saving energy. On devices like smartphones, there may be other power drains, like the radio and GPS. Al- though we focus on displays, disks, CPUs and memory in this section, the princ- ples are the same for other peripherals. Device Li et al. (1994) Lorch and Smith (1998) Display 68% 39% CPU 12% 18% Hard disk 20% 12% Modem 6% Sound 2% Memor y 0.5% 1% Other 22% Figure 5-40. Power consumption of various parts of a notebook computer. 5.8.2 Operating System Issues The operating system plays a key role in energy management. It controls all the devices, so it must decide what to shut down and when to shut it down. If it shuts down a device and that device is needed again quickly, there may be an
clipped_os_Page_419_Chunk6636
420 INPUT/OUTPUT CHAP. 5 annoying delay while it is restarted. On the other hand, if it waits too long to shut down a device, energy is wasted for nothing. The trick is to find algorithms and heuristics that let the operating system make good decisions about what to shut down and when. The trouble is that ‘‘good’’ is highly subjective. One user may find it acceptable that after 30 seconds of not using the computer it takes 2 seconds for it to respond to a keystroke. Another user may swear a blue streak under the same conditions. In the absence of audio input, the computer cannot tell these users apart. The Display Let us now look at the big spenders of the energy budget to see what can be done about each one. One of the biggest items in everyone’s energy budget is the display. To get a bright sharp image, the screen must be backlit and that takes sub- stantial energy. Many operating systems attempt to save energy here by shutting down the display when there has been no activity for some number of minutes. Often the user can decide what the shutdown interval is, thus pushing the trade-off between frequent blanking of the screen and draining the battery quickly back to the user (who probably really does not want it). Turning off the display is a sleep state because it can be regenerated (from the video RAM) almost instantaneously when any key is struck or the pointing device is moved. One possible improvement was proposed by Flinn and Satyanarayanan (2004). They suggested having the display consist of some number of zones that can be in- dependently powered up or down. In Fig. 5-41, we depict 16 zones, using dashed lines to separate them. When the cursor is in window 2, as shown in Fig. 5-41(a), only the four zones in the lower righthand corner have to be lit up. The other 12 can be dark, saving 3/4 of the screen power. When the user moves the cursor to window 1, the zones for window 2 can be darkened and the zones behind window 1 can be turned on. However, because win- dow 1 straddles 9 zones, more power is needed. If the window manager can sense what is happening, it can automatically move window 1 to fit into four zones, with a kind of snap-to-zone action, as shown in Fig. 5-41(b). To achieve this reduction from 9/16 of full power to 4/16 of full power, the window manager has to under- stand power management or be capable of accepting instructions from some other piece of the system that does. Even more sophisticated would be the ability to par- tially illuminate a window that was not completely full (e.g., a window containing short lines of text could be kept dark on the right-hand side). The Hard Disk Another major villain is the hard disk. It takes substantial energy to keep it spinning at high speed, even if there are no accesses. Many computers, especially notebooks, spin the disk down after a certain number of minutes of being idle.
clipped_os_Page_420_Chunk6637
SEC. 5.8 POWER MANAGEMENT 421 Window 1 Window 2 Window 1 Window 2 Zone (a) (b) Figure 5-41. The use of zones for backlighting the display. (a) When window 2 is selected, it is not moved. (b) When window 1 is selected, it moves to reduce the number of zones illuminated. When it is next needed, it is spun up again. Unfortunately, a stopped disk is hiber- nating rather than sleeping because it takes quite a few seconds to spin it up again, which causes noticeable delays for the user. In addition, restarting the disk consumes considerable energy. As a conse- quence, every disk has a characteristic time, Td, that is its break-even point, often in the range 5 to 15 sec. Suppose that the next disk access is expected to come some time t in the future. If t < Td, it takes less energy to keep the disk spinning rather than spin it down and then spin it up so quickly. If t > Td, the energy saved makes it worth spinning the disk down and then up again much later. If a good prediction could be made (e.g., based on past access patterns), the operating sys- tem could make good shutdown predictions and save energy. In practice, most sys- tems are conservative and stop the disk only after a few minutes of inactivity. Another way to save disk energy is to have a substantial disk cache in RAM. If a needed block is in the cache, an idle disk does not have to be restarted to sat- isfy the read. Similarly, if a write to the disk can be buffered in the cache, a stop- ped disk does not have to restarted just to handle the write. The disk can remain off until the cache fills up or a read miss happens. Another way to avoid unnecessary disk starts is for the operating system to keep running programs informed about the disk state by sending them messages or signals. Some programs have discretionary writes that can be skipped or delayed. For example, a word processor may be set up to write the file being edited to disk ev ery few minutes. If at the moment it would normally write the file out, the word processor knows that the disk is off, it can delay this write until it is turned on. The CPU The CPU can also be managed to save energy. A notebook CPU can be put to sleep in software, reducing power usage to almost zero. The only thing it can do in this state is wake up when an interrupt occurs. Therefore, whenever the CPU goes idle, either waiting for I/O or because there is no work to do, it goes to sleep.
clipped_os_Page_421_Chunk6638
422 INPUT/OUTPUT CHAP. 5 On many computers, there is a relationship between CPU voltage, clock cycle, and power usage. The CPU voltage can often be reduced in software, which saves energy but also reduces the clock cycle (approximately linearly). Since power con- sumed is proportional to the square of the voltage, cutting the voltage in half makes the CPU about half as fast but at 1/4 the power. This property can be exploited for programs with well-defined deadlines, such as multimedia viewers that have to decompress and display a frame every 40 msec, but go idle if they do it faster. Suppose that a CPU uses x joules while running full blast for 40 msec and x/4 joules running at half speed. If a multimedia viewer can decompress and display a frame in 20 msec, the operating system can run at full power for 20 msec and then shut down for 20 msec for a total energy usage of x/2 joules. Alternatively, it can run at half power and just make the deadline, but use only x/4 joules instead. A comparison of running at full speed and full power for some time interval and at half speed and one-quarter power for twice as long is shown in Fig. 5-42. In both cases the same work is done, but in Fig. 5-42(b) only half the energy is consumed doing it. 1.00 0.75 0.50 0.25 0 0 T/2 T Time Power (a) 1.00 0.75 0.50 0.25 0 0 T/2 T Time Power (b) Figure 5-42. (a) Running at full clock speed. (b) Cutting voltage by two cuts clock speed by two and power consumption by four. In a similar vein, if a user is typing at 1 char/sec, but the work needed to proc- ess the character takes 100 msec, it is better for the operating system to detect the long idle periods and slow the CPU down by a factor of 10. In short, running slowly is more energy efficient than running quickly. Interestingly, scaling down the CPU cores does not always imply a reduction in performance. Hruby et al. (2013) show that sometimes the performance of the network stack improves with slower cores. The explanation is that a core can be too fast for its own good. For instance, imagine a CPU with several fast cores, where one core is responsible for the transmission of network packets on behalf of a pro- ducer running on another core. The producer and the network stack communicate directly via shared memory and they both run on dedicated cores. The producer performs a fair amount of computation and cannot quite keep up with the core of the network stack. On a typical run, the network will transmit all it has to transmit and poll the shared memory for some amount of time to see if there is really no
clipped_os_Page_422_Chunk6639
SEC. 5.8 POWER MANAGEMENT 423 more data to transmit. Finally, it will give up and go to sleep, because continuous polling is very bad for power consumption. Shortly after, the producer provides more data, but now the network stack is fast sleep. Waking up the stack takes time and slows down the throughput. One possible solution is never to sleep, but this is not attractive either because doing so would increase the power consumption—ex- actly the opposite of what we are trying to achieve. A much more attractive solu- tion is to run the network stack on a slower core, so that it is constantly busy (and thus never sleeps), while still reducing the power consumption. If the network core is slowed down carefully, its performance will be better than a configuration where all cores are blazingly fast. The Memory Tw o possible options exist for saving energy with the memory. First, the cache can be flushed and then switched off. It can always be reloaded from main memo- ry with no loss of information. The reload can be done dynamically and quickly, so turning off the cache is entering a sleep state. A more drastic option is to write the contents of main memory to the disk, then switch off the main memory itself. This approach is hibernation, since virtually all power can be cut to memory at the expense of a substantial reload time, especially if the disk is off, too. When the memory is cut off, the CPU either has to be shut off as well or has to execute out of ROM. If the CPU is off, the interrupt that wakes it up has to cause it to jump to code in ROM so the memory can be reloaded before being used. Despite all the overhead, switching off the memory for long periods of time (e.g., hours) may be worth it if restarting in a few seconds is considered much more desirable than rebooting the operating system from disk, which often takes a minute or more. Wireless Communication Increasingly many portable computers have a wireless connection to the out- side world (e.g., the Internet). The radio transmitter and receiver required are often first-class power hogs. In particular, if the radio receiver is always on in order to listen for incoming email, the battery may drain fairly quickly. On the other hand, if the radio is switched off after, say, 1 minute of being idle, incoming messages may be missed, which is clearly undesirable. One efficient solution to this problem has been proposed by Kravets and Krish- nan (1998). The heart of their solution exploits the fact that mobile computers communicate with fixed base stations that have large memories and disks and no power constraints. What they propose is to have the mobile computer send a mes- sage to the base station when it is about to turn off the radio. From that time on, the base station buffers incoming messages on its disk. The mobile computer may in- dicate explicitly how long it is planning to sleep, or simply inform the base station
clipped_os_Page_423_Chunk6640
424 INPUT/OUTPUT CHAP. 5 when it switches on the radio again. At that point any accumulated messages can be sent to it. Outgoing messages that are generated while the radio is off are buffered on the mobile computer. If the buffer threatens to fill up, the radio is turned on and the queue transmitted to the base station. When should the radio be switched off? One possibility is to let the user or the application program decide. Another is to turn it off after some number of seconds of idle time. When should it be switched on again? Again, the user or program could decide, or it could be switched on periodically to check for inbound traffic and transmit any queued messages. Of course, it also should be switched on when the output buffer is close to full. Various other heuristics are possible. An example of a wireless technology supporting such a power-management scheme can be found in 802.11 (‘‘WiFi’’) networks. In 802.11, a mobile computer can notify the access point that it is going to sleep but it will wake up before the base station sends the next beacon frame. The access point sends out these frames periodically. At that point the access point can tell the mobile computer that it has data pending. If there is no such data, the mobile computer can sleep again until the next beacon frame. Thermal Management A somewhat different, but still energy-related issue, is thermal management. Modern CPUs get extremely hot due to their high speed. Desktop machines nor- mally have an internal electric fan to blow the hot air out of the chassis. Since reducing power consumption is usually not a driving issue with desktop machines, the fan is usually on all the time. With notebooks, the situation is different. The operating system has to monitor the temperature continuously. When it gets close to the maximum allowable tem- perature, the operating system has a choice. It can switch on the fan, which makes noise and consumes power. Alternatively, it can reduce power consumption by reducing the backlighting of the screen, slowing down the CPU, being more aggressive about spinning down the disk, and so on. Some input from the user may be valuable as a guide. For example, a user could specify in advance that the noise of the fan is objectionable, so the operating system would reduce power consumption instead. Battery Management In ye olde days, a battery just provided current until it was fully drained, at which time it stopped. Not any more. Mobile devices now use smart batteries now, which can communicate with the operating system. Upon request from the operat- ing system, they can report on things like their maximum voltage, current voltage, maximum charge, current charge, maximum drain rate, current drain rate, and
clipped_os_Page_424_Chunk6641
SEC. 5.8 POWER MANAGEMENT 425 more. Most mobile devices have programs that can be run to query and display all these parameters. Smart batteries can also be instructed to change various opera- tional parameters under control of the operating system. Some notebooks have multiple batteries. When the operating system detects that one battery is about to go, it has to arrange for a graceful cutover to the next one, without causing any glitches during the transition. When the final battery is on its last legs, it is up to the operating system to warn the user and then cause an orderly shutdown, for example, making sure that the file system is not corrupted. Driver Interface Several operating systems have an elaborate mechanism for doing power man- agement called ACPI (Advanced Configuration and Power Interface). The op- erating system can send any conformant driver commands asking it to report on the capabilities of its devices and their current states. This feature is especially impor- tant when combined with plug and play because just after it is booted, the operat- ing system does not even know what devices are present, let alone their properties with respect to energy consumption or power manageability. It can also send commands to drivers instructing them to cut their power levels (based on the capabilities that it learned earlier, of course). There is also some traf- fic the other way. In particular, when a device such as a keyboard or a mouse detects activity after a period of idleness, this is a signal to the system to go back to (near) normal operation. 5.8.3 Application Program Issues So far we have looked at ways the operating system can reduce energy usage by various kinds of devices. But there is another approach as well: tell the pro- grams to use less energy, even if this means providing a poorer user experience (better a poorer experience than no experience when the battery dies and the lights go out). Typically, this information is passed on when the battery charge is below some threshold. It is then up to the programs to decide between degrading perfor- mance to lengthen battery life or to maintain performance and risk running out of energy. One question that comes up here asks how a program can degrade its perfor- mance to save energy. This question has been studied by Flinn and Satya- narayanan (2004). They provided four examples of how degraded performance can save energy. We will now look at these. In this study, information is presented to the user in various forms. When no degradation is present, the best possible information is presented. When degrada- tion is present, the fidelity (accuracy) of the information presented to the user is worse than what it could have been. We will see examples of this shortly.
clipped_os_Page_425_Chunk6642
426 INPUT/OUTPUT CHAP. 5 In order to measure the energy usage, Flinn and Satyanarayanan devised a soft- ware tool called PowerScope. What it does is provide a power-usage profile of a program. To use it, a computer must be hooked up to an external power supply through a software-controlled digital multimeter. Using the multimeter, software is able to read out the number of milliamperes coming in from the power supply and thus determine the instantaneous power being consumed by the computer. What PowerScope does is periodically sample the program counter and the power usage and write these data to a file. After the program has terminated, the file is analyzed to give the energy usage of each procedure. These measurements formed the basis of their observations. Hardware energy-saving measures were also used and formed the baseline against which the degraded performance was measured. The first program measured was a video player. In undegraded mode, it plays 30 frames/sec in full resolution and in color. One form of degradation is to aban- don the color information and display the video in black and white. Another form of degradation is to reduce the frame rate, which leads to flicker and gives the movie a jerky quality. Still another form of degradation is to reduce the number of pixels in both directions, either by lowering the spatial resolution or making the displayed image smaller. Measures of this type saved about 30% of the energy. The second program was a speech recognizer. It sampled the microphone to construct a wav eform. This waveform could either be analyzed on the notebook computer or be sent over a radio link for analysis on a fixed computer. Doing this saves CPU energy but uses energy for the radio. Degradation was accomplished by using a smaller vocabulary and a simpler acoustic model. The win here was about 35%. The next example was a map viewer that fetched the map over the radio link. Degradation consisted of either cropping the map to smaller dimensions or telling the remote server to omit smaller roads, thus requiring fewer bits to be transmitted. Again here a gain of about 35% was achieved. The fourth experiment was with transmission of JPEG images to a Web brow- ser. The JPEG standard allows various algorithms, trading image quality against file size. Here the gain averaged only 9%. Still, all in all, the experiments showed that by accepting some quality degradation, the user can run longer on a given bat- tery. 5.9 RESEARCH ON INPUT/OUTPUT There is a fair amount of research on input/output. Some of it is focused on specific devices, rather than I/O in general. Other work focuses on the entire I/O infrastructure. For instance, the Streamline architecture aims to provide applica- tion-tailored I/O that minimizes overhead due to copying, context switching, sig- naling and poor use of the cache and TLB (DeBruijn et al., 2011). It builds on the notion of Beltway Buffers, advanced circular buffers that are more efficient than
clipped_os_Page_426_Chunk6643
SEC. 5.9 RESEARCH ON INPUT/OUTPUT 427 existing buffering systems (DeBruijn and Bos, 2008). Streamline is especially use- ful for demanding network applications. Megapipe (Han et al., 2012) is another network I/O architecture for message-oriented workloads. It creates per-core bidi- rectional channels between the kernel and user space, on which the systems layers abstractions like lightweight sockets. The sockets are not quite POSIX-compliant, so applications need to be adapted to benefit from the more efficient I/O. Often, the goal of the research is to improve performance of a specific device in one way or another. Disk systems are a case in point. Disk-arm scheduling algo- rithms are an ever-popular research area. Sometimes the focus is on improved peformance (Gonzalez-Ferez et al., 2012; Prabhakar et al., 2013; and Zhang et al., 2012b) but sometimes it is on lower energy usage (Krish et al., 2013; Nijim et al., 2013; and Zhang et al., 2012a). With the popularity of server consolidation using virtual machines, disk scheduling for virtualized systems has become a hot topic (Jin et al., 2013; and Ling et al., 2012). Not all topics are new though. That old standby, RAID, still gets plenty of attention (Chen et al., 2013; Moon and Reddy; 2013; and Timcenko and Djordje- vic, 2013) as do SSDs (Dayan et al., 2013; Kim et al., 2013; and Luo et al., 2013). On the theoretical front, some researchers are looking at modeling disk systems in order to better understand their performance under different workloads (Li et al., 2013b; and Shen and Qi, 2013). Disks are not the only I/O device in the spotlight. Another key research area relating to I/O is networking. Topics include energy usage (Hewage and Voigt, 2013; and Hoque et al., 2013), networks for data centers (Haitjema, 2013; Liu et al., 2103; and Sun et al., 2013), quality of service (Gupta, 2013; Hemkumar and Vinaykumar, 2012; and Lai and Tang, 2013), and performance (Han et al., 2012; and Soorty, 2012). Given the large number of computer scientists with notebook computers and given the microscopic battery lifetime on most of them, it should come as no sur- prise that there is tremendous interest in using software techniques to reduce power consumption. Among the specialized topics being looked at are balancing the clock speed on different cores to achieve sufficient performance without wasting power (Hruby 2013), energy usage and quality of service (Holmbacka et al., 2013), esti- mating energy usage in real time (Dutta et al., 2013), providing OS services to manage energy usage (Weissel, 2012) examining the energy cost of security (Kabri and Seret, 2009), and scheduling for multimedia (Wei et al., 2010). Not everyone is interested in notebooks, though. Some computer scientists think big and want to save meg awatts at data centers (Fetzer and Knauth, 2012; Schwartz et al., 2012; Wang et al., 2013b; and Yuan et al., 2012). At the other end of the spectrum, a very hot topic is energy use in sensor net- works (Albath et al., 2013; Mikhaylov and Tervonen, 2013; Rasaneh and Baniro- stam, 2013; and Severini et al., 2012). Somewhat surprisingly, even the lowly clock is still a subject of research. To provide good resolution, some operating systems run the clock at 1000 Hz, which
clipped_os_Page_427_Chunk6644
428 INPUT/OUTPUT CHAP. 5 leads to substantial overhead. Getting rid of this overhead is where the research comes in (Tsafir et al., 2005). Similarly, interrupt latency is still a concern for research groups, especially in the area of real-time operating systems. Since these are often found embedded in critical systems (like controls of brake and steering systems), permitting interrupts only at very specific preemption points enables the system to control the possible interleavings and permits the use of formal verification to improve dependability (Blackham et al., 2012). Device drivers are also still a very active research area. Many operating system crashes are caused by buggy device drivers. In Symdrive, the authors present a framework to test device drivers without actually talking to devices (Renzelmann et al., 2012). As an alternative approach, Rhyzik et al. (2009) show how device drivers can be constructed automatically from specifications, with fewer chances of bugs. Thin clients are also a topic of interest, especially mobile devices connected to the cloud (Hocking, 2011; and Tuan-Anh et al., 2013). Finally, there are some papers on unusual topics such as buildings as big I/O devices (Dawson-Haggerty et al., 2013). 5.10 SUMMARY Input/output is an often neglected, but important, topic. A substantial fraction of any operating system is concerned with I/O. I/O can be accomplished in one of three ways. First, there is programmed I/O, in which the main CPU inputs or out- puts each byte or word and sits in a tight loop waiting until it can get or send the next one. Second, there is interrupt-driven I/O, in which the CPU starts an I/O transfer for a character or word and goes off to do something else until an interrupt arrives signaling completion of the I/O. Third, there is DMA, in which a separate chip manages the complete transfer of a block of data, given an interrupt only when the entire block has been transferred. I/O can be structured in four levels: the interrupt-service procedures, the device drivers, the device-independent I/O software, and the I/O libraries and spoolers that run in user space. The device drivers handle the details of running the devices and providing uniform interfaces to the rest of the operating system. The device-inde- pendent I/O software does things like buffering and error reporting. Disks come in a variety of types, including magnetic disks, RAIDs, flash drives, and optical disks. On rotating disks, disk arm scheduling algorithms can often be used to improve disk performance, but the presence of virtual geometries complicates matters. By pairing two disks, a stable storage medium with certain useful properties can be constructed. Clocks are used for keeping track of the real time, limiting how long processes can run, handling watchdog timers, and doing accounting.
clipped_os_Page_428_Chunk6645
SEC. 5.10 SUMMARY 429 Character-oriented terminals have a variety of issues concerning special char- acters that can be input and special escape sequences that can be output. Input can be in raw mode or cooked mode, depending on how much control the program wants over the input. Escape sequences on output control cursor movement and allow for inserting and deleting text on the screen. Most UNIX systems use the X Window System as the basis of the user inter- face. It consists of programs that are bound to special libraries that issue drawing commands and an X server that writes on the display. Many personal computers use GUIs for their output. These are based on the WIMP paradigm: windows, icons, menus, and a pointing device. GUI-based pro- grams are generally event driven, with keyboard, mouse, and other events being sent to the program for processing as soon as they happen. In UNIX systems, the GUIs almost always run on top of X. Thin clients have some advantages over standard PCs, notably simplicity and less maintenance for users. Finally, power management is a major issue for phones, tablets, and notebooks because battery lifetimes are limited and for desktop and server machines because of an organization’s energy bills. Various techniques can be employed by the oper- ating system to reduce power consumption. Programs can also help out by sacrific- ing some quality for longer battery lifetimes. PROBLEMS 1. Advances in chip technology have made it possible to put an entire controller, includ- ing all the bus access logic, on an inexpensive chip. How does that affect the model of Fig. 1-6? 2. Given the speeds listed in Fig. 5-1, is it possible to scan documents from a scanner and transmit them over an 802.11g network at full speed? Defend your answer. 3. Figure 5-3(b) shows one way of having memory-mapped I/O even in the presence of separate buses for memory and I/O devices, namely, to first try the memory bus and if that fails try the I/O bus. A clever computer science student has thought of an im- provement on this idea: try both in parallel, to speed up the process of accessing I/O devices. What do you think of this idea? 4. Explain the tradeoffs between precise and imprecise interrupts on a superscalar machine. 5. A DMA controller has fiv e channels. The controller is capable of requesting a 32-bit word every 40 nsec. A response takes equally long. How fast does the bus have to be to avoid being a bottleneck? 6. Suppose that a system uses DMA for data transfer from disk controller to main memo- ry. Further assume that it takes t1 nsec on average to acquire the bus and t2 nsec to transfer one word over the bus (t1 >> t2). After the CPU has programmed the DMA
clipped_os_Page_429_Chunk6646
430 INPUT/OUTPUT CHAP. 5 controller, how long will it take to transfer 1000 words from the disk controller to main memory, if (a) word-at-a-time mode is used, (b) burst mode is used? Assume that com- manding the disk controller requires acquiring the bus to send one word and acknowl- edging a transfer also requires acquiring the bus to send one word. 7. One mode that some DMA controllers use is to have the device controller send the word to the DMA controller, which then issues a second bus request to write to mem- ory. How can this mode be used to perform memory to memory copy? Discuss any advantage or disadvantage of using this method instead of using the CPU to perform memory to memory copy. 8. Suppose that a computer can read or write a memory word in 5 nsec. Also suppose that when an interrupt occurs, all 32 CPU registers, plus the program counter and PSW are pushed onto the stack. What is the maximum number of interrupts per second this ma- chine can process? 9. CPU architects know that operating system writers hate imprecise interrupts. One way to please the OS folks is for the CPU to stop issuing new instructions when an interrupt is signaled, but allow all the instructions currently being executed to finish, then force the interrupt. Does this approach have any disadvantages? Explain your answer. 10. In Fig. 5-9(b), the interrupt is not acknowledged until after the next character has been output to the printer. Could it have equally well been acknowledged right at the start of the interrupt service procedure? If so, give one reason for doing it at the end, as in the text. If not, why not? 11. A computer has a three-stage pipeline as shown in Fig. 1-7(a). On each clock cycle, one new instruction is fetched from memory at the address pointed to by the PC and put into the pipeline and the PC advanced. Each instruction occupies exactly one mem- ory word. The instructions already in the pipeline are each advanced one stage. When an interrupt occurs, the current PC is pushed onto the stack, and the PC is set to the ad- dress of the interrupt handler. Then the pipeline is shifted right one stage and the first instruction of the interrupt handler is fetched into the pipeline. Does this machine have precise interrupts? Defend your answer. 12. A typical printed page of text contains 50 lines of 80 characters each. Imagine that a certain printer can print 6 pages per minute and that the time to write a character to the printer’s output register is so short it can be ignored. Does it make sense to run this printer using interrupt-driven I/O if each character printed requires an interrupt that takes 50 μsec all-in to service? 13. Explain how an OS can facilitate installation of a new device without any need for recompiling the OS. 14. In which of the four I/O software layers is each of the following done. (a) Computing the track, sector, and head for a disk read. (b) Writing commands to the device registers. (c) Checking to see if the user is permitted to use the device. (d) Converting binary integers to ASCII for printing. 15. A local area network is used as follows. The user issues a system call to write data packets to the network. The operating system then copies the data to a kernel buffer.
clipped_os_Page_430_Chunk6647
CHAP. 5 PROBLEMS 431 Then it copies the data to the network controller board. When all the bytes are safely inside the controller, they are sent over the network at a rate of 10 megabits/sec. The receiving network controller stores each bit a microsecond after it is sent. When the last bit arrives, the destination CPU is interrupted, and the kernel copies the newly arri- ved packet to a kernel buffer to inspect it. Once it has figured out which user the packet is for, the kernel copies the data to the user space. If we assume that each interrupt and its associated processing takes 1 msec, that packets are 1024 bytes (ignore the head- ers), and that copying a byte takes 1 μsec, what is the maximum rate at which one process can pump data to another? Assume that the sender is blocked until the work is finished at the receiving side and an acknowledgement comes back. For simplicity, as- sume that the time to get the acknowledgement back is so small it can be ignored. 16. Why are output files for the printer normally spooled on disk before being printed? 17. How much cylinder skew is needed for a 7200-RPM disk with a track-to-track seek time of 1 msec? The disk has 200 sectors of 512 bytes each on each track. 18. A disk rotates at 7200 RPM. It has 500 sectors of 512 bytes around the outer cylinder. How long does it take to read a sector? 19. Calculate the maximum data rate in bytes/sec for the disk described in the previous problem. 20. RAID level 3 is able to correct single-bit errors using only one parity drive. What is the point of RAID level 2? After all, it also can only correct one error and takes more drives to do so. 21. A RAID can fail if two or more of its drives crash within a short time interval. Suppose that the probability of one drive crashing in a given hour is p. What is the probability of a k-drive RAID failing in a given hour? 22. Compare RAID level 0 through 5 with respect to read performance, write performance, space overhead, and reliability. 23. How many pebibytes are there in a zebibyte? 24. Why are optical storage devices inherently capable of higher data density than mag- netic storage devices? Note: This problem requires some knowledge of high-school physics and how magnetic fields are generated. 25. What are the advantages and disadvantages of optical disks versus magnetic disks? 26. If a disk controller writes the bytes it receives from the disk to memory as fast as it re- ceives them, with no internal buffering, is interleaving conceivably useful? Discuss your answer. 27. If a disk has double interleaving, does it also need cylinder skew in order to avoid missing data when making a track-to-track seek? Discuss your answer. 28. Consider a magnetic disk consisting of 16 heads and 400 cylinders. This disk has four 100-cylinder zones with the cylinders in different zones containing 160, 200, 240. and 280 sectors, respectively. Assume that each sector contains 512 bytes, average seek time between adjacent cylinders is 1 msec, and the disk rotates at 7200 RPM. Calcu- late the (a) disk capacity, (b) optimal track skew, and (c) maximum data transfer rate.
clipped_os_Page_431_Chunk6648
432 INPUT/OUTPUT CHAP. 5 29. A disk manufacturer has two 5.25-inch disks that each have 10,000 cylinders. The newer one has double the linear recording density of the older one. Which disk proper- ties are better on the newer drive and which are the same? Are any worse on the newer one? 30. A computer manufacturer decides to redesign the partition table of a Pentium hard disk to provide more than four partitions. What are some consequences of this change? 31. Disk requests come in to the disk driver for cylinders 10, 22, 20, 2, 40, 6, and 38, in that order. A seek takes 6 msec per cylinder. How much seek time is needed for (a) First-come, first served. (b) Closest cylinder next. (c) Elevator algorithm (initially moving upward). In all cases, the arm is initially at cylinder 20. 32. A slight modification of the elevator algorithm for scheduling disk requests is to al- ways scan in the same direction. In what respect is this modified algorithm better than the elevator algorithm? 33. A personal computer salesman visiting a university in South-West Amsterdam remark- ed during his sales pitch that his company had devoted substantial effort to making their version of UNIX very fast. As an example, he noted that their disk driver used the elevator algorithm and also queued multiple requests within a cylinder in sector order. A student, Harry Hacker, was impressed and bought one. He took it home and wrote a program to randomly read 10,000 blocks spread across the disk. To his amaze- ment, the performance that he measured was identical to what would be expected from first-come, first-served. Was the salesman lying? 34. In the discussion of stable storage using nonvolatile RAM, the following point was glossed over. What happens if the stable write completes but a crash occurs before the operating system can write an invalid block number in the nonvolatile RAM? Does this race condition ruin the abstraction of stable storage? Explain your answer. 35. In the discussion on stable storage, it was shown that the disk can be recovered to a consistent state (a write either completes or does not take place at all) if a CPU crash occurs during a write. Does this property hold if the CPU crashes again during a recov- ery procedure. Explain your answer. 36. In the discussion on stable storage, a key assumption is that a CPU crash that corrupts a sector leads to an incorrect ECC. What problems might arise in the fiv e crash-recov- ery scenarios shown in Figure 5-27 if this assumption does not hold? 37. The clock interrupt handler on a certain computer requires 2 msec (including process switching overhead) per clock tick. The clock runs at 60 Hz. What fraction of the CPU is devoted to the clock? 38. A computer uses a programmable clock in square-wav e mode. If a 500 MHz crystal is used, what should be the value of the holding register to achieve a clock resolution of (a) a millisecond (a clock tick once every millisecond)? (b) 100 microseconds?
clipped_os_Page_432_Chunk6649
CHAP. 5 PROBLEMS 433 39. A system simulates multiple clocks by chaining all pending clock requests together as shown in Fig. 5-30. Suppose the current time is 5000 and there are pending clock re- quests for time 5008, 5012, 5015, 5029, and 5037. Show the values of Clock header, Current time, and Next signal at times 5000, 5005, and 5013. Suppose a new (pending) signal arrives at time 5017 for 5033. Show the values of Clock header, Current time and Next signal at time 5023. 40. Many versions of UNIX use an unsigned 32-bit integer to keep track of the time as the number of seconds since the origin of time. When will these systems wrap around (year and month)? Do you expect this to actually happen? 41. A bitmap terminal contains 1600 by 1200 pixels. To scroll a window, the CPU (or controller) must move all the lines of text upward by copying their bits from one part of the video RAM to another. If a particular window is 80 lines high by 80 characters wide (6400 characters, total), and a character’s box is 8 pixels wide by 16 pixels high, how long does it take to scroll the whole window at a copying rate of 50 nsec per byte? If all lines are 80 characters long, what is the equivalent baud rate of the terminal? Putting a character on the screen takes 5 μsec. How many lines per second can be dis- played? 42. After receiving a DEL (SIGINT) character, the display driver discards all output cur- rently queued for that display. Why? 43. A user at a terminal issues a command to an editor to delete the word on line 5 occupy- ing character positions 7 through and including 12. Assuming the cursor is not on line 5 when the command is given, what ANSI escape sequence should the editor emit to delete the word? 44. The designers of a computer system expected that the mouse could be moved at a max- imum rate of 20 cm/sec. If a mickey is 0.1 mm and each mouse message is 3 bytes, what is the maximum data rate of the mouse assuming that each mickey is reported separately? 45. The primary additive colors are red, green, and blue, which means that any color can be constructed from a linear superposition of these colors. Is it possible that someone could have a color photograph that cannot be represented using full 24-bit color? 46. One way to place a character on a bitmapped screen is to use BitBlt from a font table. Assume that a particular font uses characters that are 16 × 24 pixels in true RGB color. (a) How much font table space does each character take? (b) If copying a byte takes 100 nsec, including overhead, what is the output rate to the screen in characters/sec? 47. Assuming that it takes 2 nsec to copy a byte, how much time does it take to completely rewrite the screen of an 80 character × 25 line text mode memory-mapped screen? What about a 1024 × 768 pixel graphics screen with 24-bit color? 48. In Fig. 5-36 there is a class to RegisterClass. In the corresponding X Window code, in Fig. 5-34, there is no such call or anything like it. Why not? 49. In the text we gav e an example of how to draw a rectangle on the screen using the Win- dows GDI:
clipped_os_Page_433_Chunk6650
434 INPUT/OUTPUT CHAP. 5 Rectangle(hdc, xleft, ytop, xright, ybottom); Is there any real need for the first parameter (hdc), and if so, what? After all, the coor- dinates of the rectangle are explicitly specified as parameters. 50. A thin-client terminal is used to display a Web page containing an animated cartoon of size 400 pixels × 160 pixels running at 10 frames/sec. What fraction of a 100-Mbps Fast Ethernet is consumed by displaying the cartoon? 51. It has been observed that a thin-client system works well with a 1-Mbps network in a test. Are any problems likely in a multiuser situation? (Hint: Consider a large number of users watching a scheduled TV show and the same number of users browsing the World Wide Web.) 52. Describe two advantages and two disadvantages of thin client computing? 53. If a CPU’s maximum voltage, V, is cut to V/n, its power consumption drops to 1/n2 of its original value and its clock speed drops to 1/n of its original value. Suppose that a user is typing at 1 char/sec, but the CPU time required to process each character is 100 msec. What is the optimal value of n and what is the corresponding energy saving in percent compared to not cutting the voltage? Assume that an idle CPU consumes no energy at all. 54. A notebook computer is set up to take maximum advantage of power saving features including shutting down the display and the hard disk after periods of inactivity. A user sometimes runs UNIX programs in text mode, and at other times uses the X Window System. She is surprised to find that battery life is significantly better when she uses text-only programs. Why? 55. Write a program that simulates stable storage. Use two large fixed-length files on your disk to simulate the two disks. 56. Write a program to implement the three disk-arm scheduling algorithms. Write a driver program that generates a sequence of cylinder numbers (0–999) at random, runs the three algorithms for this sequence and prints out the total distance (number of cylin- ders) the arm needs to traverse in the three algorithms. 57. Write a program to implement multiple timers using a single clock. Input for this pro- gram consists of a sequence of four types of commands (S <int>, T, E <int>, P): S <int> sets the current time to <int>; T is a clock tick; and E <int> schedules a signal to occur at time <int>; P prints out the values of Current time, Next signal, and Clock header. Your program should also print out a statement whenever it is time to raise a signal.
clipped_os_Page_434_Chunk6651
6 DEADLOCKS Computer systems are full of resources that can be used only by one process at a time. Common examples include printers, tape drives for backing up company data, and slots in the system’s internal tables. Having two processes simultan- eously writing to the printer leads to gibberish. Having two processes using the same file-system table slot invariably will lead to a corrupted file system. Conse- quently, all operating systems have the ability to (temporarily) grant a process ex- clusive access to certain resources. For many applications, a process needs exclusive access to not one resource, but sev eral. Suppose, for example, two processes each want to record a scanned document on a Blu-ray disc. Process A requests permission to use the scanner and is granted it. Process B is programmed differently and requests the Blu-ray re- corder first and is also granted it. Now A asks for the Blu-ray recorder, but the re- quest is suspended until B releases it. Unfortunately, instead of releasing the Blu- ray recorder, B asks for the scanner. At this point both processes are blocked and will remain so forever. This situation is called a deadlock. Deadlocks can also occur across machines. For example, many off ices have a local area network with many computers connected to it. Often devices such as scanners, Blu-ray/DVD recorders, printers, and tape drives are connected to the network as shared resources, available to any user on any machine. If these de- vices can be reserved remotely (i.e., from the user’s home machine), deadlocks of the same kind can occur as described above. More complicated situations can cause deadlocks involving three, four, or more devices and users. 435
clipped_os_Page_435_Chunk6652
436 DEADLOCKS CHAP. 6 Deadlocks can also occur in a variety of other situations.. In a database sys- tem, for example, a program may have to lock several records it is using, to avoid race conditions. If process A locks record R1 and process B locks record R2, and then each process tries to lock the other one’s record, we also have a deadlock. Thus, deadlocks can occur on hardware resources or on software resources. In this chapter, we will look at several kinds of deadlocks, see how they arise, and study some ways of preventing or avoiding them. Although these deadlocks arise in the context of operating systems, they also occur in database systems and many other contexts in computer science, so this material is actually applicable to a wide variety of concurrent systems. A great deal has been written about deadlocks. Tw o bibliographies on the sub- ject have appeared in Operating Systems Review and should be consulted for refer- ences (Newton, 1979; and Zobel, 1983). Although these bibliographies are very old, most of the work on deadlocks was done well before 1980, so they are still useful. 6.1 RESOURCES A major class of deadlocks involves resources to which some process has been granted exclusive access. These resources include devices, data records, files, and so forth. To make the discussion of deadlocks as general as possible, we will refer to the objects granted as resources. A resource can be a hardware device (e.g., a Blu-ray drive) or a piece of information (e.g., a record in a database). A computer will normally have many different resources that a process can acquire. For some resources, several identical instances may be available, such as three Blu-ray drives. When several copies of a resource are available, any one of them can be used to satisfy any request for the resource. In short, a resource is anything that must be acquired, used, and released over the course of time. 6.1.1 Preemptable and Nonpreemptable Resources Resources come in two types: preemptable and nonpreemptable. A preempt- able resource is one that can be taken away from the process owning it with no ill effects. Memory is an example of a preemptable resource. Consider, for example, a system with 1 GB of user memory, one printer, and two 1-GB processes that each want to print something. Process A requests and gets the printer, then starts to compute the values to print. Before it has finished the computation, it exceeds its time quantum and is swapped out to disk. Process B now runs and tries, unsuccessfully as it turns out, to acquire the printer. Potenially, we now hav e a deadlock situation, because A has the printer and B has the memory, and neither one can proceed without the resource held by the other. Fortunately, it is possible to preempt (take away) the memory from B by
clipped_os_Page_436_Chunk6653
SEC. 6.1 RESOURCES 437 swapping it out and swapping A in. Now A can run, do its printing, and then re- lease the printer. No deadlock occurs. A nonpreemptable resource, in contrast, is one that cannot be taken away from its current owner without potentially causing failure. If a process has begun to burn a Blu-ray, suddenly taking the Blu-ray recorder away from it and giving it to another process will result in a garbled Blu-ray. Blu-ray recorders are not pre- emptable at an arbitrary moment. Whether a resource is preemptible depends on the context. On a standard PC, memory is preemptible because pages can always be swapped out to disk to recover it. However, on a smartphone that does not support swapping or paging, deadlocks cannot be avoided by just swapping out a memory hog. In general, deadlocks involve nonpreemptable resources. Potential deadlocks that involve preemptable resources can usually be resolved by reallocating re- sources from one process to another. Thus, our treatment will focus on nonpre- emptable resources. The abstract sequence of events required to use a resource is given below. 1. Request the resource. 2. Use the resource. 3. Release the resource. If the resource is not available when it is requested, the requesting process is forced to wait. In some operating systems, the process is automatically blocked when a resource request fails, and awakened when it becomes available. In other systems, the request fails with an error code, and it is up to the calling process to wait a little while and try again. A process whose resource request has just been denied will normally sit in a tight loop requesting the resource, then sleeping, then trying again. Although this process is not blocked, for all intents and purposes it is as good as blocked, be- cause it cannot do any useful work. In our further treatment, we will assume that when a process is denied a resource request, it is put to sleep. The exact nature of requesting a resource is highly system dependent. In some systems, a request system call is provided to allow processes to explicitly ask for resources. In others, the only resources that the operating system knows about are special files that only one process can have open at a time. These are opened by the usual open call. If the file is already in use, the caller is blocked until its cur- rent owner closes it. 6.1.2 Resource Acquisition For some kinds of resources, such as records in a database system, it is up to the user processes rather than the system to manage resource usage themselves. One way of allowing this is to associate a semaphore with each resource. These
clipped_os_Page_437_Chunk6654
438 DEADLOCKS CHAP. 6 semaphores are all initialized to 1. Mutexes can be used equally well. The three steps listed above are then implemented as a down on the semaphore to acquire the resource, the use of the resource, and finally an up on the resource to release it. These steps are shown in Fig. 6-1(a). typedef int semaphore; typedef int semaphore; semaphore resource 1; semaphore resource 1; semaphore resource 2; void process A(void) { void process A(void) { down(&resource 1); down(&resource 1); use resource 1( ); down(&resource 2); up(&resource 1); use both resources( ); } up(&resource 2); up(&resource 1); } (a) (b) Figure 6-1. Using a semaphore to protect resources. (a) One resource. (b) Two resources. Sometimes processes need two or more resources. They can be acquired se- quentially, as shown in Fig. 6-1(b). If more than two resources are needed, they are just acquired one after another. So far, so good. As long as only one process is involved, everything works fine. Of course, with only one process, there is no need to formally acquire re- sources, since there is no competition for them. Now let us consider a situation with two processes, A and B, and two re- sources. Two scenarios are depicted in Fig. 6-2. In Fig. 6-2(a), both processes ask for the resources in the same order. In Fig. 6-2(b), they ask for them in a different order. This difference may seem minor, but it is not. In Fig. 6-2(a), one of the processes will acquire the first resource before the other one. That process will then successfully acquire the second resource and do its work. If the other process attempts to acquire resource 1 before it has been re- leased, the other process will simply block until it becomes available. In Fig. 6-2(b), the situation is different. It might happen that one of the proc- esses acquires both resources and effectively blocks out the other process until it is done. However, it might also happen that process A acquires resource 1 and proc- ess B acquires resource 2. Each one will now block when trying to acquire the other one. Neither process will ever run again. Bad news: this situation is a dead- lock. Here we see how what appears to be a minor difference in coding style— which resource to acquire first—turns out to make the difference between the pro- gram working and the program failing in a hard-to-detect way. Because deadlocks can occur so easily, a lot of research has gone into ways to deal with them. This chapter discusses deadlocks in detail and what can be done about them.
clipped_os_Page_438_Chunk6655
SEC. 6.2 INTRODUCTION TO DEADLOCKS 439 typedef int semaphore; semaphore resource 1; semaphore resource 1; semaphore resource 2; semaphore resource 2; void process A(void) { void process A(void) { down(&resource 1); down(&resource 1); down(&resource 2); down(&resource 2); use both resources( ); use both resources( ); up(&resource 2); up(&resource 2); up(&resource 1); up(&resource 1); } } void process B(void) { void process B(void) { down(&resource 1); down(&resource 2); down(&resource 2); down(&resource 1); use both resources( ); use both resources( ); up(&resource 2); up(&resource 1); up(&resource 1); up(&resource 2); } } (a) (b) Figure 6-2. (a) Deadlock-free code. (b) Code with a potential deadlock. 6.2 INTRODUCTION TO DEADLOCKS Deadlock can be defined formally as follows: A set of processes is deadlocked if each process in the set is waiting for an event that only another process in the set can cause. Because all the processes are waiting, none of them will ever cause any event that could wake up any of the other members of the set, and all the processes continue to wait forever. For this model, we assume that processes are single threaded and that no interrupts are possible to wake up a blocked process. The no-interrupts condition is needed to prevent an otherwise deadlocked process from being awak- ened by an alarm, and then causing events that release other processes in the set. In most cases, the event that each process is waiting for is the release of some resource currently possessed by another member of the set. In other words, each member of the set of deadlocked processes is waiting for a resource that is owned by a deadlocked process. None of the processes can run, none of them can release any resources, and none of them can be awakened. The number of processes and the number and kind of resources possessed and requested are unimportant. This result holds for any kind of resource, including both hardware and software. This kind of deadlock is called a resource deadlock. It is probably the most common kind, but it is not the only kind. We first study resource deadlocks in detail and then at the end of the chapter return briefly to other kinds of deadlocks.
clipped_os_Page_439_Chunk6656
440 DEADLOCKS CHAP. 6 6.2.1 Conditions for Resource Deadlocks Coffman et al. (1971) showed that four conditions must hold for there to be a (resource) deadlock: 1. Mutual exclusion condition. Each resource is either currently assign- ed to exactly one process or is available. 2. Hold-and-wait condition. Processes currently holding resources that were granted earlier can request new resources. 3. No-preemption condition. Resources previously granted cannot be forcibly taken away from a process. They must be explicitly released by the process holding them. 4. Circular wait condition. There must be a circular list of two or more processes, each of which is waiting for a resource held by the next member of the chain. All four of these conditions must be present for a resource deadlock to occur. If one of them is absent, no resource deadlock is possible. It is worth noting that each condition relates to a policy that a system can have or not have. Can a given resource be assigned to more than one process at once? Can a process hold a resource and ask for another? Can resources be preempted? Can circular waits exist? Later on we will see how deadlocks can be attacked by trying to negate some of these conditions. 6.2.2 Deadlock Modeling Holt (1972) showed how these four conditions can be modeled using directed graphs. The graphs have two kinds of nodes: processes, shown as circles, and re- sources, shown as squares. A directed arc from a resource node (square) to a proc- ess node (circle) means that the resource has previously been requested by, granted to, and is currently held by that process. In Fig. 6-3(a), resource R is currently as- signed to process A. A directed arc from a process to a resource means that the process is currently blocked waiting for that resource. In Fig. 6-3(b), process B is waiting for resource S. In Fig. 6-3(c) we see a deadlock: process C is waiting for resource T, which is currently held by process D. Process D is not about to release resource T because it is waiting for resource U, held by C. Both processes will wait forever. A cycle in the graph means that there is a deadlock involving the processes and resources in the cycle (assuming that there is one resource of each kind). In this example, the cycle is C −T −D −U −C. Now let us look at an example of how resource graphs can be used. Imagine that we have three processes, A, B, and C, and three resources, R, S, and T. The
clipped_os_Page_440_Chunk6657
SEC. 6.2 INTRODUCTION TO DEADLOCKS 441 (a) (b) (c) T U D C S B A R Figure 6-3. Resource allocation graphs. (a) Holding a resource. (b) Requesting a resource. (c) Deadlock. requests and releases of the three processes are given in Fig. 6-4(a)–(c). The oper- ating system is free to run any unblocked process at any instant, so it could decide to run A until A finished all its work, then run B to completion, and finally run C. This ordering does not lead to any deadlocks (because there is no competition for resources) but it also has no parallelism at all. In addition to requesting and releasing resources, processes compute and do I/O. When the processes are run se- quentially, there is no possibility that while one process is waiting for I/O, another can use the CPU. Thus, running the processes strictly sequentially may not be optimal. On the other hand, if none of the processes does any I/O at all, shortest job first is better than round robin, so under some circumstances running all proc- esses sequentially may be the best way. Let us now suppose that the processes do both I/O and computing, so that round robin is a reasonable scheduling algorithm. The resource requests might oc- cur in the order of Fig. 6-4(d). If these six requests are carried out in that order, the six resulting resource graphs are asshown in Fig. 6-4(e)–(j). After request 4 has been made, A blocks waiting for S, as shown in Fig. 6-4(h). In the next two steps B and C also block, ultimately leading to a cycle and the deadlock of Fig. 6-4(j). However, as we hav e already mentioned, the operating system is not required to run the processes in any special order. In particular, if granting a particular re- quest might lead to deadlock, the operating system can simply suspend the process without granting the request (i.e., just not schedule the process) until it is safe. In Fig. 6-4, if the operating system knew about the impending deadlock, it could sus- pend B instead of granting it S. By running only A and C, we would get the re- quests and releases of Fig. 6-4(k) instead of Fig. 6-4(d). This sequence leads to the resource graphs of Fig. 6-4(l)–(q), which do not lead to deadlock. After step (q), process B can be granted S because A is finished and C has ev erything it needs. Even if B blocks when requesting T, no deadlock can occur. B will just wait until C is finished. Later in this chapter we will study a detailed algorithm for making allocation decisions that do not lead to deadlock. For the moment, the point to understand is that resource graphs are a tool that lets us see if a given request/release sequence
clipped_os_Page_441_Chunk6658
442 DEADLOCKS CHAP. 6 (j) A Request R Request S Release R Release S B Request S Request T Release S Release T C Request T Request R Release T Release R 1. A requests R 2. B requests S 3. C requests T 4. A requests S 5. B requests T 6. C requests R deadlock 1. A requests R 2. C requests T 3. A requests S 4. C requests R 5. A releases R 6. A releases S no deadlock A R B S C T (i) A R B S C T (h) A R B S C T (g) A R B S C T (f) A R B S C T (e) (d) (c) (b) (a) A R B S C T (q) A R B S C T (p) A R B S C T (o) A R B S C T (n) A R B S C T (m) A R B S C T (l) (k) A R B S C T Figure 6-4. An example of how deadlock occurs and how it can be avoided.
clipped_os_Page_442_Chunk6659
SEC. 6.2 INTRODUCTION TO DEADLOCKS 443 leads to deadlock. We just carry out the requests and releases step by step, and after every step we check the graph to see if it contains any cycles. If so, we have a deadlock; if not, there is no deadlock. Although our treatment of resource graphs has been for the case of a single resource of each type, resource graphs can also be generalized to handle multiple resources of the same type (Holt, 1972). In general, four strategies are used for dealing with deadlocks. 1. Just ignore the problem. Maybe if you ignore it, it will ignore you. 2. Detection and recovery. Let them occur, detect them, and take action. 3. Dynamic avoidance by careful resource allocation. 4. Prevention, by structurally negating one of the four conditions. In the next four sections, we will examine each of these methods in turn. 6.3 THE OSTRICH ALGORITHM The simplest approach is the ostrich algorithm: stick your head in the sand and pretend there is no problem.† People react to this strategy in different ways. Math- ematicians find it unacceptable and say that deadlocks must be prevented at all costs. Engineers ask how often the problem is expected, how often the system crashes for other reasons, and how serious a deadlock is. If deadlocks occur on the av erage once every fiv e years, but system crashes due to hardware failures and op- erating system bugs occur once a week, most engineers would not be willing to pay a large penalty in performance or convenience to eliminate deadlocks. To make this contrast more specific, consider an operating system that blocks the caller when an open system call on a physical device such as a Blu-ray driver or a printer cannot be carried out because the device is busy. Typically it is up to the device driver to decide what action to take under such circumstances. Blocking or returning an error code are two obvious possibilities. If one process suc- cessfully opens the Blu-ray drive and another successfully opens the printer and then each process tries to open the other one and blocks trying, we have a dead- lock. Few current systems will detect this. 6.4 DEADLOCK DETECTION AND RECOVERY A second technique is detection and recovery. When this technique is used, the system does not attempt to prevent deadlocks from occurring. Instead, it lets them occur, tries to detect when this happens, and then takes some action to †Actually, this bit of folklore is nonsense. Ostriches can run at 60 km/hour and their kick is powerful enough to kill any lion with visions of a big chicken dinner, and lions know this.
clipped_os_Page_443_Chunk6660
444 DEADLOCKS CHAP. 6 recover after the fact. In this section we will look at some of the ways deadlocks can be detected and some of the ways recovery from them can be handled. 6.4.1 Deadlock Detection with One Resource of Each Type Let us begin with the simplest case: there is only one resource of each type. Such a system might have one scanner, one Blu-ray recorder, one plotter, and one tape drive, but no more than one of each class of resource. In other words, we are excluding systems with two printers for the moment. We will treat them later, using a different method. For such a system, we can construct a resource graph of the sort illustrated in Fig. 6-3. If this graph contains one or more cycles, a deadlock exists. Any process that is part of a cycle is deadlocked. If no cycles exist, the system is not dead- locked. As an example of a system more complex than those we have looked at so far, consider a system with seven processes, A though G, and six resources, R through W. The state of which resources are currently owned and which ones are currently being requested is as follows: 1. Process A holds R and wants S. 2. Process B holds nothing but wants T. 3. Process C holds nothing but wants S. 4. Process D holds U and wants S and T. 5. Process E holds T and wants V. 6. Process F holds W and wants S. 7. Process G holds V and wants U. The question is: ‘‘Is this system deadlocked, and if so, which processes are in- volved?’’ To answer this question, we can construct the resource graph of Fig. 6-5(a). This graph contains one cycle, which can be seen by visual inspection. The cycle is shown in Fig. 6-5(b). From this cycle, we can see that processes D, E, and G are all deadlocked. Processes A, C, and F are not deadlocked because S can be allo- cated to any one of them, which then finishes and returns it. Then the other two can take it in turn and also complete. (Note that to make this example more inter- esting we have allowed processes, namely D, to ask for two resources at once.) Although it is relatively simple to pick out the deadlocked processes by visual inspection from a simple graph, for use in actual systems we need a formal algo- rithm for detecting deadlocks. Many algorithms for detecting cycles in directed graphs are known. Below we will give a simple one that inspects a graph and ter- minates either when it has found a cycle or when it has shown that none exists. It
clipped_os_Page_444_Chunk6661
SEC. 6.4 DEADLOCK DETECTION AND RECOVERY 445 R S T T U V U V W C D E D E G G A F B (a) (b) Figure 6-5. (a) A resource graph. (b) A cycle extracted from (a). uses one dynamic data structure, L, a list of nodes, as well as a list of arcs. During the algorithm, to prevent repeated inspections, arcs will be marked to indicate that they hav e already been inspected, The algorithm operates by carrying out the following steps as specified: 1. For each node, N, in the graph, perform the following fiv e steps with N as the starting node. 2. Initialize L to the empty list, and designate all the arcs as unmarked. 3. Add the current node to the end of L and check to see if the node now appears in L two times. If it does, the graph contains a cycle (listed in L) and the algorithm terminates. 4. From the given node, see if there are any unmarked outgoing arcs. If so, go to step 5; if not, go to step 6. 5. Pick an unmarked outgoing arc at random and mark it. Then follow it to the new current node and go to step 3. 6. If this node is the initial node, the graph does not contain any cycles and the algorithm terminates. Otherwise, we have now reached a dead end. Remove it and go back to the previous node, that is, the one that was current just before this one, make that one the current node, and go to step 3. What this algorithm does is take each node, in turn, as the root of what it hopes will be a tree, and do a depth-first search on it. If it ever comes back to a node it has already encountered, then it has found a cycle. If it exhausts all the arcs from any giv en node, it backtracks to the previous node. If it backtracks to the root and cannot go further, the subgraph reachable from the current node does not contain
clipped_os_Page_445_Chunk6662
446 DEADLOCKS CHAP. 6 any cycles. If this property holds for all nodes, the entire graph is cycle free, so the system is not deadlocked. To see how the algorithm works in practice, let us use it on the graph of Fig. 6-5(a). The order of processing the nodes is arbitrary, so let us just inspect them from left to right, top to bottom, first running the algorithm starting at R, then successively A, B, C, S, D, T, E, F, and so forth. If we hit a cycle, the algorithm stops. We start at R and initialize L to the empty list. Then we add R to the list and move to the only possibility, A, and add it to L, giving L = [R, A]. From A we go to S, giving L = [R, A, S]. S has no outgoing arcs, so it is a dead end, forcing us to backtrack to A. Since A has no unmarked outgoing arcs, we backtrack to R, com- pleting our inspection of R. Now we restart the algorithm starting at A, resetting L to the empty list. This search, too, quickly stops, so we start again at B. From B we continue to follow outgoing arcs until we get to D, at which time L = [B, T, E, V, G, U, D]. Now we must make a (random) choice. If we pick S we come to a dead end and backtrack to D. The second time we pick T and update L to be [B, T, E, V, G, U, D, T ], at which point we discover the cycle and stop the algorithm. This algorithm is far from optimal. For a better one, see Even (1979). Never- theless, it demonstrates that an algorithm for deadlock detection exists. 6.4.2 Deadlock Detection with Multiple Resources of Each Type When multiple copies of some of the resources exist, a different approach is needed to detect deadlocks. We will now present a matrix-based algorithm for de- tecting deadlock among n processes, P1 through Pn. Let the number of resource classes be m, with E1 resources of class 1, E2 resources of class 2, and generally, Ei resources of class i (1 ≤i ≤m). E is the existing resource vector. It giv es the total number of instances of each resource in existence. For example, if class 1 is tape drives, then E1 = 2 means the system has two tape drives. At any instant, some of the resources are assigned and are not available. Let A be the av ailable resource vector, with Ai giving the number of instances of re- source i that are currently available (i.e., unassigned). If both of our two tape drives are assigned, A1 will be 0. Now we need two arrays, C, the current allocation matrix, and R, the request matrix. The ith row of C tells how many instances of each resource class Pi cur- rently holds. Thus, Cij is the number of instances of resource j that are held by process i. Similarly, Rij is the number of instances of resource j that Pi wants. These four data structures are shown in Fig. 6-6. An important invariant holds for these four data structures. In particular, every resource is either allocated or is available. This observation means that n i=1Σ Cij + A j = E j
clipped_os_Page_446_Chunk6663
SEC. 6.4 DEADLOCK DETECTION AND RECOVERY 447 Resources in existence (E1, E2, E3, …, Em) Current allocation matrix C11 C21 Cn1 C12 C22 Cn2 C13 C23 Cn3 C1m C2m Cnm Row n is current allocation to process n Resources available (A1, A2, A3, …, Am) Request matrix R11 R21 Rn1 R12 R22 Rn2 R13 R23 Rn3 R1m R2m Rnm Row 2 is what process 2 needs Figure 6-6. The four data structures needed by the deadlock detection algorithm. In other words, if we add up all the instances of the resource j that have been allo- cated and to this add all the instances that are available, the result is the number of instances of that resource class that exist. The deadlock detection algorithm is based on comparing vectors. Let us define the relation A ≤B on two vectors A and B to mean that each element of A is less than or equal to the corresponding element of B. Mathematically, A ≤B holds if and only if Ai ≤Bi for 1 ≤i ≤m. Each process is initially said to be unmarked. As the algorithm progresses, processes will be marked, indicating that they are able to complete and are thus not deadlocked. When the algorithm terminates, any unmarked processes are known to be deadlocked. This algorithm assumes a worst-case scenario: all processes keep all acquired resources until they exit. The deadlock detection algorithm can now be giv en as follows. 1. Look for an unmarked process, Pi, for which the ith row of R is less than or equal to A. 2. If such a process is found, add the ith row of C to A, mark the process, and go back to step 1. 3. If no such process exists, the algorithm terminates. When the algorithm finishes, all the unmarked processes, if any, are deadlocked. What the algorithm is doing in step 1 is looking for a process that can be run to completion. Such a process is characterized as having resource demands that can be met by the currently available resources. The selected process is then run until it finishes, at which time it returns the resources it is holding to the pool of avail- able resources. It is then marked as completed. If all the processes are ultimately able to run to completion, none of them are deadlocked. If some of them can never
clipped_os_Page_447_Chunk6664
448 DEADLOCKS CHAP. 6 finish, they are deadlocked. Although the algorithm is nondeterministic (because it may run the processes in any feasible order), the result is always the same. As an example of how the deadlock detection algorithm works, see Fig. 6-7. Here we have three processes and four resource classes, which we have arbitrarily labeled tape drives, plotters, scanners, and Blu-ray drives. Process 1 has one scan- ner. Process 2 has two tape drives and a Blu-ray drive. Process 3 has a plotter and two scanners. Each process needs additional resources, as shown by the R matrix. Blu-rays Tape drives Tape drives Plotters Plotters Scanners Scanners Blu-rays E = ( 4 2 3 1 ) Current allocation matrix Request matrix A = ( 2 1 0 0 ) C = 0 0 1 0 2 0 0 1 0 1 2 0 R = 2 0 0 1 1 0 1 0 2 1 0 0 Figure 6-7. An example for the deadlock detection algorithm. To run the deadlock detection algorithm, we look for a process whose resource request can be satisfied. The first one cannot be satisfied because there is no Blu- ray drive available. The second cannot be satisfied either, because there is no scan- ner free. Fortunately, the third one can be satisfied, so process 3 runs and eventual- ly returns all its resources, giving A = (2 2 2 0) At this point process 2 can run and return its resources, giving A = (4 2 2 1) Now the remaining process can run. There is no deadlock in the system. Now consider a minor variation of the situation of Fig. 6-7. Suppose that proc- ess 3 needs a Blu-ray drive as well as the two tape drives and the plotter. None of the requests can be satisfied, so the entire system will eventually be deadlocked. Even if we give process 3 its two tape drives and one plotter, the system deadlocks when it requests the Blu-ray drive. Now that we know how to detect deadlocks (at least with static resource re- quests known in advance), the question of when to look for them comes up. One possibility is to check every time a resource request is made. This is certain to detect them as early as possible, but it is potentially expensive in terms of CPU time. An alternative strategy is to check every k minutes, or perhaps only when the CPU utilization has dropped below some threshold. The reason for considering the CPU utilization is that if enough processes are deadlocked, there will be few run- nable processes, and the CPU will often be idle.
clipped_os_Page_448_Chunk6665
SEC. 6.4 DEADLOCK DETECTION AND RECOVERY 449 6.4.3 Recovery from Deadlock Suppose that our deadlock detection algorithm has succeeded and detected a deadlock. What next? Some way is needed to recover and get the system going again. In this section we will discuss various ways of recovering from deadlock. None of them are especially attractive, howev er. Recovery through Preemption In some cases it may be possible to temporarily take a resource away from its current owner and give it to another process. In many cases, manual intervention may be required, especially in batch-processing operating systems running on mainframes. For example, to take a laser printer away from its owner, the operator can col- lect all the sheets already printed and put them in a pile. Then the process can be suspended (marked as not runnable). At this point the printer can be assigned to another process. When that process finishes, the pile of printed sheets can be put back in the printer’s output tray and the original process restarted. The ability to take a resource away from a process, have another process use it, and then give it back without the process noticing it is highly dependent on the nature of the resource. Recovering this way is frequently difficult or impossible. Choosing the process to suspend depends largely on which ones have resources that can easily be taken back. Recovery through Rollback If the system designers and machine operators know that deadlocks are likely, they can arrange to have processes checkpointed periodically. Checkpointing a process means that its state is written to a file so that it can be restarted later. The checkpoint contains not only the memory image, but also the resource state, in other words, which resources are currently assigned to the process. To be most ef- fective, new checkpoints should not overwrite old ones but should be written to new files, so as the process executes, a whole sequence accumulates. When a deadlock is detected, it is easy to see which resources are needed. To do the recovery, a process that owns a needed resource is rolled back to a point in time before it acquired that resource by starting at one of its earlier checkpoints. All the work done since the checkpoint is lost (e.g., output printed since the check- point must be discarded, since it will be printed again). In effect, the process is reset to an earlier moment when it did not have the resource, which is now assign- ed to one of the deadlocked processes. If the restarted process tries to acquire the resource again, it will have to wait until it becomes available.
clipped_os_Page_449_Chunk6666
450 DEADLOCKS CHAP. 6 Recovery through Killing Processes The crudest but simplest way to break a deadlock is to kill one or more proc- esses. One possibility is to kill a process in the cycle. With a little luck, the other processes will be able to continue. If this does not help, it can be repeated until the cycle is broken. Alternatively, a process not in the cycle can be chosen as the victim in order to release its resources. In this approach, the process to be killed is carefully chosen because it is holding resources that some process in the cycle needs. For example, one process might hold a printer and want a plotter, with another process holding a plotter and wanting a printer. These two are deadlocked. A third process may hold another identical printer and another identical plotter and be happily running. Kill- ing the third process will release these resources and break the deadlock involving the first two. Where possible, it is best to kill a process that can be rerun from the beginning with no ill effects. For example, a compilation can always be rerun because all it does is read a source file and produce an object file. If it is killed partway through, the first run has no influence on the second run. On the other hand, a process that updates a database cannot always be run a second time safely. If the process adds 1 to some field of a table in the database, running it once, killing it, and then running it again will add 2 to the field, which is incorrect. 6.5 DEADLOCK AV OIDANCE In the discussion of deadlock detection, we tacitly assumed that when a proc- ess asks for resources, it asks for them all at once (the R matrix of Fig. 6-6). In most systems, however, resources are requested one at a time. The system must be able to decide whether granting a resource is safe or not and make the allocation only when it is safe. Thus, the question arises: Is there an algorithm that can al- ways avoid deadlock by making the right choice all the time? The answer is a qualified yes—we can avoid deadlocks, but only if certain information is available in advance. In this section we examine ways to avoid deadlock by careful resource allocation. 6.5.1 Resource Trajectories The main algorithms for deadlock avoidance are based on the concept of safe states. Before describing them, we will make a slight digression to look at the con- cept of safety in a graphic and easy-to-understand way. Although the graphical ap- proach does not translate directly into a usable algorithm, it gives a good intuitive feel for the nature of the problem.
clipped_os_Page_450_Chunk6667
SEC. 6.5 DEADLOCK AVOIDANCE 451 In Fig. 6-8 we see a model for dealing with two processes and two resources, for example, a printer and a plotter. The horizontal axis represents the number of instructions executed by process A. The vertical axis represents the number of in- structions executed by process B. At I1 A requests a printer; at I2 it needs a plotter. The printer and plotter are released at I3 and I4, respectively. Process B needs the plotter from I5 to I7 and the printer from I6 to I8. Plotter Printer Printer Plotter B A u (Both processes finished) p q r s t I8 I7 I6 I5 I4 I3 I2 I1
clipped_os_Page_451_Chunk6668
452 DEADLOCKS CHAP. 6 point t the only safe thing to do is run process A until it gets to I4. Beyond that, any trajectory to u will do. The important thing to see here is that at point t, B is requesting a resource. The system must decide whether to grant it or not. If the grant is made, the system will enter an unsafe region and eventually deadlock. To avoid the deadlock, B should be suspended until A has requested and released the plotter. 6.5.2 Safe and Unsafe States The deadlock avoidance algorithms that we will study use the information of Fig. 6-6. At any instant of time, there is a current state consisting of E, A, C, and R. A state is said to be safe if there is some scheduling order in which every proc- ess can run to completion even if all of them suddenly request their maximum number of resources immediately. It is easiest to illustrate this concept by an ex- ample using one resource. In Fig. 6-9(a) we have a state in which A has three instances of the resource but may need as many as nine eventually. B currently has two and may need four altogether, later. Similarly, C also has two but may need an additional fiv e. A total of 10 instances of the resource exist, so with seven re- sources already allocated, three there are still free. A B C 3 2 2 9 4 7 Free: 3 (a) A B C 3 4 2 9 4 7 Free: 1 (b) A B C 3 0 – – 2 9 7 Free: 5 (c) A B C 3 0 7 9 7 Free: 0 (d) – A B C 3 0 0 9 – Free: 7 (e) Has Max Has Max Has Max Has Max Has Max Figure 6-9. Demonstration that the state in (a) is safe. The state of Fig. 6-9(a) is safe because there exists a sequence of allocations that allows all processes to complete. Namely, the scheduler can simply run B exclusively, until it asks for and gets two more instances of the resource, leading to the state of Fig. 6-9(b). When B completes, we get the state of Fig. 6-9(c). Then the scheduler can run C, leading eventually to Fig. 6-9(d). When C completes, we get Fig. 6-9(e). Now A can get the six instances of the resource it needs and also complete. Thus, the state of Fig. 6-9(a) is safe because the system, by careful scheduling, can avoid deadlock. Now suppose we have the initial state shown in Fig. 6-10(a), but this time A requests and gets another resource, giving Fig. 6-10(b). Can we find a sequence that is guaranteed to work? Let us try. The scheduler could run B until it asked for all its resources, as shown in Fig. 6-10(c). Eventually, B completes and we get the state of Fig. 6-10(d). At this point we are stuck. We only have four instances of the resource free, and each of the active
clipped_os_Page_452_Chunk6669
SEC. 6.5 DEADLOCK AVOIDANCE 453 A B C 3 2 2 9 4 7 Free: 3 (a) A B C 4 2 2 9 4 7 Free: 2 (b) A B C 4 4 — 4 2 9 7 Free: 0 (c) A B C 4 — 2 9 7 Free: 4 (d) Has Max Has Max Has Max Has Max Figure 6-10. Demonstration that the state in (b) is not safe. processes needs fiv e. There is no sequence that guarantees completion. Thus, the allocation decision that moved the system from Fig. 6-10(a) to Fig. 6-10(b) went from a safe to an unsafe state. Running A or C next starting at Fig. 6-10(b) does not work either. In retrospect, A’s request should not have been granted. It is worth noting that an unsafe state is not a deadlocked state. Starting at Fig. 6-10(b), the system can run for a while. In fact, one process can even com- plete. Furthermore, it is possible that A might release a resource before asking for any more, allowing C to complete and avoiding deadlock altogether. Thus, the dif- ference between a safe state and an unsafe state is that from a safe state the system can guarantee that all processes will finish; from an unsafe state, no such guaran- tee can be given. 6.5.3 The Banker’s Algorithm for a Single Resource A scheduling algorithm that can avoid deadlocks is due to Dijkstra (1965); it is known as the banker’s algorithm and is an extension of the deadlock detection al- gorithm given in Sec. 3.4.1. It is modeled on the way a small-town banker might deal with a group of customers to whom he has granted lines of credit. (Years ago, banks did not lend money unless they knew they could be repaid.) What the algo- rithm does is check to see if granting the request leads to an unsafe state. If so, the request is denied. If granting the request leads to a safe state, it is carried out. In Fig. 6-11(a) we see four customers, A, B, C, and D, each of whom has been granted a certain number of credit units (e.g., 1 unit is 1K dollars). The banker knows that not all customers will need their maximum credit immediately, so he has reserved only 10 units rather than 22 to service them. (In this analogy, customers are proc- esses, units are, say, tape drives, and the banker is the operating system.) The customers go about their respective businesses, making loan requests from time to time (i.e., asking for resources). At a certain moment, the situation is as shown in Fig. 6-11(b). This state is safe because with two units left, the banker can delay any requests except C’s, thus letting C finish and release all four of his re- sources. With four units in hand, the banker can let either D or B have the neces- sary units, and so on. Consider what would happen if a request from B for one more unit were grant- ed in Fig. 6-11(b). We would have situation Fig. 6-11(c), which is unsafe. If all
clipped_os_Page_453_Chunk6670
454 DEADLOCKS CHAP. 6 A B C D 0 0 0 0 6 Has Max 5 4 7 Free: 10 A B C D 1 1 2 4 6 Has Max 5 4 7 Free: 2 A B C D 1 2 2 4 6 Has Max 5 4 7 Free: 1 (a) (b) (c) Figure 6-11. Three resource allocation states: (a) Safe. (b) Safe. (c) Unsafe. the customers suddenly asked for their maximum loans, the banker could not sat- isfy any of them, and we would have a deadlock. An unsafe state does not have to lead to deadlock, since a customer might not need the entire credit line available, but the banker cannot count on this behavior. The banker’s algorithm considers each request as it occurs, seeing whether granting it leads to a safe state. If it does, the request is granted; otherwise, it is postponed until later. To see if a state is safe, the banker checks to see if he has enough resources to satisfy some customer. If so, those loans are assumed to be repaid, and the customer now closest to the limit is checked, and so on. If all loans can eventually be repaid, the state is safe and the initial request can be granted. 6.5.4 The Banker’s Algorithm for Multiple Resources The banker’s algorithm can be generalized to handle multiple resources. Fig- ure 6-12 shows how it works. Blu-rays Printers Printers Plotters Plotters Tape drives Tape drives Process Process Blu-rays A 3 0 1 1 B 0 1 0 0 C 1 1 1 0 D 1 1 0 1 E 0 0 Resources assigned 0 0 A 1 1 0 0 B 0 1 1 2 C 3 1 0 0 D 0 0 1 0 E 2 1 Resources still assigned 1 0 E = (6342) P = (5322) A = (1020) Figure 6-12. The banker’s algorithm with multiple resources. In Fig. 6-12 we see two matrices. The one on the left shows how many of each resource are currently assigned to each of the fiv e processes. The matrix on the right shows how many resources each process still needs in order to complete.
clipped_os_Page_454_Chunk6671
SEC. 6.5 DEADLOCK AVOIDANCE 455 These matrices are just C and R from Fig. 6-6. As in the single-resource case, processes must state their total resource needs before executing, so that the system can compute the right-hand matrix at each instant. The three vectors at the right of the figure show the existing resources, E, the possessed resources, P, and the available resources, A, respectively. From E we see that the system has six tape drives, three plotters, four printers, and two Blu-ray drives. Of these, fiv e tape drives, three plotters, two printers, and two Blu-ray drives are currently assigned. This fact can be seen by adding up the entries in the four resource columns in the left-hand matrix. The available resource vector is just the difference between what the system has and what is currently in use. The algorithm for checking to see if a state is safe can now be stated. 1. Look for a row, R, whose unmet resource needs are all smaller than or equal to A. If no such row exists, the system will eventually deadlock since no process can run to completion (assuming processes keep all resources until they exit). 2. Assume the process of the chosen row requests all the resources it needs (which is guaranteed to be possible) and finishes. Mark that process as terminated and add all of its resources to the A vector. 3. Repeat steps 1 and 2 until either all processes are marked terminated (in which case the initial state was safe) or no process is left whose resource needs can be met (in which case the system was not safe). If several processes are eligible to be chosen in step 1, it does not matter which one is selected: the pool of available resources either gets larger, or at worst, stays the same. Now let us get back to the example of Fig. 6-12. The current state is safe. Suppose that process B now makes a request for the printer. This request can be granted because the resulting state is still safe (process D can finish, and then proc- esses A or E, followed by the rest). Now imagine that after giving B one of the two remaining printers, E wants the last printer. Granting that request would reduce the vector of available resources to (1 0 0 0), which leads to deadlock, so E’s request must be deferred for a while. The banker’s algorithm was first published by Dijkstra in 1965. Since that time, nearly every book on operating systems has described it in detail. Innumer- able papers have been written about various aspects of it. Unfortunately, few authors have had the audacity to point out that although in theory the algorithm is wonderful, in practice it is essentially useless because processes rarely know in ad- vance what their maximum resource needs will be. In addition, the number of processes is not fixed, but dynamically varying as new users log in and out. Fur- thermore, resources that were thought to be available can suddenly vanish (tape drives can break). Thus, in practice, few, if any, existing systems use the banker’s algorithm for avoiding deadlocks. Some systems, however, use heuristics similar to
clipped_os_Page_455_Chunk6672
456 DEADLOCKS CHAP. 6 those of the banker’s algorithm to prevent deadlock. For instance, networks may throttle traffic when buffer utilization reaches higher than, say, 70%—estimating that the remaining 30% will be sufficient for current users to complete their service and return their resources. 6.6 DEADLOCK PREVENTION Having seen that deadlock avoidance is essentially impossible, because it re- quires information about future requests, which is not known, how do real systems avoid deadlock? The answer is to go back to the four conditions stated by Coff- man et al. (1971) to see if they can provide a clue. If we can ensure that at least one of these conditions is never satisfied, then deadlocks will be structurally im- possible (Havender, 1968). 6.6.1 Attacking the Mutual-Exclusion Condition First let us attack the mutual exclusion condition. If no resource were ever as- signed exclusively to a single process, we would never hav e deadlocks. For data, the simplest method is to make data read only, so that processes can use the data concurrently. Howev er, it is equally clear that allowing two processes to write on the printer at the same time will lead to chaos. By spooling printer output, several processes can generate output at the same time. In this model, the only process that actually requests the physical printer is the printer daemon. Since the daemon never requests any other resources, we can eliminate deadlock for the printer. If the daemon is programmed to begin printing even before all the output is spooled, the printer might lie idle if an output process decides to wait several hours after the first burst of output. For this reason, daemons are normally programmed to print only after the complete output file is available. However, this decision it- self could lead to deadlock. What would happen if two processes each filled up one half of the available spooling space with output and neither was finished pro- ducing its full output? In this case, we would have two processes that had each fin- ished part, but not all, of their output, and could not continue. Neither process will ev er finish, so we would have a deadlock on the disk. Nevertheless, there is a germ of an idea here that is frequently applicable. Av oid assigning a resource unless absolutely necessary, and try to make sure that as few processes as possible may actually claim the resource. 6.6.2 Attacking the Hold-and-Wait Condition The second of the conditions stated by Coffman et al. looks slightly more promising. If we can prevent processes that hold resources from waiting for more resources, we can eliminate deadlocks. One way to achieve this goal is to require
clipped_os_Page_456_Chunk6673
SEC. 6.6 DEADLOCK PREVENTION 457 all processes to request all their resources before starting execution. If ev erything is available, the process will be allocated whatever it needs and can run to comple- tion. If one or more resources are busy, nothing will be allocated and the process will just wait. An immediate problem with this approach is that many processes do not know how many resources they will need until they hav e started running. In fact, if they knew, the banker’s algorithm could be used. Another problem is that resources will not be used optimally with this approach. Take, as an example, a process that reads data from an input tape, analyzes it for an hour, and then writes an output tape as well as plotting the results. If all resources must be requested in advance, the process will tie up the output tape drive and the plotter for an hour. Nevertheless, some mainframe batch systems require the user to list all the re- sources on the first line of each job. The system then preallocates all resources im- mediately and does not release them until they are no longer needed by the job (or in the simplest case, until the job finishes). While this method puts a burden on the programmer and wastes resources, it does prevent deadlocks. A slightly different way to break the hold-and-wait condition is to require a process requesting a resource to first temporarily release all the resources it cur- rently holds. Then it tries to get everything it needs all at once. 6.6.3 Attacking the No-Preemption Condition Attacking the third condition (no preemption) is also a possibility. If a process has been assigned the printer and is in the middle of printing its output, forcibly taking away the printer because a needed plotter is not available is tricky at best and impossible at worst. However, some resources can be virtualized to avoid this situation. Spooling printer output to the disk and allowing only the printer daemon access to the real printer eliminates deadlocks involving the printer, although it cre- ates a potential for deadlock over disk space. With large disks though, running out of disk space is unlikely. However, not all resources can be virtualized like this. For example, records in databases or tables inside the operating system must be locked to be used and therein lies the potential for deadlock. 6.6.4 Attacking the Circular Wait Condition Only one condition is left. The circular wait can be eliminated in several ways. One way is simply to have a rule saying that a process is entitled only to a single resource at any moment. If it needs a second one, it must release the first one. For a process that needs to copy a huge file from a tape to a printer, this restriction is unacceptable. Another way to avoid the circular wait is to provide a global numbering of all the resources, as shown in Fig. 6-13(a). Now the rule is this: processes can request
clipped_os_Page_457_Chunk6674
458 DEADLOCKS CHAP. 6 resources whenever they want to, but all requests must be made in numerical order. A process may request first a printer and then a tape drive, but it may not request first a plotter and then a printer. (a) (b) 1. Imagesetter 2. Printer 3. Plotter 4. Tape drive 5. Blu-ray drive A i B j Figure 6-13. (a) Numerically ordered resources. (b) A resource graph. With this rule, the resource allocation graph can never hav e cycles. Let us see why this is true for the case of two processes, in Fig. 6-13(b). We can get a dead- lock only if A requests resource j and B requests resource i. Assuming i and j are distinct resources, they will have different numbers. If i > j, then A is not allowed to request j because that is lower than what it already has. If i < j, then B is not al- lowed to request i because that is lower than what it already has. Either way, dead- lock is impossible. With more than two processes, the same logic holds. At every instant, one of the assigned resources will be highest. The process holding that resource will never ask for a resource already assigned. It will either finish, or at worst, request ev en higher-numbered resources, all of which are available. Eventually, it will fin- ish and free its resources. At this point, some other process will hold the highest resource and can also finish. In short, there exists a scenario in which all processes finish, so no deadlock is present. A minor variation of this algorithm is to drop the requirement that resources be acquired in strictly increasing sequence and merely insist that no process request a resource lower than what it is already holding. If a process initially requests 9 and 10, and then releases both of them, it is effectively starting all over, so there is no reason to prohibit it from now requesting resource 1. Although numerically ordering the resources eliminates the problem of dead- locks, it may be impossible to find an ordering that satisfies everyone. When the resources include process-table slots, disk spooler space, locked database records, and other abstract resources, the number of potential resources and different uses may be so large that no ordering could possibly work. Various approaches to deadlock prevention are summarized in Fig. 6-14. 6.7 OTHER ISSUES In this section we will discuss a few miscellaneous issues related to deadlocks. These include two-phase locking, nonresource deadlocks, and starvation.
clipped_os_Page_458_Chunk6675
SEC. 6.7 OTHER ISSUES 459 Condition Approach Mutual exclusion Spool ev erything Hold and wait Request all resources initially No preemption Take resources away Circular wait Order resources numer ically Figure 6-14. Summary of approaches to deadlock prevention. 6.7.1 Two-Phase Locking Although both avoidance and prevention are not terribly promising in the gen- eral case, for specific applications, many excellent special-purpose algorithms are known. As an example, in many database systems, an operation that occurs fre- quently is requesting locks on several records and then updating all the locked records. When multiple processes are running at the same time, there is a real dan- ger of deadlock. The approach often used is called two-phase locking. In the first phase, the process tries to lock all the records it needs, one at a time. If it succeeds, it begins the second phase, performing its updates and releasing the locks. No real work is done in the first phase. If during the first phase, some record is needed that is already locked, the proc- ess just releases all its locks and starts the first phase all over. In a certain sense, this approach is similar to requesting all the resources needed in advance, or at least before anything irreversible is done. In some versions of two-phase locking, there is no release and restart if a locked record is encountered during the first phase. In these versions, deadlock can occur. However, this strategy is not applicable in general. In real-time systems and process control systems, for example, it is not acceptable to just terminate a proc- ess partway through because a resource is not available and start all over again. Neither is it acceptable to start over if the process has read or written messages to the network, updated files, or anything else that cannot be safely repeated. The al- gorithm works only in those situations where the programmer has very carefully arranged things so that the program can be stopped at any point during the first phase and restarted. Many applications cannot be structured this way. 6.7.2 Communication Deadlocks All of our work so far has concentrated on resource deadlocks. One process wants something that another process has and must wait until the first one gives it up. Sometimes the resources are hardware or software objects, such as Blu-ray drives or database records, but sometimes they are more abstract. Resource dead- lock is a problem of competition synchronization. Independent processes would
clipped_os_Page_459_Chunk6676
460 DEADLOCKS CHAP. 6 complete service if their execution were not interleaved with competing processes. A process locks resources in order to prevent inconsistent resource states caused by interleaved access to resources. Interleaved access to locked resources, however, enables resource deadlock. In Fig. 6-2 we saw a resource deadlock where the re- sources were semaphores. A semaphore is a bit more abstract than a Blu-ray drive, but in this example, each process successfully acquired a resource (one of the semaphores) and deadlocked trying to acquire another one (the other semaphore). This situation is a classical resource deadlock. However, as we mentioned at the start of the chapter, while resource deadlocks are the most common kind, they are not the only kind. Another kind of deadlock can occur in communication systems (e.g., networks), in which two or more proc- esses communicate by sending messages. A common arrangement is that process A sends a request message to process B, and then blocks until B sends back a reply message. Suppose that the request message gets lost. A is blocked waiting for the reply. B is blocked waiting for a request asking it to do something. We hav e a deadlock. This, though, is not the classical resource deadlock. A does not have posses- sion of some resource B wants, and vice versa. In fact, there are no resources at all in sight. But it is a deadlock according to our formal definition since we have a set of (two) processes, each blocked waiting for an event only the other one can cause. This situation is called a communication deadlock to contrast it with the more common resource deadlock. Communication deadlock is an anomaly of coopera- tion synchronization. The processes in this type of deadlock could not complete service if executed independently. Communication deadlocks cannot be prevented by ordering the resources (since there are no resources) or avoided by careful scheduling (since there are no moments when a request could be postponed). Fortunately, there is another techni- que that can usually be employed to break communication deadlocks: timeouts. In most network communication systems, whenever a message is sent to which a re- ply is expected, a timer is started. If the timer goes off before the reply arrives, the sender of the message assumes that the message has been lost and sends it again (and again and again if needed). In this way, the deadlock is broken. Phrased dif- ferently, the timeout serves as a heuristic to detect deadlocks and enables recovery. This heuristic is applicable to resource deadlock also and is relied upon by users with temperamental or buggy device drivers that can deadlock and freeze the sys- tem. Of course, if the original message was not lost but the reply was simply delay- ed, the intended recipient may get the message two or more times, possibly with undesirable consequences. Think about an electronic banking system in which the message contains instructions to make a payment. Clearly, that should not be re- peated (and executed) multiple times just because the network is slow or the time- out too short. Designing the communication rules, called the protocol, to get ev erything right is a complex subject, but one far beyond the scope of this book.
clipped_os_Page_460_Chunk6677
SEC. 6.7 OTHER ISSUES 461 Readers interested in network protocols might be interested in another book by one of the authors, Computer Networks (Tanenbaum and Wetherall, 2010). Not all deadlocks occurring in communication systems or networks are com- munication deadlocks. Resource deadlocks can also occur there. Consider, for ex- ample, the network of Fig. 6-15. It is a simplified view of the Internet. Very sim- plified. The Internet consists of two kinds of computers: hosts and routers. A host is a user computer, either someone’s tablet or PC at home, a PC at a company, or a corporate server. Hosts do work for people. A router is a specialized communica- tions computer that moves packets of data from the source to the destination. Each host is connected to one or more routers, either by a DSL line, cable TV con- nection, LAN, dial-up line, wireless network, optical fiber, or something else. A B D C Host Host Host Host Buffer Router Figure 6-15. A resource deadlock in a network. When a packet comes into a router from one of its hosts, it is put into a buffer for subsequent transmission to another router and then to another until it gets to the destination. These buffers are resources and there are a finite number of them. In Fig. 6-16 each router has only eight buffers (in practice they hav e millions, but that does not change the nature of the potential deadlock, just its frequency). Suppose that all the packets at router A need to go to B and all the packets at B need to go to C and all the packets at C need to go to D and all the packets at D need to go to A. No packet can move because there is no buffer at the other end and we have a clas- sical resource deadlock, albeit in the middle of a communications system. 6.7.3 Livelock In some situations, a process tries to be polite by giving up the locks it already acquired whenever it notices that it cannot obtain the next lock it needs. Then it waits a millisecond, say, and tries again. In principle, this is good and should help to detect and avoid deadlock. However, if the other process does the same thing at exactly the same time, they will be in the situation of two people trying to pass each other on the street when both of them politely step aside, and yet no progress is possible, because they keep stepping the same way at the same time.
clipped_os_Page_461_Chunk6678
462 DEADLOCKS CHAP. 6 Consider an atomic primitive try lock in which the calling process tests a mutex and either grabs it or returns failure. In other words, it never blocks. Pro- grammers can use it together with acquire lock which also tries to grab the lock, but blocks if the lock is not available. Now imagine a pair of processes running in parallel (perhaps on different cores) that use two resources, as shown in Fig. 6-16. Each one needs two resources and uses the try lock primitive to try to acquire the necessary locks. If the attempt fails, the process gives up the lock it holds and tries again. In Fig. 6-16, process A runs and acquires resource 1, while process 2 runs and acquires resource 2. Next, they try to acquire the other lock and fail. To be polite, they giv e up the lock they are currently holding and try again. This proce- dure repeats until a bored user (or some other entity) puts one of these processes out of its misery. Clearly, no process is blocked and we could even say that things are happening, so this is not a deadlock. Still, no progress is possible, so we do have something equivalent: a livelock. void process A(void) { acquire lock(&resource 1); while (try lock(&resource 2) == FAIL) { release lock(&resource 1); wait fixed time(); acquire lock(&resource 1); } use both resources( ); release lock(&resource 2); release lock(&resource 1); } void process A(void) { acquire lock(&resource 2); while (try lock(&resource 1) == FAIL) { release lock(&resource 2); wait fixed time(); acquire lock(&resource 2); } use both resources( ); release lock(&resource 1); release lock(&resource 2); } Figure 6-16. Polite processes that may cause livelock. Livelock and deadlock can occur in surprising ways. In some systems, the total number of processes allowed is determined by the number of entries in the process table. Thus, process-table slots are finite resources. If a fork fails because the table is full, a reasonable approach for the program doing the fork is to wait a random time and try again.
clipped_os_Page_462_Chunk6679
SEC. 6.7 OTHER ISSUES 463 Now suppose that a UNIX system has 100 process slots. Ten programs are running, each of which needs to create 12 children. After each process has created 9 processes, the 10 original processes and the 90 new processes have exhausted the table. Each of the 10 original processes now sits in an endless loop forking and failing—a livelock. The probability of this happening is minuscule, but it could happen. Should we abandon processes and the fork call to eliminate the problem? The maximum number of open files is similarly restricted by the size of the i- node table, so a similar problem occurs when it fills up. Swap space on the disk is another limited resource. In fact, almost every table in the operating system represents a finite resource. Should we abolish all of these because it might hap- pen that a collection of n processes might each claim 1/n of the total, and then each try to claim another one? Probably not a good idea. Most operating systems, including UNIX and Windows, basically just ignore the problem on the assumption that most users would prefer an occasional livelock (or even deadlock) to a rule restricting all users to one process, one open file, and one of everything. If these problems could be eliminated for free, there would not be much discussion. The problem is that the price is high, mostly in terms of put- ting inconvenient restrictions on processes. Thus, we are faced with an unpleasant trade-off between convenience and correctness, and a great deal of discussion about which is more important, and to whom. 6.7.4 Starvation A problem closely related to deadlock and livelock is starvation. In a dynam- ic system, requests for resources happen all the time. Some policy is needed to make a decision about who gets which resource when. This policy, although seem- ingly reasonable, may lead to some processes never getting service even though they are not deadlocked. As an example, consider allocation of the printer. Imagine that the system uses some algorithm to ensure that allocating the printer does not lead to deadlock. Now suppose that several processes all want it at once. Who should get it? One possible allocation algorithm is to give it to the process with the smallest file to print (assuming this information is available). This approach maximizes the number of happy customers and seems fair. Now consider what happens in a busy system when one process has a huge file to print. Every time the printer is free, the system will look around and choose the process with the shortest file. If there is a constant stream of processes with short files, the process with the huge file will never be allocated the printer. It will simply starve to death (be postponed indefi- nitely, even though it is not blocked). Starvation can be avoided by using a first-come, first-served resource alloca- tion policy. With this approach, the process waiting the longest gets served next. In due course of time, any giv en process will eventually become the oldest and thus get the needed resource.
clipped_os_Page_463_Chunk6680
464 DEADLOCKS CHAP. 6 It is worth mentioning that some people do not make a distinction between starvation and deadlock because in both cases there is no forward progress. Others feel that they are fundamentally different because a process could easily be pro- grammed to try to do something n times and, if all of them failed, try something else. A blocked process does not have that choice. 6.8 RESEARCH ON DEADLOCKS If ever there was a subject that was investigated mercilessly during the early days of operating systems, it was deadlocks. The reason is that deadlock detection is a nice little graph-theory problem that one mathematically inclined graduate stu- dent could get his jaws around and chew on for 4 years. Many algorithms were de- vised, each one more exotic and less practical than the previous one. Most of that work has died out. Still, a few papers are still being published on deadlocks. Recent work on deadlocks includes the research into deadlock immunity (Jula et al., 2011). The main idea of this approach is that applications detect deadlocks when they occur and then save their ‘‘signatures,’’ so as to avoid the same deadlock in future runs. Marino et al. (2013), on the other hand, use concurrency control to make sure that deadlocks cannot occur in the first place. Another research direction is to try and detect deadlocks. Recent work on deadlock detection was presented by Pyla and Varadarajan (2012). The work by Cai and Chan (2012), presents a new dynamic deadlock detection scheme that iter- atively prunes lock dependencies that have no incoming or outgoing edges. The problem of deadlock creeps up everywhere. Wu et al. (2013) describe a deadlock control system for automated manufacturing systems. It models such sys- tems using Petri nets to look for necessary and sufficient conditions to allow for permissive deadlock control. There is also much research on distributed deadlock detection, especially in high-performance computing. For instance, there is a significant body of work on deadlock detection-based scheduling. Wang and Lu (2013) present a scheduling al- gorithm for workflow computations in the presence of storage constraints. Hilbrich et al. (2013) describe runtime deadlock detection for MPI. Finally, there is a huge amount of theoretical work on distributed deadlock detection. However, we will not consider it here because (1) it is outside the scope of this book, and (2) none of it is even remotely practical in real systems. Its main function seems to be keeping otherwise unemployed graph theorists off the streets. 6.9 SUMMARY Deadlock is a potential problem in any operating system. It occurs when all the members of a set of processes are blocked waiting for an event that only other members of the same set can cause. This situation causes all the processes to wait
clipped_os_Page_464_Chunk6681
SEC. 6.9 SUMMARY 465 forever. Commonly the event that the processes are waiting for is the release of some resource held by another member of the set. Another situation in which deadlock is possible is when a set of communicating processes are all waiting for a message and the communication channel is empty and no timeouts are pending. Resource deadlock can be avoided by keeping track of which states are safe and which are unsafe. A safe state is one in which there exists a sequence of ev ents that guarantee that all processes can finish. An unsafe state has no such guarantee. The banker’s algorithm avoids deadlock by not granting a request if that request will put the system in an unsafe state. Resource deadlock can be structurally prevented by building the system in such a way that it can never occur by design. For example, by allowing a process to hold only one resource at any instant the circular wait condition required for deadlock is broken. Resource deadlock can also be prevented by numbering all the resources and making processes request them in strictly increasing order. Resource deadlock is not the only kind of deadlock. Communication deadlock is also a potential problem in some systems although it can often be handled by setting appropriate timeouts. Livelock is similar to deadlock in that it can stop all forward progress, but it is technically different since it involves processes that are not actually blocked. Star- vation can be avoided by a first-come, first-served allocation policy. PROBLEMS 1. Give an example of a deadlock taken from politics. 2. Students working at individual PCs in a computer laboratory send their files to be printed by a server that spools the files on its hard disk. Under what conditions may a deadlock occur if the disk space for the print spool is limited? How may the deadlock be avoided? 3. In the preceding question, which resources are preemptable and which are nonpre- emptable? 4. In Fig. 6-1 the resources are returned in the reverse order of their acquisition. Would giving them back in the other order be just as good? 5. The four conditions (mutual exclusion, hold and wait, no preemption and circular wait) are necessary for a resource deadlock to occur. Giv e an example to show that these conditions are not sufficient for a resource deadlock to occur. When are these condi- tions sufficient for a resource deadock to occur? 6. City streets are vulnerable to a circular blocking condition called gridlock, in which intersections are blocked by cars that then block cars behind them that then block the cars that are trying to enter the previous intersection, etc. All intersections around a city block are filled with vehicles that block the oncoming traffic in a circular manner.
clipped_os_Page_465_Chunk6682
466 DEADLOCKS CHAP. 6 Gridlock is a resource deadlock and a problem in competition synchronization. New York City’s prevention algorithm, called "don’t block the box," prohibits cars from entering an intersection unless the space following the intersection is also available. Which prevention algorithm is this? Can you provide any other prevention algorithms for gridlock? 7. Suppose four cars each approach an intersection from four different directions simul- taneously. Each corner of the intersection has a stop sign. Assume that traffic regula- tions require that when two cars approach adjacent stop signs at the same time, the car on the left must yield to the car on the right. Thus, as four cars each drive up to their individual stop signs, each waits (indefinitely) for the car on the left to proceed. Is this anomaly a communication deadlock? Is it a resource deadlock? 8. Is it possible that a resource deadlock involves multiple units of one type and a single unit of another? If so, give an example. 9. Fig. 6-3 shows the concept of a resource graph. Do illegal graphs exist, that is, graphs that structurally violate the model we have used of resource usage? If so, give an ex- ample of one. 10. Consider Fig. 6-4. Suppose that in step (o) C requested S instead of requesting R. Would this lead to deadlock? Suppose that it requested both S and R. 11. Suppose that there is a resource deadlock in a system. Give an example to show that the set of processes deadlocked can include processes that are not in the circular chain in the corresponding resource allocation graph. 12. In order to control traffic, a network router, A periodically sends a message to its neighbor, B, telling it to increase or decrease the number of packets that it can handle. At some point in time, Router A is flooded with traffic and sends B a message telling it to cease sending traffic. It does this by specifying that the number of bytes B may send (A’s window size) is 0. As traffic surges decrease, A sends a new message, telling B to restart transmission. It does this by increasing the window size from 0 to a positive number. That message is lost. As described, neither side will ever transmit. What type of deadlock is this? 13. The discussion of the ostrich algorithm mentions the possibility of process-table slots or other system tables filling up. Can you suggest a way to enable a system administra- tor to recover from such a situation? 14. Consider the following state of a system with four processes, P1, P2, P3, and P4, and five types of resources, RS1, RS2, RS3, RS4, and RS5: 0 0 0 2 1 0 0 0 1 1 0 0 E = (24144) A = (01021) C = R = 1 2 1 0 0 1 1 0 1 1 0 2 1 0 1 0 2 1 0 2 0 3 1 0 2 1 1 0 Using the deadlock detection algorithm described in Section 6.4.2, show that there is a deadlock in the system. Identify the processes that are deadlocked.
clipped_os_Page_466_Chunk6683
CHAP. 6 PROBLEMS 467 15. Explain how the system can recover from the deadlock in previous problem using (a) recovery through preemption. (b) recovery through rollback. (c) recovery through killing processes. 16. Suppose that in Fig. 6-6 Cij + Rij > E j for some i. What implications does this have for the system? 17. All the trajectories in Fig. 6-8 are horizontal or vertical. Can you envision any circum- stances in which diagonal trajectories are also possible? 18. Can the resource trajectory scheme of Fig. 6-8 also be used to illustrate the problem of deadlocks with three processes and three resources? If so, how can this be done? If not, why not? 19. In theory, resource trajectory graphs could be used to avoid deadlocks. By clever scheduling, the operating system could avoid unsafe regions. Is there a practical way of actually doing this? 20. Can a system be in a state that is neither deadlocked nor safe? If so, give an example. If not, prove that all states are either deadlocked or safe. 21. Take a careful look at Fig. 6-11(b). If D asks for one more unit, does this lead to a safe state or an unsafe one? What if the request came from C instead of D? 22. A system has two processes and three identical resources. Each process needs a maxi- mum of two resources. Is deadlock possible? Explain your answer. 23. Consider the previous problem again, but now with p processes each needing a maxi- mum of m resources and a total of r resources available. What condition must hold to make the system deadlock free? 24. Suppose that process A in Fig. 6-12 requests the last tape drive. Does this action lead to a deadlock? 25. The banker’s algorithm is being run in a system with m resource classes and n proc- esses. In the limit of large m and n, the number of operations that must be performed to check a state for safety is proportional to manb. What are the values of a and b? 26. A system has four processes and fiv e allocatable resources. The current allocation and maximum needs are as follows: Allocated Maximum Available Process A 1 0 2 1 1 1 1 2 1 3 0 0 x 1 1 Process B 2 0 1 1 0 2 2 2 1 0 Process C 1 1 0 1 0 2 1 3 1 0 Process D 1 1 1 1 0 1 1 2 2 1 What is the smallest value of x for which this is a safe state? 27. One way to eliminate circular wait is to have rule saying that a process is entitled only to a single resource at any moment. Give an example to show that this restriction is unacceptable in many cases.
clipped_os_Page_467_Chunk6684
468 DEADLOCKS CHAP. 6 28. Tw o processes, A and B, each need three records, 1, 2, and 3, in a database. If A asks for them in the order 1, 2, 3, and B asks for them in the same order, deadlock is not possible. However, if B asks for them in the order 3, 2, 1, then deadlock is possible. With three resources, there are 3! or six possible combinations in which each process can request them. What fraction of all the combinations is guaranteed to be deadlock free? 29. A distributed system using mailboxes has two IPC primitives, send and receive. The latter primitive specifies a process to receive from and blocks if no message from that process is available, even though messages may be waiting from other processes. There are no shared resources, but processes need to communicate frequently about other matters. Is deadlock possible? Discuss. 30. In an electronic funds transfer system, there are hundreds of identical processes that work as follows. Each process reads an input line specifying an amount of money, the account to be credited, and the account to be debited. Then it locks both accounts and transfers the money, releasing the locks when done. With many processes running in parallel, there is a very real danger that a process having locked account x will be unable to lock y because y has been locked by a process now waiting for x. Devise a scheme that avoids deadlocks. Do not release an account record until you have com- pleted the transactions. (In other words, solutions that lock one account and then re- lease it immediately if the other is locked are not allowed.) 31. One way to prevent deadlocks is to eliminate the hold-and-wait condition. In the text it was proposed that before asking for a new resource, a process must first release what- ev er resources it already holds (assuming that is possible). However, doing so intro- duces the danger that it may get the new resource but lose some of the existing ones to competing processes. Propose an improvement to this scheme. 32. A computer science student assigned to work on deadlocks thinks of the following bril- liant way to eliminate deadlocks. When a process requests a resource, it specifies a time limit. If the process blocks because the resource is not available, a timer is start- ed. If the time limit is exceeded, the process is released and allowed to run again. If you were the professor, what grade would you give this proposal and why? 33. Main memory units are preempted in swapping and virtual memory systems. The processor is preempted in time-sharing environments. Do you think that these preemp- tion methods were developed to handle resource deadlock or for other purposes? How high is their overhead? 34. Explain the differences between deadlock, livelock, and starvation. 35. Assume two processes are issuing a seek command to reposition the mechanism to ac- cess the disk and enable a read command. Each process is interrupted before executing its read, and discovers that the other has moved the disk arm. Each then reissues the seek command, but is again interrupted by the other. This sequence continually repeats. Is this a resource deadlock or a livelock? What methods would you recommend to handle the anomaly? 36. Local Area Networks utilize a media access method called CSMA/CD, in which sta- tions sharing a bus can sense the medium and detect transmissions as well as collis-
clipped_os_Page_468_Chunk6685
CHAP. 6 PROBLEMS 469 ions. In the Ethernet protocol, stations requesting the shared channel do not transmit frames if they sense the medium is busy. When such transmission has terminated, waiting stations each transmit their frames. Two frames that are transmitted at the same time will collide. If stations immediately and repeatedly retransmit after collision de- tection, they will continue to collide indefinitely. (a) Is this a resource deadlock or a livelock? (b) Can you suggest a solution to this anomaly? (c) Can starvation occur with this scenario? 37. A program contains an error in the order of cooperation and competition mechanisms, resulting in a consumer process locking a mutex (mutual exclusion semaphore) before it blocks on an empty buffer. The producer process blocks on the mutex before it can place a value in the empty buffer and awaken the consumer. Thus, both processes are blocked forever, the producer waiting for the mutex to be unlocked and the consumer waiting for a signal from the producer. Is this a resource deadlock or a communication deadlock? Suggest methods for its control. 38. Cinderella and the Prince are getting divorced. To divide their property, they hav e agreed on the following algorithm. Every morning, each one may send a letter to the other’s lawyer requesting one item of property. Since it takes a day for letters to be de- livered, they hav e agreed that if both discover that they hav e requested the same item on the same day, the next day they will send a letter canceling the request. Among their property is their dog, Woofer, Woofer’s doghouse, their canary, Tweeter, and Tweeter’s cage. The animals love their houses, so it has been agreed that any division of property separating an animal from its house is invalid, requiring the whole division to start over from scratch. Both Cinderella and the Prince desperately want Woofer. So that they can go on (separate) vacations, each spouse has programmed a personal com- puter to handle the negotiation. When they come back from vacation, the computers are still negotiating. Why? Is deadlock possible? Is starvation possible? Discuss your answer. 39. A student majoring in anthropology and minoring in computer science has embarked on a research project to see if African baboons can be taught about deadlocks. He locates a deep canyon and fastens a rope across it, so the baboons can cross hand-over- hand. Several baboons can cross at the same time, provided that they are all going in the same direction. If eastward-moving and westward-moving baboons ever get onto the rope at the same time, a deadlock will result (the baboons will get stuck in the mid- dle) because it is impossible for one baboon to climb over another one while suspended over the canyon. If a baboon wants to cross the canyon, he must check to see that no other baboon is currently crossing in the opposite direction. Write a program using semaphores that avoids deadlock. Do not worry about a series of eastward-moving baboons holding up the westward-moving baboons indefinitely. 40. Repeat the previous problem, but now avoid starvation. When a baboon that wants to cross to the east arrives at the rope and finds baboons crossing to the west, he waits until the rope is empty, but no more westward-moving baboons are allowed to start until at least one baboon has crossed the other way.
clipped_os_Page_469_Chunk6686
470 DEADLOCKS CHAP. 6 41. Program a simulation of the banker’s algorithm. Your program should cycle through each of the bank clients asking for a request and evaluating whether it is safe or unsafe. Output a log of requests and decisions to a file. 42. Write a program to implement the deadlock detection algorithm with multiple re- sources of each type. Your program should read from a file the following inputs: the number of processes, the number of resource types, the number of resources of each type in existence (vector E), the current allocation matrix C (first row, followed by the second row, and so on), the request matrix R (first row, followed by the second row, and so on). The output of your program should indicate whether there is a deadlock in the system. In case there is, the program should print out the identities of all processes that are deadlocked. 43. Write a program that detects if there is a deadlock in the system by using a resource al- location graph. Your program should read from a file the following inputs: the number of processes and the number of resources. For each process if should read four num- bers: the number of resources it is currently holding, the IDs of resources it is holding, the number of resources it is currently requesting, the IDs of resources it is requesting. The output of program should indicate if there is a deadlock in the system. In case there is, the program should print out the identities of all processes that are deadlocked. 44. In certain countries, when two people meet they bow to each other. The protocol is that one of them bows first and stays down until the other one bows. If they bow at the same time, they will both stay bowed forever. Write a program that does not deadlock.
clipped_os_Page_470_Chunk6687
7 VIRTUALIZATION AND THE CLOUD In some situations, an organization has a multicomputer but does not actually want it. A common example is where a company has an email server, a Web server, an FTP server, some e-commerce servers, and others. These all run on different computers in the same equipment rack, all connected by a high-speed network, in other words, a multicomputer. One reason all these servers run on separate ma- chines may be that one machine cannot handle the load, but another is reliability: management simply does not trust the operating system to run 24 hours a day, 365 or 366 days a year, with no failures. By putting each service on a separate com- puter, if one of the servers crashes, at least the other ones are not affected. This is good for security also. Even if some malevolent intruder manages to compromise the Web server, he will not immediately have access to sensitive emails also—a property sometimes referred to as sandboxing. While isolation and fault tolerance are achieved this way, this solution is expensive and hard to manage because so many machines are involved. Mind you, these are just two out of many reasons for keeping separate ma- chines. For instance, organizations often depend on more than one operating sys- tem for their daily operations: a Web server on Linux, a mail server on Windows, an e-commerce server for customers running on OS X, and a few other services running on various flavors of UNIX. Again, this solution works, but cheap it is def- initely not. What to do? A possible (and popular) solution is to use virtual machine tech- nology, which sounds very hip and modern, but the idea is old, dating back to the 471
clipped_os_Page_471_Chunk6688
472 VIRTUALIZATION AND THE CLOUD CHAP. 7 1960s. Even so, the way we use it today is definitely new. The main idea is that a VMM (Virtual Machine Monitor) creates the illusion of multiple (virtual) ma- chines on the same physical hardware. A VMM is also known as a hypervisor. As discussed in Sec. 1.7.5, we distinguish between type 1 hypervisors which run on the bare metal, and type 2 hypervisors that may make use of all the wonderful ser- vices and abstractions offered by an underlying operating system. Either way, vir- tualization allows a single computer to host multiple virtual machines, each poten- tially running a completely different operating system. The advantage of this approach is that a failure in one virtual machine does not bring down any others. On a virtualized system, different servers can run on dif- ferent virtual machines, thus maintaining the partial-failure model that a multicom- puter has, but at a lower cost and with easier maintainability. Moreover, we can now run multiple different operating systems on the same hardware, benefit from virtual machine isolation in the face of attacks, and enjoy other good stuff. Of course, consolidating servers like this is like putting all your eggs in one basket. If the server running all the virtual machines fails, the result is even more catastrophic than the crashing of a single dedicated server. The reason virtuali- zation works, however, is that most service outages are due not to faulty hardware, but to ill-designed, unreliable, buggy and poorly configured software, emphatically including operating systems. With virtual machine technology, the only software running in the highest privilege mode is the hypervisor, which has two orders of magnitude fewer lines of code than a full operating system, and thus two orders of magnitude fewer bugs. A hypervisor is simpler than an operating system because it does only one thing: emulate multiple copies of the bare metal (most commonly the Intel x86 architecture). Running software in virtual machines has other advantages in addition to strong isolation. One of them is that having fewer physical machines saves money on hardware and electricity and takes up less rack space. For a company such as Amazon or Microsoft, which may have hundreds of thousands of servers doing a huge variety of different tasks at each data center, reducing the physical demands on their data centers represents a huge cost savings. In fact, server companies fre- quently locate their data centers in the middle of nowhere—just to be close to, say, hydroelectric dams (and cheap energy). Virtualization also helps in trying out new ideas. Typically, in large companies, individual departments or groups think of an interesting idea and then go out and buy a server to implement it. If the idea catches on and hundreds or thousands of servers are needed, the corporate data center expands. It is often hard to move the software to existing machines because each application often needs a different version of the operating system, its own li- braries, configuration files, and more. With virtual machines, each application can take its own environment with it. Another advantage of virtual machines is that checkpointing and migrating vir- tual machines (e.g., for load balancing across multiple servers) is much easier than migrating processes running on a normal operating system. In the latter case, a fair
clipped_os_Page_472_Chunk6689
SEC. 7.1 HISTORY 473 amount of critical state information about every process is kept in operating system tables, including information relating to open files, alarms, signal handlers, and more. When migrating a virtual machine, all that have to be moved are the memory and disk images, since all the operating system tables move, too. Another use for virtual machines is to run legacy applications on operating sys- tems (or operating system versions) no longer supported or which do not work on current hardware. These can run at the same time and on the same hardware as cur- rent applications. In fact, the ability to run at the same time applications that use different operating systems is a big argument in favor of virtual machines. Yet another important use of virtual machines is for software development. A programmer who wants to make sure his software works on Windows 7, Windows 8, several versions of Linux, FreeBSD, OpenBSD, NetBSD, and OS X, among other systems no longer has to get a dozen computers and install different operat- ing systems on all of them. Instead, he merely creates a dozen virtual machines on a single computer and installs a different operating system on each one. Of course, he could have partitioned the hard disk and installed a different operating system in each partition, but that approach is more difficult. First of all, standard PCs sup- port only four primary disk partitions, no matter how big the disk is. Second, al- though a multiboot program could be installed in the boot block, it would be neces- sary to reboot the computer to work on a new operating system. With virtual ma- chines, all of them can run at once, since they are really just glorified processes. Perhaps the most important and buzzword-compliant use case for virtualization nowadays is found in the cloud. The key idea of a cloud is straightforward: out- source your computation or storage needs to a well-managed data center run by a company specializing in this and staffed by experts in the area. Because the data center typically belongs to someone else, you will probably have to pay for the use of the resources, but at least you will not have to worry about the physical ma- chines, power, cooling, and maintenance. Because of the isolation offered by virtu- alizaton, cloud-providers can allow multiple clients, even competitors, to share a single physical machine. Each client gets a piece of the pie. At the risk of stretch- ing the cloud metaphor, we mention that early critics maintained that the pie was only in the sky and that real organizations would not want to put their sensitive data and computations on someone else’s resources. By now, howev er, virtualized machines in the cloud are used by countless organization for countless applica- tions, and while it may not be for all organizations and all data, there is no doubt that cloud computing has been a success. 7.1 HISTORY With all the hype surrounding virtualizaton in recent years, we sometimes for- get that by Internet standards virtual machines are ancient. As early as the 1960s. IBM experimented with not just one but two independently developed hypervisors:
clipped_os_Page_473_Chunk6690
474 VIRTUALIZATION AND THE CLOUD CHAP. 7 SIMMON and CP-40. While CP-40 was a research project, it was reimplemented as CP-67 to form the control program of CP/CMS, a virtual machine operating system for the IBM System/360 Model 67. Later, it was reimplemented again and released as VM/370 for the System/370 series in 1972. The System/370 line was replaced by IBM in the 1990s by the System/390. This was basically a name change since the underlying architecture remained the same for reasons of back- ward compatibility. Of course, the hardware technology was improved and the newer machines were bigger and faster than the older ones, but as far as virtualiza- tion was concerned, nothing changed. In 2000, IBM released the z-series, which supported 64-bit virtual address spaces but was otherwise backward compatible with the System/360. All of these systems supported virtualization decades before it became popular on the x86. In 1974, two computer scientists at UCLA, Gerald Popek and Robert Gold- berg, published a seminal paper (‘‘Formal Requirements for Virtualizable Third Generation Architectures’’) that listed exactly what conditions a computer architec- ture should satisfy in order to support virtualization efficiently (Popek and Gold- berg, 1974). It is impossible to write a chapter on virtualization without referring to their work and terminology. Famously, the well-known x86 architecture that also originated in the 1970s did not meet these requirements for decades. It was not the only one. Nearly every architecture since the mainframe also failed the test. The 1970s were very productive, seeing also the birth of UNIX, Ethernet, the Cray-1, Microsoft, and Apple—so, despite what your parents may say, the 1970s were not just about disco! In fact, the real Disco revolution started in the 1990s, when researchers at Stan- ford University developed a new hypervisor by that name and went on to found VMware, a virtualization giant that offers type 1 and type 2 hypervisors and now rakes in billions of dollars in revenue (Bugnion et al., 1997, Bugnion et al., 2012). Incidentally, the distinction between ‘‘type 1’’ and ‘‘type 2’’ hypervisors is also from the seventies (Goldberg, 1972). VMware introduced its first virtualization solution for x86 in 1999. In its wake other products followed: Xen, KVM, Virtu- alBox, Hyper-V, Parallels, and many others. It seems the time was right for virtu- alization, even though the theory had been nailed down in 1974 and for decades IBM had been selling computers that supported—and heavily used—virtualization. In 1999, it became popular among the masses, but new it was not, despite the mas- sive attention it suddenly gained. 7.2 REQUIREMENTS FOR VIRTUALIZATION It is important that virtual machines act just like the real McCoy. In particular, it must be possible to boot them like real machines and install arbitrary operating systems on them, just as can be done on the real hardware. It is the task of the
clipped_os_Page_474_Chunk6691
SEC. 7.2 REQUIREMENTS FOR VIRTUALIZATION 475 hypervisor to provide this illusion and to do it efficiently. Indeed, hypervisors should score well in three dimensions: 1. Safety: the hypervisor should have full control of the virtualized re- sources. 2. Fidelity: the behavior of a program on a virtual machine should be identical to that of the same program running on bare hardware. 3. Efficiency: much of the code in the virtual machine should run with- out intervention by the hypervisor. An unquestionably safe way to execute the instructions is to consider each in- struction in turn in an interpreter (such as Bochs) and perform exactly what is needed for that instruction. Some instructions can be executed directly, but not too many. For instance, the interpreter may be able to execute an INC (increment) in- struction simply as is, but instructions that are not safe to execute directly must be simulated by the interpreter. For instance, we cannot really allow the guest operat- ing system to disable interrupts for the entire machine or modify the page-table mappings. The trick is to make the operating system on top of the hypervisor think that it has disabled interrupts, or changed the machine’s page mappings. We will see how this is done later. For now, we just want to say that the interpreter may be safe, and if carefully implemented, perhaps even hi-fi, but the performance sucks. To also satisfy the performance criterion, we will see that VMMs try to execute most of the code directly. Now let us turn to fidelity. Virtualization has long been a problem on the x86 architecture due to defects in the Intel 386 architecture that were slavishly carried forward into new CPUs for 20 years in the name of backward compatibility. In a nutshell, every CPU with kernel mode and user mode has a set of instructions that behave differently when executed in kernel mode than when executed in user mode. These include instructions that do I/O, change the MMU settings, and so on. Popek and Goldberg called these sensitive instructions. There is also a set of instructions that cause a trap if executed in user mode. Popek and Goldberg called these privileged instructions. Their paper stated for the first time that a machine is virtualizable only if the sensitive instructions are a subset of the privileged in- structions. In simpler language, if you try to do something in user mode that you should not be doing in user mode, the hardware should trap. Unlike the IBM/370, which had this property, Intel’s 386 did not. Quite a few sensitive 386 instructions were ignored if executed in user mode or executed with different behavior. For ex- ample, the POPF instruction replaces the flags register, which changes the bit that enables/disables interrupts. In user mode, this bit is simply not changed. As a consequence, the 386 and its successors could not be virtualized, so they could not support a hypervisor directly. Actually, the situation is even worse than sketched. In addition to the problems with instructions that fail to trap in user mode, there are instructions that can read
clipped_os_Page_475_Chunk6692
476 VIRTUALIZATION AND THE CLOUD CHAP. 7 sensitive state in user mode without causing a trap. For example, on x86 proces- sors prior to 2005, a program can determine whether it is running in user mode or kernel mode by reading its code-segment selector. An operating system that did this and discovered that it was actually in user mode might make an incorrect de- cision based on this information. This problem was finally solved when Intel and AMD introduced virtualization in their CPUs starting in 2005 (Uhlig, 2005). On the Intel CPUs it is called VT (Virtualization Technology); on the AMD CPUs it is called SVM (Secure Vir- tual Machine). We will use the term VT in a generic sense below. Both were inspired by the IBM VM/370 work, but they are slightly different. The basic idea is to create containers in which virtual machines can be run. When a guest operat- ing system is started up in a container, it continues to run there until it causes an exception and traps to the hypervisor, for example, by executing an I/O instruction. The set of operations that trap is controlled by a hardware bitmap set by the hyper- visor. With these extensions the classical trap-and-emulate virtual machine ap- proach becomes possible. The astute reader may have noticed an apparent contradiction in the descrip- tion thus far. On the one hand, we have said that x86 was not virtualizable until the architecture extensions introduced in 2005. On the other hand, we saw that VMware launched its first x86 hypervisor in 1999. How can both be true at the same time? The answer is that the hypervisors before 2005 did not really run the original guest operating system. Rather, they re wrote part of the code on the fly to replace problematic instructions with safe code sequences that emulated the origi- nal instruction. Suppose, for instance, that the guest operating system performed a privileged I/O instruction, or modified one of the CPU’s privileged control regis- ters (like the CR3 register which contains a pointer to the page directory). It is im- portant that the consequences of such instructions are limited to this virtual ma- chine and do not affect other virtual machines, or the hypervisor itself. Thus, an unsafe I/O instruction was replaced by a trap that, after a safety check, performed an equivalent instruction and returned the result. Since we are rewriting, we can use the trick to replace instructions that are sensitive, but not privileged. Other in- structions execute natively. The technique is known as binary translation; we will discuss it more detail in Sec. 7.4. There is no need to rewrite all sensitive instructions. In particular, user proc- esses on the guest can typically run without modification. If the instruction is non- privileged but sensitive and behaves differently in user processes than in the kernel, that is fine. We are running it in userland anyway. For sensitive instructions that are privileged, we can resort to the classical trap-and-emulate, as usual. Of course, the VMM must ensure that it receives the corresponding traps. Typically, the VMM has a module that executes in the kernel and redirects the traps to its own handlers. A different form of virtualization is known as paravirtualization. It is quite different from full virtualization, because it never even aims to present a virtual machine that looks just like the actual underlying hardware. Instead, it presents a
clipped_os_Page_476_Chunk6693
SEC. 7.2 REQUIREMENTS FOR VIRTUALIZATION 477 machine-like software interface that explicitly exposes the fact that it is a virtu- alized environment. For instance, it offers a set of hypercalls, which allow the guest to send explicit requests to the hypervisor (much as a system call offers ker- nel services to applications). Guests use hypercalls for privileged sensitive opera- tions like updating the page tables, but because they do it explicitly in cooperation with the hypervisor, the overall system can be simpler and faster. It should not come as a surprise that paravirtualization is nothing new either. IBM’s VM operating system has offered such a facility, albeit under a different name, since 1972. The idea was revived by the Denali (Whitaker et al., 2002) and Xen (Barham et al., 2003) virtual machine monitors. Compared to full virtu- alization, the drawback of paravirtualization is that the guest has to be aware of the virtual machine API. Typically, this means it should be customized explicitly for the hypervisor. Before we delve more deeply into type 1 and type 2 hypervisors, it is important to mention that not all virtualization technology tries to trick the guest into believ- ing that it has the entire system. Sometimes, the aim is simply to allow a process to run that was originally written for a different operating system and/or architecture. We therefore distinguish between full system virtualization and process-level vir- tualization. While we focus on the former in the remainder of this chapter, proc- ess-level virtualization technology is used in practice also. Well-known examples include the WINE compatibility layer that allows Windows application to run on POSIX-compliant systems like Linux, BSD, and OS X, and the process-level ver- sion of the QEMU emulator that allows applications for one architecture to run on another. 7.3 TYPE 1 AND TYPE 2 HYPERVISORS Goldberg (1972) distinguished between two approaches to virtualization. One kind of hypervisor, dubbed a type 1 hypervisor is illustrated in Fig. 7-1(a). Tech- nically, it is like an operating system, since it is the only program running in the most privileged mode. Its job is to support multiple copies of the actual hardware, called virtual machines, similar to the processes a normal operating system runs. In contrast, a type 2 hypervisor, shown in Fig. 7-1(b), is a different kind of animal. It is a program that relies on, say, Windows or Linux to allocate and schedule resources, very much like a regular process. Of course, the type 2 hyper- visor still pretends to be a full computer with a CPU and various devices. Both types of hypervisor must execute the machine’s instruction set in a safe manner. For instance, an operating system running on top of the hypervisor may change and ev en mess up its own page tables, but not those of others. The operating system running on top of the hypervisor in both cases is called the guest operating system. For a type 2 hypervisor, the operating system running on the hardware is called the host operating system. The first type 2 hypervisor
clipped_os_Page_477_Chunk6694
478 VIRTUALIZATION AND THE CLOUD CHAP. 7 Type 1 hypervisor Hardware (CPU, disk, network, interrupts, etc.) Hardware (CPU, disk, network, interrupts, etc.) Host OS (e.g., Linux) Control Domain Linux Windows Excel Word Mplayer Emacs Type 2 hypervisor Guest OS (e.g., Windows) Guest OS process Host OS process Figure 7-1. Location of type 1 and type 2 hypervisors. on the x86 market was VMware Workstation (Bugnion et al., 2012). In this sec- tion, we introduce the general idea. A study of VMware follows in Sec. 7.12. Type 2 hypervisors, sometimes referred to as hosted hypervisors, depend for much of their functionality on a host operating system such as Windows, Linux, or OS X. When it starts for the first time, it acts like a newly booted computer and expects to find a DVD, USB drive, or CD-ROM containing an operating system in the drive. This time, however, the drive could be a virtual device. For instance, it is possible to store the image as an ISO file on the hard drive of the host and have the hypervisor pretend it is reading from a proper DVD drive. It then installs the oper- ating system to its virtual disk (again really just a Windows, Linux, or OS X file) by running the installation program found on the DVD. Once the guest operating system is installed on the virtual disk, it can be booted and run. The various categories of virtualization we have discussed are summarized in the table of Fig. 7-2 for both type 1 and type 2 hypervisors. For each combination of hypervisor and kind of virtualization, some examples are given. Vir tualizaton method Type 1 hyper visor Type 2 hyper visor Vir tualization without HW support ESX Server 1.0 VMware Wor kstation 1 Paravir tualization Xen 1.0 Vir tualization with HW support vSphere, Xen, Hyper-V VMware Fusion, KVM, Parallels Process virtualization Wine Figure 7-2. Examples of hypervisors. Type 1 hypervisors run on the bare metal whereas type 2 hypervisors use the services of an existing host operating system. 7.4 TECHNIQUES FOR EFFICIENT VIRTUALIZATION Virtualizability and performance are important issues, so let us examine them more closely. Assume, for the moment, that we have a type 1 hypervisor sup- porting one virtual machine, as shown in Fig. 7-3. Like all type 1 hypervisors, it
clipped_os_Page_478_Chunk6695
SEC. 7.4 TECHNIQUES FOR EFFICIENT VIRTUALIZATION 479 runs on the bare metal. The virtual machine runs as a user process in user mode, and as such is not allowed to execute sensitive instructions (in the Popek-Goldberg sense). However, the virtual machine runs a guest operating system that thinks it is in kernel mode (although, of course, it is not). We will call this virtual kernel mode. The virtual machine also runs user processes, which think they are in user mode (and really are in user mode). Type 1 hypervisor Virtual machine Guest operating system Virtual kernel mode Virtual user mode Hardware Trap on privileged instruction User process Kernel mode User mode Figure 7-3. When the operating system in a virtual machine executes a kernel- only instruction, it traps to the hypervisor if virtualization technology is present. What happens when the guest operating system (which thinks it is in kernel mode) executes an instruction that is allowed only when the CPU really is in kernel mode? Normally, on CPUs without VT, the instruction fails and the operating sys- tem crashes. On CPUs with VT, when the guest operating system executes a sensi- tive instruction, a trap to the hypervisor does occur, as illustrated in Fig. 7-3. The hypervisor can then inspect the instruction to see if it was issued by the guest oper- ating system in the virtual machine or by a user program in the virtual machine. In the former case, it arranges for the instruction to be carried out; in the latter case, it emulates what the real hardware would do when confronted with a sensitive in- struction executed in user mode. 7.4.1 Virtualizing the Unvirtualizable Building a virtual machine system is relatively straightforward when VT is available, but what did people do before that? For instance, VMware released a hypervisor well before the arrival of the virtualization extensions on the x86. Again, the answer is that the software engineers who built such systems made clever use of binary translation and hardware features that did exist on the x86, such as the processor’s protection rings. For many years, the x86 has supported four protection modes or rings. Ring 3 is the least privileged. This is where normal user processes execute. In this ring, you cannot execute privileged instructions. Ring 0 is the most privileged ring that allows the execution of any instruction. In normal operation, the kernel runs in
clipped_os_Page_479_Chunk6696
480 VIRTUALIZATION AND THE CLOUD CHAP. 7 ring 0. The remaining two rings are not used by any current operating system. In other words, hypervisors were free to use them as they pleased. As shown in Fig. 7-4, many virtualization solutions therefore kept the hypervisor in kernel mode (ring 0) and the applications in user mode (ring 3), but put the guest operating sys- tem in a layer of intermediate privilege (ring 1). As a result, the kernel is privileged relative to the user processes and any attempt to access kernel memory from a user program leads to an access violation. At the same time, the guest operating sys- tem’s privileged instructions trap to the hypervisor. The hypervisor does some san- ity checks and then performs the instructions on the guest’s behalf. Type 1 hypervisor Virtual machine Guest operating system (Rewrite binary prior to execution + emulate) ring 0 ring 1 ring 2 ring 3 Hardware User process Figure 7-4. The binary translator rewrites the guest operating system running in ring 1, while the hypervisor runs in ring 0. As for the sensitive instructions in the guest’s kernel code: the hypervisor makes sure they no longer exist. To do so, it rewrites the code, one basic block at a time. A basic block is a short, straight-line sequence of instructions that ends with a branch. By definition, a basic block contains no jump, call, trap, return, or other instruction that alters the flow of control, except for the very last instruction which does precisely that. Just prior to executing a basic block, the hypervisor first scans it to see if it contains sensitive instructions (in the Popek and Goldberg sense), and if so, replaces them with a call to a hypervisor procedure that handles them. The branch on the last instruction is also replaced by a call into the hypervisor (to make sure it can repeat the procedure for the next basic block). Dynamic translation and emulation sound expensive, but typically are not. Translated blocks are cached, so no translation is needed in the future. Also, most code blocks do not contain sensi- tive or privileged instructions and thus can executes natively. In particular, as long as the hypervisor configures the hardware carefully (as is done, for instance, by VMware), the binary translator can ignore all user processes; they execute in non- privileged mode anyway. After a basic block has completed executing, control is returned to the hypervi- sor, which then locates its successor. If the successor has already been translated,
clipped_os_Page_480_Chunk6697
SEC. 7.4 TECHNIQUES FOR EFFICIENT VIRTUALIZATION 481 it can be executed immediately. Otherwise, it is first translated, cached, then ex- ecuted. Eventually, most of the program will be in the cache and run at close to full speed. Various optimizations are used, for example, if a basic block ends by jumping to (or calling) another one, the final instruction can be replaced by a jump or call directly to the translated basic block, eliminating all overhead associated with finding the successor block. Again, there is no need to replace sensitive in- structions in user programs; the hardware will just ignore them anyway. On the other hand, it is common to perform binary translation on all the guest operating system code running in ring 1 and replace even the privileged sensitive instructions that, in principle, could be made to trap also. The reason is that traps are very expensive and binary translation leads to better performance. So far we have described a type 1 hypervisor. Although type 2 hypervisors are conceptually different from type 1 hypervisors, they use, by and large, the same techniques. For instance, VMware ESX Server (a type 1 hypervisor first shipped in 2001) used exactly the same binary translation as the first VMware Workstation (a type 2 hypervisor released two years earlier). However, to run the guest code natively and use exactly the same techniques requires the type 2 hypervisor to manipulate the hardware at the lowest level, which cannot be done from user space. For instance, it has to set the segment de- scriptors to exactly the right value for the guest code. For faithful virtualization, the guest operating system should also be tricked into thinking that it is the true and only king of the mountain with full control of all the machine’s resources and with access to the entire address space (4 GB on 32-bit machines). When the king finds another king (the host kernel) squatting in its address space, the king will not be amused. Unfortunately, this is exactly what happens when the guest runs as a user proc- ess on a regular operating system. For instance, in Linux a user process has access to just 3 GB of the 4-GB address space, as the remaining 1 GB is reserved for the kernel. Any access to the kernel memory leads to a trap. In principle, it is possible to take the trap and emulate the appropriate actions, but doing so is expensive and typically requires installing the appropriate trap handler in the host kernel. Another (obvious) way to solve the two-kings problem, is to reconfigure the system to re- move the host operating system and actually give the guest the entire address space. However, doing so is clearly not possible from user space either. Likewise, the hypervisor needs to handle the interrupts to do the right thing, for instance when the disk sends an interrupt or a page fault occurs. Also, if the hypervisor wants to use trap-and-emulate for privileged instructions, it needs to re- ceive the traps. Again, installing trap/interrupt handlers in the kernel is not possible for user processes. Most modern type 2 hypervisors therefore have a kernel module operating in ring 0 that allows them to manipulate the hardware with privileged instructions. Of course, manipulating the hardware at the lowest level and giving the guest access to the full address space is all well and good, but at some point the hypervisor
clipped_os_Page_481_Chunk6698
482 VIRTUALIZATION AND THE CLOUD CHAP. 7 needs to clean it up and restore the original processor context. Suppose, for instance, that the guest is running when an interrupt arrives from an external de- vice. Since a type 2 hypervisor depends on the host’s device drivers to handle the interrupt, it needs to reconfigure the hardware completely to run the host operating system code. When the device driver runs, it finds everything just as it expected it to be. The hypervisor behaves just like teenagers throwing a party while their par- ents are away. It is okay to rearrange the furniture completely, as long as they put it back exactly as they found it before the parents come home. Going from a hard- ware configuration for the host kernel to a configuration for the guest operating system is known as a world switch. We will discuss it in detail when we discuss VMware in Sec. 7.12. It should now be clear why these hypervisors work, even on unvirtualizable hardware: sensitive instructions in the guest kernel are replaced by calls to proce- dures that emulate these instructions. No sensitive instructions issued by the guest operating system are ever executed directly by the true hardware. They are turned into calls to the hypervisor, which then emulates them. 7.4.2 The Cost of Virtualization One might naively expect that CPUs with VT would greatly outperform soft- ware techniques that resort to translation, but measurements show a mixed picture (Adams and Agesen, 2006). It turns out that the trap-and-emulate approach used by VT hardware generates a lot of traps, and traps are very expensive on modern hardware because they ruin CPU caches, TLBs, and branch prediction tables inter- nal to the CPU. In contrast, when sensitive instructions are replaced by calls to hypervisor procedures within the executing process, none of this context-switching overhead is incurred. As Adams and Agesen show, depending on the workload, sometimes software beats hardware. For this reason, some type 1 (and type 2) hypervisors do binary translation for performance reasons, even though the soft- ware will execute correctly without it. With binary translation, the translated code itself may be either slower or faster than the original code. Suppose, for instance, that the guest operating system dis- ables hardware interrupts using the CLI instruction (‘‘clear interrupts’’). Depending on the architecture, this instruction can be very slow, taking many tens of cycles on certain CPUs with deep pipelines and out-of-order execution. It should be clear by now that the guest’s wanting to turn off interrupts does not mean the hypervisor should really turn them off and affect the entire machine. Thus, the hypervisor must turn them off for the guest without really turning them off. To do so, it may keep track of a dedicated IF (Interrupt Flag) in the virtual CPU data structure it maintains for each guest (making sure the virtual machine does not get any inter- rupts until the interrupts are turned off again). Every occurrence of CLI in the guest will be replaced by something like ‘‘Vir tualCPU.IF = 0’’, which is a very cheap move
clipped_os_Page_482_Chunk6699
SEC. 7.4 TECHNIQUES FOR EFFICIENT VIRTUALIZATION 483 instruction that may take as little as one to three cycles. Thus, the translated code is faster. Still, with modern VT hardware, usually the hardware beats the software. On the other hand, if the guest operating system modifies its page tables, this is very costly. The problem is that each guest operating system on a virtual machine thinks it ‘‘owns’’ the machine and is at liberty to map any virtual page to any phys- ical page in memory. Howev er, if one virtual machine wants to use a physical page that is already in use by another virtual machine (or the hypervisor), something has to give. We will see in Section 7.6 that the solution is to add an extra level of page tables to map ‘‘guest physical pages’’ to the actual physical pages on the host. Not surprisingly, mucking around with multiple levels of page tables is not cheap. 7.5 ARE HYPERVISORS MICROKERNELS DONE RIGHT? Both type 1 and type 2 hypervisors work with unmodified guest operating sys- tems, but have to jump through hoops to get good performance. We hav e seen that paravirtualization takes a different approach by modifying the source code of the guest operating system instead. Rather than performing sensitive instructions, the paravirtualized guest executes hypercalls. In effect the guest operating system is acting like a user program making system calls to the operating system (the hyper- visor). When this route is taken, the hypervisor must define an interface consisting of a set of procedure calls that guest operating systems can use. This set of calls forms what is effectively an API (Application Programming Interface) even though it is an interface for use by guest operating systems, not application pro- grams. Going one step further, by removing all the sensitive instructions from the op- erating system and just having it make hypercalls to get system services like I/O, we have turned the hypervisor into a microkernel, like that of Fig. 1-26. The idea, explored in paravirtualization, is that emulating peculiar hardware instructions is an unpleasant and time-consuming task. It requires a call into the hypervisor and then emulating the exact semantics of a complicated instruction. It is far better just to have the guest operating system call the hypervisor (or microkernel) to do I/O, and so on. Indeed, some researchers have argued that we should perhaps consider hyper- visors as ‘‘microkernels done right’’ (Hand et al., 2005). The first thing to mention is that this is a highly controversial topic and some researchers have vocally opposed the notion, arguing that the difference between the two is not fundamental to begin with (Heiser et al., 2006). Others suggest that compared to microkernels, hypervisors may not even be that well suited for building secure systems, and advocate that they be extended with kernel functionality like message passing and memory sharing (Hohmuth et al., 2004). Finally, some researchers argue that per- haps hypervisors are not even ‘‘operating systems research done right’’ (Roscoe et al., 2007). Since nobody said anything about operating system textbooks done right
clipped_os_Page_483_Chunk6700