text
stringlengths
139
4.06k
source
stringlengths
16
26
we access the TLB instead of the page table on every reference, the TLB will need to include other status bits, such as the dirty and the reference bits. On every reference, we look up the virtual page number in the TLB. If we get a hit, the physical page number is used to form the address, and the corresponding reference bit is turned on. If the processor is performing a write, the dirty bit is also turned on. If a miss in the TLB occurs, we must determine whether it is a page fault or merely a TLB miss. If the page exists in memory, then the TLB miss indicates only that the translation is missing. In such cases, the processor can handle the TLB miss by loading the translation from the page table into the TLB and then trying the reference again. If the page is not present in memory, then the TLB miss indicates a true page fault. In this case, the processor invokes the operating system using an ­exception. Because the TLB has many fewer entries than the number of pages in main memory, TLB misses will be much more fre­quent than true page faults. TLB misses can be handled either in hardware or in software. In practice, with care there can be little performance difference between the two approaches, because the basic operations are the same in either case. After a TLB miss occurs and the missing translation has been retrieved from the page table, we will need to select a TLB entry to replace. Because the reference and dirty bits are contained in the TLB entry, we need to copy these bits back to the page table entry when we replace an entry. These bits are the only portion of the TLB entry that can be changed. Using write-back—that is, copying these entries back at miss time rather than when they are written—is very efficient, since we expect the TLB miss rate to be small. Some systems use other techniques to approximate the reference and dirty bits, eliminating the need to write into the TLB except to load a new table entry on a miss. Some typical values for a TLB might be ■ ■TLB size: 16–512 entries ■ ■Block size: 1–2 page table entries (typically 4–8 bytes each) ■ ■Hit time: 0.5–1 clock cycle ■ ■Miss penalty: 10–100 clock cycles ■ ■Miss rate: 0.01%–1% Designers have used a wide variety of associativities in TLBs. Some systems use small, fully associative TLBs because a fully associative mapping has a lower miss rate; furthermore, since the TLB is small, the cost of a fully associative mapping is not too high. Other systems use large TLBs, often with small associativity. With a fully associative mapping, choosing the entry to replace becomes tricky since implementing a hardware LRU scheme is too expensive. Furthermore, since TLB misses are much more frequent than page faults and thus must be handled more cheaply, we cannot afford an expensive software algorithm, as we can for page 5.4 Virtual Memory 503
Hennesey_Page_501_Chunk501
504 Chapter 5 Large and Fast: Exploiting Memory Hierarchy faults. As a result, many systems provide some support for randomly choosing an entry to replace. We’ll examine replacement schemes in a little more detail in Section 5.5. The Intrinsity FastMATH TLB To see these ideas in a real processor, let’s take a closer look at the TLB of the Intrinsity FastMATH. The memory system uses 4 KB pages and a 32-bit address space; thus, the virtual page number is 20 bits long, as in the top of Figure 5.24. The physical address is the same size as the virtual address. The TLB contains 16 entries, it is fully associative, and it is shared between the instruction and data ref­erences. Each entry is 64 bits wide and contains a 20-bit tag (which is the virtual page number for that TLB entry), the corresponding physical page number (also 20 bits), a valid bit, a dirty bit, and other bookkeeping bits. Figure 5.24 shows the TLB and one of the caches, while Figure 5.25 shows the steps in processing a read or write request. When a TLB miss occurs, the MIPS hardware saves the page number of the reference in a special register and generates an exception. The exception invokes the operating system, which handles the miss in software. To find the physical address for the missing page, the TLB miss rou­ tine indexes the page table using the page number of the virtual address and the page table register, which indicates the starting address of the active process page table. Using a special set of system instructions that can update the TLB, the oper­ ating system places the physical address from the page table into the TLB. A TLB miss takes about 13 clock cycles, assuming the code and the page table entry are in the instruction cache and data cache, respectively. (We will see the MIPS TLB code on page 513.) A true page fault occurs if the page table entry does not have a valid physical address. The hardware maintains an index that indicates the recom­ mended entry to replace; the recommended entry is chosen randomly. There is an extra complication for write requests: namely, the write access bit in the TLB must be checked. This bit prevents the program from writing into pages for which it has only read access. If the program attempts a write and the write access bit is off, an exception is generated. The write access bit forms part of the protection mechanism, which we will discuss shortly. Integrating Virtual Memory, TLBs, and Caches Our virtual memory and cache systems work together as a hierarchy, so that data cannot be in the cache unless it is present in main memory. The operating system helps maintain this hierarchy by flushing the contents of any page from the cache when it decides to migrate that page to disk. At the same time, the OS modifies the page tables and TLB, so that an attempt to access any data on the migrated page will gener­ate a page fault.
Hennesey_Page_502_Chunk502
FIGURE 5.24 The TLB and cache implement the process of going from a virtual address to a data item in the Intrinsity Fast­MATH. This figure shows the organization of the TLB and the data cache, assuming a 4 KB page size. This diagram focuses on a read; Figure 5.25 describes how to handle writes. Note that unlike Figure 5.9, the tag and data RAMs are split. By addressing the long but narrow data RAM with the cache index concatenated with the block offset, we select the desired word in the block without a 16:1 multiplexor. While the cache is direct mapped, the TLB is fully associative. Implementing a fully associative TLB requires that every TLB tag be compared against the virtual page number, since the entry of interest can be anywhere in the TLB. (See content addressable memories in the Elaboration on page 485.) If the valid bit of the matching entry is on, the access is a TLB hit, and bits from the physical page number together with bits from the page offset form the index that is used to access the cache. = = 20 Virtual page number Page offset Tag Valid Dirty TLB Physical page number Tag Valid TLB hit Cache hit Data Data Byte offset = = = = = Physical page number Page offset Physical address tag Cache index 12 20 Block offset Physical address 18 32 8 4 2 12 8 Cache 31 30 29 3 2 1 0 14 13 12 11 10 9 Virtual address 5.4 Virtual Memory 505
Hennesey_Page_503_Chunk503
506 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Yes Write access bit on? No Yes Cache hit? No Write data into cache, update the dirty bit, and put the data and the address into the write buffer Yes TLB hit? Virtual address TLB access Try to read data from cache No Yes Write? No Cache miss stall while read block Deliver data to the CPU Write protection exception Yes Cache hit? No Try to write data to cache Cache miss stall while read block TLB miss exception Physical address FIGURE 5.25 Processing a read or a write-through in the Intrinsity FastMATH TLB and cache. If the TLB generates a hit, the cache can be accessed with the resulting physical address. For a read, the cache generates a hit or miss and supplies the data or causes a stall while the data is brought from memory. If the operation is a write, a portion of the cache entry is overwritten for a hit and the data is sent to the write buffer if we assume write-through. A write miss is just like a read miss except that the block is modified after it is read from memory. Write-back requires writes to set a dirty bit for the cache block, and a write buffer is loaded with the whole block only on a read miss or write miss if the block to be replaced is dirty. Notice that a TLB hit and a cache hit are independent events, but a cache hit can only occur after a TLB hit occurs, which means that the data must be present in memory. The relationship between TLB misses and cache misses is examined further in the following example and the exercises at the end of this chapter.
Hennesey_Page_504_Chunk504
Under the best of circumstances, a virtual address is translated by the TLB and sent to the cache where the appropriate data is found, retrieved, and sent back to the processor. In the worst case, a reference can miss in all three components of the memory hierarchy: the TLB, the page table, and the cache. The following example illustrates these interactions in more detail. Overall Operation of a Memory Hierarchy In a memory hierarchy like that of Figure 5.24, which includes a TLB and a cache organized as shown, a memory reference can encounter three different types of misses: a TLB miss, a page fault, and a cache miss. Consider all the combinations of these three events with one or more occurring (seven possi­ bilities). For each possibility, state whether this event can actually occur and under what circumstances. Figure 5.26 shows all combinations and whether each is possible in practice. TLB Page table Cache Possible? If so, under what circumstance? Hit Hit Miss Possible, although the page table is never really checked if TLB hits. Miss Hit Hit TLB misses, but entry found in page table; after retry, data is found in cache. Miss Hit Miss TLB misses, but entry found in page table; after retry, data misses in cache. Miss Miss Miss TLB misses and is followed by a page fault; after retry, data must miss in cache. Hit Miss Miss Impossible: cannot have a translation in TLB if page is not present in memory. Hit Miss Hit Impossible: cannot have a translation in TLB if page is not present in memory. Miss Miss Hit Impossible: data cannot be allowed in cache if the page is not in memory. FIGURE 5.26 The possible combinations of events in the TLB, virtual memory system, and cache. Three of these combinations are impossible, and one is possible (TLB hit, virtual memory hit, cache miss) but never detected. Elaboration: Figure 5.26 assumes that all memory addresses are translated to physical addresses before the cache is accessed. In this organization, the cache is physically indexed and physically tagged (both the cache index and tag are physical, rather than virtual, addresses). In such a system, the amount of time to access memory, EXAMPLE ANSWER 5.4 Virtual Memory 507
Hennesey_Page_505_Chunk505
508 Chapter 5 Large and Fast: Exploiting Memory Hierarchy assuming a cache hit, must accommodate both a TLB access and a cache access; of course, these accesses can be pipelined. Alternatively, the processor can index the cache with an address that is completely or par­tially virtual. This is called a virtually addressed cache, and it uses tags that are virtual addresses; hence, such a cache is virtually indexed and virtually tagged. In such caches, the address translation hardware (TLB) is unused during the normal cache access, since the cache is accessed with a virtual address that has not been translated to a physical address. This takes the TLB out of the critical path, reducing cache latency. When a cache miss occurs, however, the processor needs to translate the address to a physical address so that it can fetch the cache block from main memory. When the cache is accessed with a virtual address and pages are shared between programs (which may access them with different virtual addresses), there is the possibility of aliasing. Aliasing occurs when the same object has two names—in this case, two virtual addresses for the same page. This ambiguity creates a problem, because a word on such a page may be cached in two different locations, each corresponding to different virtual addresses. This ambiguity would allow one program to write the data without the other program being aware that the data had changed. Completely virtually addressed caches either introduce design limitations on the cache and TLB to reduce aliases or require the operating system, and possibly the user, to take steps to ensure that aliases do not occur. A common compromise between these two design points is caches that are virtually indexed—sometimes using just the page offset portion of the address, which is really a physical address since it is not translated—but use physical tags. These designs, which are virtually indexed but physically tagged, attempt to achieve the performance advantages of virtually indexed caches with the architecturally simpler advantages of a physically addressed cache. For example, there is no alias problem in this case. Figure 5.24 assumed a 4 KB page size, but it’s really 16 KB, so the Intrinsity FastMATH can use this trick. To pull it off, there must be careful coordination between the minimum page size, the cache size, and associativity. Implementing Protection with Virtual Memory Perhaps the most important function of virtual memory is to allow sharing of a single main memory by multiple processes, while providing memory protection among these processes and the operating system. The protection mechanism must ensure that although multiple processes are sharing the same main memory, one renegade process cannot write into the address space of another user process or into the operating system either intentionally or unintentionally. The write access bit in the TLB can protect a page from being written. Without this level of protec­ tion, computer viruses would be even more widespread. virtually addressed cache A cache that is accessed with a vir­tual address rather than a physi­cal address. aliasing A situation in which the same object is accessed by two addresses; can occur in vir­tual memory when there are two virtual addresses for the same physical page. physically addressed cache A cache that is addressed by a physical address.
Hennesey_Page_506_Chunk506
To enable the operating system to implement protection in the virtual memory sys­tem, the hardware must provide at least the three basic capabilities summarized below. 1. Support at least two modes that indicate whether the running process is a user process or an operating system process, variously called a supervisor process, a kernel process, or an executive process. 2. Provide a portion of the processor state that a user process can read but not write. This includes the user/supervisor mode bit, which dictates whether the processor is in user or supervisor mode, the page table pointer, and the TLB. To write these elements, the operating system uses special instructions that are only available in supervisor mode. 3. Provide mechanisms whereby the processor can go from user mode to supervisor mode and vice versa. The first direction is typically accom­ plished by a system call exception, implemented as a special instruction (syscall in the MIPS instruction set) that transfers control to a dedicated location in supervisor code space. As with any other exception, the program counter from the point of the system call is saved in the exception PC (EPC), and the processor is placed in supervisor mode. To return to user mode from the exception, use the return from exception (ERET) instruction, which resets to user mode and jumps to the address in EPC. By using these mechanisms and storing the page tables in the operating sys­tem’s address space, the operating system can change the page tables while pre­venting a user process from changing them, ensuring that a user ­process can access only the storage provided to it by the operating system. We also want to prevent a process from reading the data of another ­process. For example, we wouldn’t want a student program to read the grades while they were in the processor’s memory. Once we begin sharing main memory, we must provide the ability for a process to protect its data from both reading and writ­ing by another process; otherwise, sharing the main memory will be a mixed blessing! Remember that each process has its own virtual address space. Thus, if the operating system keeps the page tables organized so that the independent virtual pages map to disjoint physical pages, one process will not be able to access another’s data. Of course, this also requires that a user process be unable to change the page table mapping. The operating system can assure safety if it prevents the user process from modifying its own page tables. However, the operating system must be able to modify the page tables. Placing the page tables in the protected address space of the operating system satisfies both requirements. Hardware/ Software Interface supervisor mode Also called kernel mode. A mode ­indicating that a running process is an operating ­system process. system call A special instruc­tion that transfers control from user mode to a dedicated loca­tion in supervisor code space, invoking the exception mecha­nism in the process. 5.4 Virtual Memory 509
Hennesey_Page_507_Chunk507
510 Chapter 5 Large and Fast: Exploiting Memory Hierarchy When processes want to share information in a limited way, the operating system must assist them, since accessing the information of another process requires changing the page table of the accessing process. The write access bit can be used to restrict the sharing to just read sharing, and, like the rest of the page table, this bit can be changed only by the operating system. To allow another process, say, P1, to read a page owned by process P2, P2 would ask the operating system to create a page table entry for a virtual page in P1’s address space that points to the same physical page that P2 wants to share. The operating system could use the write protection bit to prevent P1 from writing the ­data, if that was P2’s wish. Any bits that determine the access rights for a page must be included in both the page table and the TLB, because the page table is accessed only on a TLB miss. Elaboration: When the operating system decides to change from running process P1 to run­ning process P2 (called a context switch or process switch), it must ensure that P2 cannot get access to the page tables of P1 because that would compromise protection. If there is no TLB, it suffices to change the page table register to point to P2’s page table (rather than to P1’s); with a TLB, we must clear the TLB entries that belong to P1—both to protect the data of P1 and to force the TLB to load the entries for P2. If the process switch rate were high, this could be quite ineffi­cient. For example, P2 might load only a few TLB entries before the operating system switched back to P1. Unfortunately, P1 would then find that all its TLB entries were gone and would have to pay TLB misses to reload them. This problem arises because the virtual addresses used by P1 and P2 are the same, and we must clear out the TLB to avoid confusing these addresses. A common alternative is to extend the virtual address space by adding a process identifier or task identifier. The Intrinsity FastMATH has an 8-bit address space ID (ASID) field for this purpose. This small field identifies the currently running process; it is kept in a register loaded by the operating system when it switches processes. The process identifier is concatenated to the tag portion of the TLB, so that a TLB hit occurs only if both the page number and the pro­cess identifier match. This combination eliminates the need to clear the TLB, except on rare occasions. Similar problems can occur for a cache, since on a process switch the cache will contain data from the running process. These problems arise in different ways for physically addressed and virtually addressed caches, and a variety of different solutions, such as process identifiers, are used to ensure that a process gets its own data. Handling TLB Misses and Page Faults Although the translation of virtual to physical addresses with a TLB is straightfor­ ward when we get a TLB hit, handling TLB misses and page faults is more com­plex. A TLB miss occurs when no entry in the TLB matches a virtual address. A TLB miss can indicate one of two possibilities: 1. The page is present in memory, and we need only create the missing TLB entry. 2. The page is not present in memory, and we need to transfer control to the operating system to deal with a page fault. context switch A changing of the internal state of the proces­sor to allow a different process to use the processor that includes saving the state needed to return to the currently exe­cuting process.
Hennesey_Page_508_Chunk508
How do we know which of these two circumstances has occurred? When we process the TLB miss, we will look for a page table entry to bring into the TLB. If the matching page table entry has a valid bit that is turned off, then the corresponding page is not in memory and we have a page fault, rather than just a TLB miss. If the valid bit is on, we can simply retrieve the desired entry. A TLB miss can be handled in software or hardware because it will require only a short sequence of operations to copy a valid page table entry from memory into the TLB. MIPS traditionally handles a TLB miss in software. It brings in the page table entry from memory and then re-executes the instruction that caused the TLB miss. Upon re-executing, it will get a TLB hit. If the page table entry indicates the page is not in memory, this time it will get a page fault exception. Handling a TLB miss or a page fault requires using the exception mechanism to interrupt the active process, transferring control to the operating system, and later resuming execution of the interrupted process. A page fault will be recognized sometime during the clock cycle used to access memory. To restart the instruction after the page fault is handled, the program counter of the instruction that caused the page fault must be saved. Just as in Chapter 4, the exception program counter (EPC) is used to hold this value. In addition, a TLB miss or page fault exception must be asserted by the end of the same clock cycle that the memory access occurs, so that the next clock cycle will begin exception processing rather than continue normal instruction execu­ tion. If the page fault was not recognized in this clock cycle, a load instruction could overwrite a register, and this could be disastrous when we try to restart the instruction. For example, consider the instruction lw $1,0($1): the computer must be able to prevent the write pipeline stage from occurring; otherwise, it could not properly restart the instruction, since the contents of $1 would have been destroyed. A similar complication arises on stores. We must prevent the write into memory from actually completing when there is a page fault; this is usually done by deasserting the write control line to the memory. Register CP0 register number Description EPC 14 Where to restart after exception Cause 13 Cause of exception BadVAddr 8 Address that caused exception Index 0 Location in TLB to be read or written Random 1 Pseudorandom location in TLB EntryLo 2 Physical page address and flags EntryHi 10 Virtual page address Context 4 Page table address and page number FIGURE 5.27 MIPS control registers. These are considered to be in coprocessor 0, and hence are read using mfc0 and written using mtc0. 5.4 Virtual Memory 511
Hennesey_Page_509_Chunk509
512 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Between the time we begin executing the exception handler in the operating system and the time that the operating system has saved all the state of the process, the operating system is particularly vulnerable. For example, if another excep­tion occurred when we were processing the first exception in the operating sys­tem, the control unit would overwrite the exception program counter, making it impossible to return to the instruction that caused the page fault! We can avoid this disaster by providing the ability to disable and enable exceptions. When an exception first occurs, the processor sets a bit that disables all other exceptions; this could happen at the same time the processor sets the supervisor mode bit. The operating system will then save just enough state to allow it to recover if another exception occurs— namely, the exception program counter (EPC) and Cause registers. EPC and Cause are two of the special control registers that help with exceptions, TLB misses, and page faults; Figure 5.27 shows the rest. The operating system can then re-enable exceptions. These steps make sure that exceptions will not cause the processor to lose any state and thereby be unable to restart execution of the interrupting instruction. Once the operating system knows the virtual address that caused the page fault, it must complete three steps: 1. Look up the page table entry using the virtual address and find the location of the referenced page on disk. 2. Choose a physical page to replace; if the chosen page is dirty, it must be writ­ ten out to disk before we can bring a new virtual page into this physical page. 3. Start a read to bring the referenced page from disk into the chosen physical page. Of course, this last step will take millions of processor clock cycles (so will the sec­ ond if the replaced page is dirty); accordingly, the operating system will usually select another process to execute in the processor until the disk access completes. Because the operating system has saved the state of the process, it can freely give control of the processor to another process. When the read of the page from disk is complete, the operating system can restore the state of the process that originally caused the page fault and execute the instruction that returns from the exception. This instruction will reset the proces­ sor from kernel to user mode, as well as restore the program counter. The user process then re-executes the instruction that faulted, accesses the requested page successfully, and continues execution. Hardware/ Software Interface exception enable Also called interrupt enable. A signal or action that controls whether the process responds to an excep­tion or not; necessary for preventing the occurrence of exceptions during intervals before the processor has safely saved the state needed to restart.
Hennesey_Page_510_Chunk510
Page fault exceptions for data accesses are difficult to implement properly in a processor because of a combination of three characteristics: 1. They occur in the middle of instructions, unlike instruction page faults. 2. The instruction cannot be completed before handling the exception. 3. After handling the exception, the instruction must be restarted as if nothing had occurred. Making instructions restartable, so that the exception can be handled and the instruction later continued, is relatively easy in an architecture like the MIPS. Because each instruction writes only one data item and this write occurs at the end of the instruction cycle, we can simply prevent the instruction from complet­ing (by not writing) and restart the instruction at the beginning. Let’s look in more detail at MIPS. When a TLB miss occurs, the MIPS hardware saves the page number of the reference in a special register called BadVAddr and generates an exception. The exception invokes the operating system, which handles the miss in software. Control is transferred to address 8000 0000hex, the location of the TLB miss han­dler. To find the physical address for the missing page, the TLB miss routine indexes the page table using the page number of the virtual address and the page table regis­ter, which indicates the starting address of the active process page table. To make this indexing fast, MIPS hardware places everything you need in the special Context register: the upper 12 bits have the address of the base of the page table, and the next 18 bits have the virtual address of the missing page. Each page table entry is one word, so the last 2 bits are 0. Thus, the first two instructions copy the Context regis­ter into the kernel temporary register $k1 and then load the page table entry from that address into $k1. Recall that $k0 and $k1 are reserved for the operating system to use without saving; a major reason for this convention is to make the TLB miss handler fast. Below is the MIPS code for a typical TLB miss handler: TLBmiss: mfc0 $k1,Context # copy address of PTE into temp $k1 lw $k1, 0($k1) # put PTE into temp $k1 mtc0 $k1,EntryLo # put PTE into special register EntryLo tlbwr # put EntryLo into TLB entry at Random eret # return from TLB miss exception As shown above, MIPS has a special set of system instructions to update the TLB. The instruction tlbwr copies from control register EntryLo into the TLB entry selected by the control register Random. Random implements random replacement, so it is basically a free-running counter. A TLB miss takes about a dozen clock cycles. restartable instruction An instruction that can resume exe­cution after an exception is resolved without the excep­tion’s affecting the result of the instruction. handler Name of a software routine invoked to “handle” an exception or interrupt. 5.4 Virtual Memory 513
Hennesey_Page_511_Chunk511
514 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Note that the TLB miss handler does not check to see if the page table entry is valid. Because the exception for TLB entry missing is much more frequent than a page fault, the operating system loads the TLB from the page table without exam­ ining the entry and restarts the instruction. If the entry is invalid, another and dif­ferent exception occurs, and the operating system recognizes the page fault. This method makes the frequent case of a TLB miss fast, at a slight performance pen­alty for the infrequent case of a page fault. Once the process that generated the page fault has been interrupted, it transfers control to 8000 0180hex, a different address than the TLB miss handler. This is the general address for exception; TLB miss has a special entry point to lower the pen­alty for a TLB miss. The operating system uses the exception Cause register to diagnose the cause of the exception. Because the exception is a page fault, the operating system knows that extensive processing will be required. Thus, unlike a TLB miss, it saves the entire state of the active process. This state includes all the general-purpose and floating-point registers, the page table address register, the EPC, and the exception Cause register. Since exception handlers do not usually use the floating-point registers, the general entry point does not save them, leav­ing that to the few handlers that need them. Figure 5.28 sketches the MIPS code of an exception handler. Note that we save and restore the state in MIPS code, taking care when we enable and disable excep­ tions, but we invoke C code to handle the particular exception. The virtual address that caused the fault depends on whether the fault was an instruction or data fault. The address of the instruction that generated the fault is in the EPC. If it was an instruction page fault, the EPC contains the virtual address of the faulting page; otherwise, the faulting virtual address can be computed by examining the instruction (whose address is in the EPC) to find the base register and offset field. Elaboration: This simplified version assumes that the stack pointer (sp) is valid. To avoid the problem of a page fault during this low-level exception code, MIPS sets aside a portion of its address space that cannot have page faults, called unmapped. The operating system places the exception entry point code and the exception stack in unmapped memory. MIPS hardware translates virtual addresses 8000 0000hex to BFFF FFFFhex to physical addresses simply by ignoring the upper bits of the virtual address, thereby placing these addresses in the low part of physical memory. Thus, the operating system places exception entry points and exception stacks in unmapped memory. Elaboration: The code in Figure 5.28 shows the MIPS-32 exception return sequence. The older MIPS-I architecture uses rfe and jr instead of eret. unmapped A portion of the address space that cannot have page faults.
Hennesey_Page_512_Chunk512
Save state Save GPR addi $k1,$sp, -XCPSIZE # save space on stack for state sw $sp, XCT_SP($k1) # save $sp on stack sw $v0, XCT_V0($k1) # save $v0 on stack ... # save $v1, $ai, $si, $ti,... on stack sw $ra, XCT_RA($k1) # save $ra on stack Save hi, lo mfhi $v0 # copy Hi mflo $v1 # copy Lo sw $v0, XCT_HI($k1) # save Hi value on stack sw $v1, XCT_LO($k1) # save Lo value on stack Save exception registers mfc0 $a0, $cr # copy cause register sw $a0, XCT_CR($k1) # save $cr value on stack ... # save $v1,.... mfc0 $a3, $sr # copy status register sw $a3, XCT_SR($k1) # save $sr on stack Set sp move $sp, $k1 # sp = sp - XCPSIZE Enable nested exceptions andi $v0, $a3, MASK1 # $v0 = $sr & MASK1, enable exceptions mtc0 $v0, $sr # $sr = value that enables exceptions Call C exception handler Set $gp move $gp, GPINIT # set $gp to point to heap area Call C code move $a0, $sp # arg1 = pointer to exception stack jal xcpt_deliver # call C code to handle exception Restoring state Restore most GPR, hi, lo move $at, $sp # temporary value of $sp lw $ra, XCT_RA($at) # restore $ra from stack ... # restore $t0,...., $a1 lw $a0, XCT_A0($k1) # restore $a0 from stack Restore status register lw $v0, XCT_SR($at) # load old $sr from stack li $v1, MASK2 # mask to disable exceptions and $v0, $v0, $v1 # $v0 = $sr & MASK2, disable exceptions mtc0 $v0, $sr # set status register Exception return Restore $sp and rest of GPR used as temporary registers lw $sp, XCT_SP($at) # restore $sp from stack lw $v0, XCT_V0($at) # restore $v0 from stack lw $v1, XCT_V1($at) # restore $v1 from stack lw $k1, XCT_EPC($at) # copy old $epc from stack lw $at, XCT_AT($at) # restore $at from stack Restore ERC and return mtc0 $k1, $epc # restore $epc eret $ra # return to interrupted instruction FIGURE 5.28 MIPS code to save and restore state on an exception. Elaboration: For processors with more complex instructions that can touch many memory locations and write many data items, making instructions restartable is much harder. Processing one instruction may generate a number of page faults in the middle of the instruction. For example, x86 processors have block move instructions that touch thousands of data words. In such processors, instructions often cannot be restarted 5.4 Virtual Memory 515
Hennesey_Page_513_Chunk513
516 Chapter 5 Large and Fast: Exploiting Memory Hierarchy from the beginning, as we do for MIPS instructions. Instead, the instruction must be interrupted and later continued midstream in its execution. Resuming an instruction in the middle of its execution usually requires saving some special state, processing the exception, and restoring that special state. Making this work prop­erly requires careful and detailed coordination between the exception-handling code in the operating system and the hardware. Summary Virtual memory is the name for the level of memory hierarchy that manages cach­ ing between the main memory and disk. Virtual memory allows a single program to expand its address space beyond the limits of main memory. More importantly, virtual memory supports sharing of the main memory among multiple, simulta­ neously active processes, in a protected manner. Managing the memory hierarchy between main memory and disk is challeng­ing because of the high cost of page faults. Several techniques are used to reduce the miss rate: 1. Pages are made large to take advantage of spatial locality and to reduce the miss rate. 2. The mapping between virtual addresses and physical addresses, which is implemented with a page table, is made fully associative so that a virtual page can be placed anywhere in main memory. 3. The operating system uses techniques, such as LRU and a reference bit, to choose which pages to replace. Writes to disk are expensive, so virtual memory uses a write-back scheme and also tracks whether a page is unchanged (using a dirty bit) to avoid writing unchanged pages back to disk. The virtual memory mechanism provides address translation from a virtual address used by the program to the physical address space used for accessing memory. This address translation allows protected sharing of the main memory and provides several additional benefits, such as simplifying memory allocation. Ensuring that processes are protected from each other requires that only the operating system can change the address translations, which is implemented by preventing user programs from changing the page tables. Controlled sharing of pages among processes can be implemented with the help of the operating sys­tem and access bits in the page table that indicate whether the user program has read or write access to a page. If a processor had to access a page table resident in memory to translate every ­access, virtual memory would be too expensive, as caches would be pointless! Instead, a TLB acts as a cache for translations from the page table. Addresses are then translated from virtual to physical using the translations in the TLB. Caches, virtual memory, and TLBs all rely on a common set of principles and policies. The next section discusses this common framework.
Hennesey_Page_514_Chunk514
Although virtual memory was invented to enable a small memory to act as a large one, the performance difference between disk and memory means that if a program routinely accesses more virtual memory than it has physical mem­ory, it will run very slowly. Such a program would be continuously swapping pages between memory and disk, called thrashing. Thrashing is a disaster if it occurs, but it is rare. If your program thrashes, the easiest solution is to run it on a computer with more memory or buy more memory for your computer. A more complex choice is to re-examine your algorithm and data structures to see if you can change the locality and thereby reduce the number of pages that your program uses simultaneously. This set of popular pages is informally called the working set. A more common performance problem is TLB misses. Since a TLB might handle only 32–64 page entries at a time, a program could easily see a high TLB miss rate, as the processor may access less than a quarter megabyte directly: 64 × 4 KB = 0.25 MB. For example, TLB misses are often a challenge for Radix Sort. To try to alleviate this problem, most computer architectures now support variable page sizes. For example, in addition to the standard 4 KB page, MIPS hardware sup­ports 16 KB, 64 KB, 256 KB, 1 MB, 4 MB, 16 MB, 64 MB, and 256 MB pages. Hence, if a program uses large page sizes, it can access more memory directly without TLB misses. The practical challenge is getting the operating system to allow programs to select these larger page sizes. Once again, the more complex solution to reducing TLB misses is to re-examine the algorithm and data structures to reduce the work­ ing set of pages; given the importance of memory accesses to performance and the frequency of TLB misses, some programs with large working sets have been redesigned with that goal. Match the memory hierarchy element on the left with the closest phrase on the right: 1. L1 cache a. A cache for a cache 2. L2 cache b. A cache for disks 3. Main memory c. A cache for a main memory 4. TLB d. A cache for page table entries Understanding Program Performance Check Yourself 5.4 Virtual Memory 517
Hennesey_Page_515_Chunk515
518 Chapter 5 Large and Fast: Exploiting Memory Hierarchy 5.5  A Common Framework for Memory Hierarchies By now, you’ve recognized that the different types of memory hierarchies share a great deal in common. Although many of the aspects of memory hierarchies differ quantitatively, many of the policies and features that determine how a hierarchy functions are similar qualitatively. Figure 5.29 shows how some of the quantitative characteristics of memory hierarchies can differ. In the rest of this section, we will discuss the common operational alternatives for memory hierarchies, and how these determine their behavior. We will examine these policies as a series of four questions that apply between any two levels of a memory hierarchy, although for simplicity we will primarily use terminology for caches. Feature Typical values for L1 caches Typical values for L2 caches Typical values for paged memory Typical values for a TLB Total size in blocks 250–2000 15,000–50,000 16,000–250,000 40–1024 Total size in kilobytes 16–64 500–4000 1,000,000–1,000,000,000 0.25–16 Block size in bytes 16–64 64–128 4000–64,000 4–32 Miss penalty in clocks 10–25 100–1000 10,000,000–100,000,000 10–1000 Miss rates (global for L2) 2%–5% 0.1%–2% 0.00001%–0.0001% 0.01%–2% FIGURE 5.29 The key quantitative design parameters that characterize the major elements of memory hierarchy in a com­puter. These are typical values for these levels as of 2008. Although the range of values is wide, this is partially because many of the values that have shifted over time are related; for example, as caches become larger to overcome larger miss penalties, block sizes also grow. Question 1: Where Can a Block Be Placed? We have seen that block placement in the upper level of the hierarchy can use a range of schemes, from direct mapped to set associative to fully associative. As mentioned above, this entire range of schemes can be thought of as variations on a set-associa­tive scheme where the number of sets and the number of blocks per set varies: Scheme name Number of sets Blocks per set Direct mapped Number of blocks in cache 1 Set associative ​ Number of blocks in the cache  Associativity ​ Associativity (typically 2–16) Fully associative 1 Number of blocks in the cache The advantage of increasing the degree of associativity is that it usually decreases the miss rate. The improvement in miss rate comes from reducing misses that com­ pete for the same location. We will examine these in more detail shortly. First, let’s
Hennesey_Page_516_Chunk516
look at how much improvement is gained. Figure 5.30 shows the miss rates for several cache sizes as associativity varies from direct mapped to eight-way set asso­ ciative. The largest gains are obtained in going from direct mapped to two-way set associative, which yields between a 20% and 30% reduc­tion in the miss rate. As cache sizes grow, the relative improvement from associa­tivity increases only slightly; since the overall miss rate of a larger cache is lower, the opportunity for improving the miss rate decreases and the absolute improve­ment in the miss rate from associativity shrinks significantly. The potential disad­vantages of associativ­ ity, as we mentioned earlier, are increased cost and slower access time. FIGURE 5.30 The data cache miss rates for each of eight cache sizes improve as the associativity increases. While the benefit of going from one-way (direct mapped) to two-way set asso­ciative is significant, the benefits of further associativity are smaller (e.g., 1%–10% improvement going from two-way to four-way versus 20%–30% improvement going from one-way to two-way). There is even less improvement in going from four-way to eight-way set associative, which, in turn, comes very close to the miss rates of a fully associative cache. Smaller caches obtain a significantly larger absolute benefit from associativity because the base miss rate of a small cache is larger. Figure 5.15 explains how this data was col­lected. Associativity Miss rate 0 One-way Two-way 3% 6% 9% 12% 15% Four-way Eight-way 1 KB 2 KB 4 KB 8 KB 16 KB 32 KB 64 KB 128 KB Question 2: How Is a Block Found? The choice of how we locate a block depends on the block placement scheme, since that dictates the number of possible locations. We can summarize the schemes as follows: 5.5 A Common Framework for Memory Hierarchies 519
Hennesey_Page_517_Chunk517
520 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Associativity Location method Comparisons required Direct mapped Index 1 Set associative Index the set, search among elements Degree of associativity Full Search all cache entries Size of the cache Separate lookup table 0 The choice among direct-mapped, set-associative, or fully associative mapping in any memory hierarchy will depend on the cost of a miss versus the cost of implementing associativity, both in time and in extra hardware. Including the L2 cache on the chip enables much higher associativity, because the hit times are not as critical and the designer does not have to rely on standard SRAM chips as the building blocks. Fully associative caches are prohibitive except for small sizes, where the cost of the comparators is not overwhelming and where the absolute miss rate improvements are greatest. In virtual memory systems, a separate mapping table—the page table—is kept to index the memory. In addition to the storage required for the table, using an index table requires an extra memory access. The choice of full associativity for page placement and the extra table is motivated by these facts: 1. Full associativity is beneficial, since misses are very expensive. 2. Full associativity allows software to use sophisticated replacement schemes that are designed to reduce the miss rate. 3. The full map can be easily indexed with no extra hardware and no search­ing required. Therefore, virtual memory systems almost always use fully associative placement. Set-associative placement is often used for caches and TLBs, where the access combines indexing and the search of a small set. A few systems have used direct- mapped caches because of their advantage in access time and simplicity. The advantage in access time occurs because finding the requested block does not depend on a comparison. Such design choices depend on many details of the implementation, such as whether the cache is on-chip, the technology used for implementing the cache, and the critical role of cache access time in determining the processor cycle time. Question 3: Which Block Should Be Replaced on a Cache Miss? When a miss occurs in an associative cache, we must decide which block to replace. In a fully associative cache, all blocks are candidates for replacement. If the cache is set associative, we must choose among the blocks in the set. Of course, replacement is easy in a direct-mapped cache because there is only one candidate.
Hennesey_Page_518_Chunk518
There are the two primary strategies for replacement in set-associative or fully associative caches: ■ ■Random: Candidate blocks are randomly selected, possibly using some hardware assistance. For example, MIPS supports random replacement for TLB misses. ■ ■Least recently used (LRU): The block replaced is the one that has been unused for the longest time. In practice, LRU is too costly to implement for hierarchies with more than a small degree of associativity (two to four, typically), since tracking the usage information is costly. Even for four-way set associativity, LRU is often approximated—for example, by keeping track of which pair of blocks is LRU (which ­requires 1 bit), and then tracking which block in each pair is LRU (which requires 1 bit per pair). For larger associativity, either LRU is approximated or random replacement is used. In caches, the replacement algorithm is in hardware, which means that the scheme should be easy to implement. Random replacement is simple to build in hardware, and for a two-way set-associative cache, random replacement has a miss rate about 1.1 times higher than LRU­ ­replacement. As the caches become larger, the miss rate for both replacement ­strategies falls, and the absolute differ­ence becomes small. In fact, random replacement can sometimes be better than the simple LRU approximations that are easily implemented in hardware. In virtual memory, some form of LRU is always approximated, since even a tiny reduction in the miss rate can be important when the cost of a miss is enormous. Reference bits or equivalent functionality are often provided to make it easier for the operating system to track a set of less recently used pages. ­Because misses are so expensive and relatively infrequent, approximating this information primarily in software is acceptable. Question 4: What Happens on a Write? A key characteristic of any memory hierarchy is how it deals with writes. We have already seen the two basic options: ■ ■Write-through: The information is written to both the block in the cache and the block in the lower level of the memory hierarchy (main memory for a cache). The caches in Section 5.2 used this scheme. ■ ■Write-back: The in­formation is written only to the block in the cache. The modi­fied block is written to the lower level of the hierarchy only when it is re­placed. Virtual memory systems always use write-back, for the reasons discussed in Section 5.4. 5.5 A Common Framework for Memory Hierarchies 521
Hennesey_Page_519_Chunk519
522 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Both write-back and write-through have their advantages. The key advantages of write-back are the following: ■ ■Individual words can be written by the processor at the rate that the cache, rather than the memory, can accept them. ■ ■Multiple writes within a block require only one write to the lower level in the hierarchy. ■ ■When blocks are written back, the system can make effective use of a high- bandwidth transfer, since the entire block is written. Write-through has these advantages: ■ ■Misses are simpler and cheaper because they never require a block to be written back to the lower level. ■ ■Write-through is easier to implement than write-back, although to be prac­ tical, a write-through cache will still need to use a write buffer. In virtual memory systems, only a write-back policy is practical because of the long latency of a write to the lower level of the hierarchy (disk). The rate at which writes are generated by a processor generally exceed the rate at which the memory system can process them, even allowing for physically and logically wider memories and burst modes for DRAM. Consequently, today lowest-level caches typically use write-back. Caches, TLBs, and virtual memory may initially look very different, but they rely on the same two principles of locality, and they can be under­ stood by their answers to four questions: Question 1: Where can a block be placed? Answer: One place (direct mapped), a few places (set associative), or any place (fully associative). Question 2: How is a block found? Answer: There are four methods: indexing (as in a direct-mapped cache), limited search (as in a set-associative cache), full search (as in a fully associative cache), and a separate lookup table (as in a page table). Question 3: What block is replaced on a miss? Answer: Typically, either the least recently used or a random block. Question 4: How are writes handled? Answer: Each level in the hierarchy can use either write-through or write-back. The BIG Picture
Hennesey_Page_520_Chunk520
5.5 A Common Framework for Memory Hierarchies 523 The Three Cs: An Intuitive Model for Understanding the Behavior of Memory Hierarchies In this section, we look at a model that provides insight into the sources of misses in a memory hierarchy and how the misses will be affected by changes in the hier­ archy. We will explain the ideas in terms of caches, although the ideas carry over directly to any other level in the hierarchy. In this model, all misses are classified into one of three categories (the three Cs): ■ Compulsory misses: These are cache misses caused by the first access to a block that has never been in the cache. These are also called cold-start misses. ■ Capacity misses: These are cache misses caused when the cache cannot con­ tain all the blocks needed during execution of a program. Capacity misses occur when blocks are replaced and then later retrieved. ■ Conflict misses: These are cache misses that occur in set-associative or ­direct-mapped caches when multiple blocks compete for the same set. Con­ flict misses are those misses in a direct-mapped or set-associative cache that are eliminated in a fully associative cache of the same size. These cache misses are also called collision misses. Figure 5.31 shows how the miss rate divides into the three sources. These sources of misses can be directly attacked by changing some aspect of the cache design. Since conflict misses arise directly from contention for the same cache block, increasing associativity reduces conflict misses. Associativity, however, may slow access time, leading to lower overall performance. Capacity misses can easily be reduced by enlarging the cache; indeed, second- level caches have been growing steadily larger for many years. Of course, when we make the cache larger, we must also be careful about increasing the access time, which could lead to lower overall performance. Thus, first-level caches have been growing slowly, if at all. Because compulsory misses are generated by the first reference to a block, the primary way for the cache system to reduce the number of compulsory misses is to increase the block size. This will reduce the number of references required to touch each block of the program once, because the program will consist of fewer cache blocks. As mentioned above, increasing the block size too much can have a negative effect on performance because of the increase in the miss penalty. The decomposition of misses into the three Cs is a useful qualitative model. In real cache designs, many of the design choices interact, and changing one cache characteristic will often affect several components of the miss rate. Despite such shortcomings, this model is a useful way to gain insight into the performance of cache designs. three Cs model A cache model in which all cache misses are classified into one of three cate­gories: compulsory misses, capacity misses, and conflict misses. compulsory miss Also called cold-start miss. A cache miss caused by the first access to a block that has ­never been in the cache. capacity miss A cache miss that occurs because the cache, even with full associativity, can­not contain all the blocks needed to satisfy the request. conflict miss Also called colli­sion miss. A cache miss that occurs in a set-associative or direct­ mapped cache when mul­tiple blocks compete for the same set and that are eliminated in a fully associative cache of the same size.
Hennesey_Page_521_Chunk521
524 Chapter 5 Large and Fast: Exploiting Memory Hierarchy The challenge in designing memory hierarchies is that every change that potentially improves the miss rate can also negatively affect overall perfor­ mance, as Figure 5.32 summarizes. This combination of ­positive and nega­ tive effects is what makes the design of a memory hierarchy interesting. FIGURE 5.31 The miss rate can be broken into three sources of misses. This graph shows the total miss rate and its components for a range of cache sizes. This data is for the SPEC CPU2000 integer and floating-point benchmarks and is from the same source as the data in Figure 5.30. The compulsory miss component is 0.006% and cannot be seen in this graph. The next component is the capacity miss rate, which depends on cache size. The conflict portion, which depends both on associativity and on cache size, is shown for a range of associativities from one-way to eight-way. In each case, the labeled section corre­sponds to the increase in the miss rate that occurs when the associativity is changed from the next higher degree to the labeled degree of associativity. For example, the section labeled two-way indicates the addi­tional misses arising when the cache has associativity of two rather than four. Thus, the difference in the miss rate incurred by a direct-mapped cache versus a fully associative cache of the same size is given by the sum of the sections marked eight-way, four-way, two-way, and one-way. The difference between eight-way and four-way is so small that it is difficult to see on this graph. Cache size (KB) Miss rate per type 0% 8 32 1% 2% 3% 4% 5% 128 512 6% 7% 16 64 256 4 Capacity 8% 9% 10% 1024 One-way Two-way Four-way The BIG Picture
Hennesey_Page_522_Chunk522
Design change Effect on miss rate Possible negative performance effect Increase cache size Decreases capacity misses May increase access time Increase associativity Decreases miss rate due to conflict misses May increase access time Increase block size Decreases miss rate for a wide range of block sizes due to spatial locality Increases miss penalty. Very large block could increase miss rate FIGURE 5.32 Memory hierarchy design challenges. Which of the following statements (if any) are generally true? 1. There is no way to reduce compulsory misses. 2. Fully associative caches have no conflict misses. 3. In reducing misses, associativity is more important than capacity. 5.6 Virtual Machines An idea related to virtual memory that is almost as old is Virtual Machines (VM). They were first developed in the mid-1960s, and they have remained an important part of mainframe computing over the years. Although largely ignored in the domain of single-user computers in the 1980s and 1990s, they have recently gained popularity due to ■ ■The increasing importance of isolation and security in modern systems ■ ■The failures in security and reliability of standard operating systems ■ ■The sharing of a single computer among many unrelated users ■ ■The dramatic increases in raw speed of processors over the decades, which makes the overhead of VMs more acceptable The broadest definition of VMs includes basically all emulation methods that provide a standard software interface, such as the Java VM. In this section, we are interested in VMs that provide a complete system-level environment at the binary instruction set architecture (ISA) level. Although some VMs run different ISAs in the VM from the native hardware, we assume they always match the hardware. Such VMs are called (Operating) System Virtual Machines. IBM VM/370, VMware ESX Server, and Xen are examples. Check Yourself 5.6 Virtual Machines 525
Hennesey_Page_523_Chunk523
526 Chapter 5 Large and Fast: Exploiting Memory Hierarchy System virtual machines present the illusion that the users have an entire ­computer to themselves, including a copy of the operating system. A single com­ puter runs multiple VMs and can support a number of different operating systems (OSes). On a conventional platform, a single OS “owns” all the hardware resources, but with a VM, multiple OSes all share the hardware resources. The software that supports VMs is called a virtual machine monitor (VMM) or hypervisor; the VMM is the heart of virtual machine technology. The underlying hardware platform is called the host, and its resources are shared among the guest VMs. The VMM determines how to map virtual resources to physical resources: a physical resource may be time-shared, partitioned, or even emulated in software. The VMM is much smaller than a traditional OS; the isolation portion of a VMM is perhaps only 10,000 lines of code. Although our interest here is in VMs for improving protection, VMs provide two other benefits that are commercially significant: 1. Managing software. VMs provide an abstraction that can run the complete software stack, even including old operating systems like DOS. A typical deployment might be some VMs running legacy OSes, many running the current stable OS release, and a few testing the next OS release. 2. Managing hardware. One reason for multiple servers is to have each appli­ cation running with the compatible version of the operating system on sep­ arate computers, as this separation can improve dependability. VMs allow these separate software stacks to run independently yet share hardware, thereby consolidating the number of servers. Another example is that some VMMs support migration of a running VM to a different computer, either to balance load or to evacuate from failing hardware. In general, the cost of processor virtualization depends on the workload. User- level processor-bound programs have zero virtualization overhead, because the OS is rarely invoked, so everything runs at native speeds. I/O-intensive workloads are generally also OS-intensive, executing many system calls and privileged instructions that can result in high virtualization overhead. On the other hand, if the I/O-intensive workload is also I/O-bound, the cost of processor virtualization can be completely hidden, since the processor is often idle waiting for I/O. The overhead is determined by both the number of instructions that must be emulated by the VMM and by how much time each takes to emulate. Hence, when the guest VMs run the same ISA as the host, as we assume here, the goal of the architecture and the VMM is to run almost all instructions directly on the native hardware.
Hennesey_Page_524_Chunk524
Requirements of a Virtual Machine Monitor What must a VM monitor do? It presents a software interface to guest software, it must isolate the state of guests from each other, and it must protect itself from guest software (including guest OSes). The qualitative requirements are: ■ ■Guest software should behave on a VM exactly as if it were running on the native hardware, except for performance-related behavior or limitations of fixed resources shared by multiple VMs. ■ ■Guest software should not be able to change allocation of real system resources directly. To “virtualize” the processor, the VMM must control just about everything—access to privileged state, address translation, I/O, exceptions, and interrupts—even though the guest VM and OS currently running are temporarily using them. For example, in the case of a timer interrupt, the VMM would suspend the cur­ rently running guest VM, save its state, handle the interrupt, determine which guest VM to run next, and then load its state. Guest VMs that rely on a timer interrupt are provided with a virtual timer and an emulated timer interrupt by the VMM. To be in charge, the VMM must be at a higher privilege level than the guest VM, which generally runs in user mode; this also ensures that the execution of any privileged instruction will be handled by the VMM. The basic requirements of ­system virtual machines are almost identical to those for paged virtual memory listed above: ■ ■At least two processor modes, system and user ■ ■A privileged subset of instructions that is available only in system mode, resulting in a trap if executed in user mode; all system resources must be controllable only via these instructions (Lack of) Instruction Set Architecture Support for Virtual Machines If VMs are planned for during the design of the ISA, it’s relatively easy to reduce both the number of instructions that must be executed by a VMM and improve their emulation speed. An architecture that allows the VM to execute directly on the hardware earns the title virtualizable, and the IBM 370 architecture proudly bears that label. Alas, since VMs have been considered for desktop and PC-based server applica­ tions only fairly recently, most instruction sets were created without virtualization in mind. These culprits include x86 and most RISC architectures, including ARM and MIPS. 5.6 Virtual Machines 527
Hennesey_Page_525_Chunk525
528 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Because the VMM must ensure that the guest system only interacts with virtual resources, a conventional guest OS runs as a user mode program on top of the VMM. Then, if a guest OS attempts to access or modify information related to hardware resources via a privileged instruction—for example, reading or writing the page table pointer—it will trap to the VMM. The VMM can then effect the appropriate changes to corresponding real resources. Hence, if any instruction that tries to read or write such sensitive information traps when executed in user mode, the VMM can intercept it and support a virtual version of the sensitive information, as the guest OS expects. In the absence of such support, other measures must be taken. A VMM must take special precautions to locate all problematic instructions and ensure that they behave correctly when executed by a guest OS, thereby increasing the complexity of the VMM and reducing the performance of running the VM. Protection and Instruction Set Architecture Protection is a joint effort of architecture and operating systems, but architects had to modify some awkward details of existing instruction set architectures when virtual memory became popular. For example, to support virtual memory in the IBM 370, architects had to change the successful IBM 360 instruction set architec­ ture that had been announced just six years before. Similar adjustments are being made today to accommodate virtual machines. For example, the x86 instruction POPF loads the flag registers from the top of the stack in memory. One of the flags is the Interrupt Enable (IE) flag. If you run the POPF instruction in user mode, rather than trap it, it simply changes all the flags except IE. In system mode, it does change the IE. Since a guest OS runs in user mode inside a VM, this is a problem, as it expects to see a changed IE. Historically, IBM mainframe hardware and VMM took three steps to improve performance of virtual machines: 1. Reduce the cost of processor virtualization 2. Reduce interrupt overhead cost due to the virtualization 3. Reduce interrupt cost by steering interrupts to the proper VM without invoking VMM In 2006, new proposals by AMD and Intel try to address the first point, reduc­ing the cost of processor virtualization. It will be interesting to see how many genera­ tions of architecture and VMM modifications it will take to address all three points, and how long before virtual machines of the 21st century will be as effi­cient as the IBM mainframes and VMMs of the 1970s.
Hennesey_Page_526_Chunk526
Elaboration: In addition to virtualizing the instruction set, another challenge is virtualiza­tion of virtual memory, as each guest OS in every VM manages its own set of page tables. To make this work, the VMM separates the notions of real and physical memory (which are often treated synonymously), and makes real memory a separate, intermediate level between virtual memory and physical memory. (Some use the terms virtual memory, physical memory, and machine memory to name the same three levels.) The guest OS maps virtual memory to real memory via its page tables, and the VMM page tables map the guest’s real memory to physical memory. The virtual memory architecture is specified either via page tables, as in IBM VM/370 and the x86, or via the TLB structure, as in MIPS. Rather than pay an extra level of indirection on every memory access, the VMM maintains a shadow page table that maps directly from the guest virtual address space to the physical address space of the hardware. By detecting all modifications to the guest’s page table, the VMM can ensure the shadow page table entries being used by the hardware for translations cor­respond to those of the guest OS environment, with the exception of the correct physical pages substituted for the real pages in the guest tables. Hence, the VMM must trap any attempt by the guest OS to change its page table or to access the page table pointer. This is commonly done by write protecting the guest page tables and trapping any access to the page table pointer by a guest OS. As noted above, the latter happens naturally if accessing the page table pointer is a privileged operation. The final portion of the architecture to virtualize is I/O. This is by far the most difficult part of system virtualization because of the increasing number of I/O devices attached to the com­puter and the increasing diversity of I/O device types. Another difficulty is the sharing of a real device among multiple VMs, and yet another comes from supporting the myriad of device driv­ers that are required, especially if different guest OSes are supported on the same VM system. The VM illusion can be maintained by giving each VM generic versions of each type of I/O device driver, and then leaving it to the VMM to handle real I/O. 5.7 Using a Finite-State Machine to Control a Simple Cache We can now implement control for a cache, just as we implemented control for the single-cycle and pipelined datapaths in Chapter 4. This section starts with a definition of a simple cache and then a description of finite-state machines (FSM). It finishes with the FSM of a controller for this simple cache. Section 5.9 on the CD goes into more depth, showing the cache and controller in a new hardware description language. A Simple Cache We’re going to design a controller for a simple cache. Here are the key charateris­tics of the cache: 5.7 Using a Finite-State Machine to Control a Simple Cache 529
Hennesey_Page_527_Chunk527
530 Chapter 5 Large and Fast: Exploiting Memory Hierarchy ■ ■Direct-mapped cache ■ ■Write-back using write allocate ■ ■Block size is 4 words (16 bytes or 128 bits) ■ ■Cache size is 16 KB, so it holds 1024 blocks ■ ■32-bit byte addresses ■ ■The cache includes a valid bit and dirty bit per block From Section 5.2, we can now calculate the fields of an address for the cache: ■ ■Cache index is 10 bits ■ ■Block offset is 4 bits ■ ■Tag size is 32 - (10 + 4) or 18 bits The signals between the processor to the cache are ■ ■1-bit Read or Write signal ■ ■1-bit Valid signal, saying whether there is a cache operation or not ■ ■32-bit address ■ ■32-bit data from processor to cache ■ ■32-bit data from cache to processor ■ ■1-bit Ready signal, saying the cache operation is complete Note that this is a blocking cache, in that the processor must wait until the cache has finished the request. The interface between the memory and the cache has the same fields as between the processor and the cache, except that the data fields are now 128 bits wide. The extra memory width in generally found microprocessors today, which deal with either 32-bit or 64-bit words in the processor while the DRAM control­ler is often 128 bits. Making the cache block match the width of the DRAM sim­plified the design. Here are the signals: ■ ■1-bit Read or Write signal ■ ■1-bit Valid signal, saying whether there is a memory operation or not ■ ■32-bit address ■ ■128-bit data from cache to memory ■ ■128-bit data from memory to cache ■ ■1-bit Ready signal, saying the memory operation is complete
Hennesey_Page_528_Chunk528
Note that the interface to memory is not a fixed number of cycles. We assume a memory controller that will notify the cache via the Ready signal when the mem­ ory read or write is finished. Before describing the cache controller, we need to review finite-state machines, which allow us to control an operation that can take multiple clock cycles. Finite-State Machines To design the control unit for the single-cycle datapath, we used a set of truth tables that specified the setting of the control signals based on the instruction class. For a cache, the control is more complex because the operation can be a series of steps. The control for a cache must specify both the signals to be set in any step and the next step in the sequence. The most common multistep control method is based on finite-state machines, which are usually represented graphically. A finite-state machine con­sists of a set of states and directions on how to change states. The directions are defined by a next-state function, which maps the current state and the inputs to a new state. When we use a finite-state machine for control, each state also specifies a set of outputs that are asserted when the machine is in that state. The implemen­tation of a finite-state machine usually assumes that all outputs that are not explicitly asserted are deasserted. Similarly, the correct operation of the datapath depends on the fact that a signal that is not explicitly asserted is deasserted, rather than acting as a don’t care. Multiplexor controls are slightly different, since they select one of the inputs whether they are 0 or 1. Thus, in the finite-state machine, we always specify the setting of all the multiplexor controls that we care about. When we implement the finite-state machine with logic, setting a control to 0 may be the default and thus may not require any gates. A simple example of a finite-state machine appears in Appendix C, and if you are unfamiliar with the concept of a finite-state machine, you may want to examine Appendix C before proceeding. A finite-state machine can be implemented with a temporary register that holds the current state and a block of combinational logic that determines both the data­­ path signals to be asserted and the next state. Figure 5.33 shows how such an imple­ mentation might look. Appendix D describes in detail how the finite-state machine is implemented using this structure. In Section C.3, the combinational control logic for a finite-state machine is implemented both with a ROM (read- only memory) and a PLA (programmable logic array). (Also see Appendix C for a description of these logic elements.) finite-state machine A sequen­tial logic function con­sisting of a set of inputs and outputs, a next-state function that maps the cur­rent state and the inputs to a new state, and an output function that maps the ­current state and possibly the inputs to a set of­ asserted outputs. next-state function A combi­national function that, ­given the inputs and the current state, determines the next state of a finite-state machine. 5.7 Using a Finite-State Machine to Control a Simple Cache 531
Hennesey_Page_529_Chunk529
532 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Elaboration: The style of finite-state machine in this book is called a Moore machines, after Edward Moore. Its identifying characteristic is that the output depends only on the current state. For a Moore machine, the box labeled combinational control logic can be split into two pieces. One piece has the control output and only the state input, while the other has only the next-state output. An alternative style of machine is a Mealy machine, named after George Mealy. The Mealy machine allows both the input and the current state to be used to determine the output. Moore machines have potential implementation advantages in speed and size of the control unit. The speed advantages arise because the control outputs, which are needed early in the clock cycle, do not depend on the inputs, but only on the current state. In Appendix C, when the imple­mentation of this finite-state machine is taken down to logic gates, the size advantage can be clearly seen. The potential disadvantage of a Moore machine is that it may require additional states. For example, in situations where there is a one-state difference between two sequences of states, the Mealy machine may unify the states by making the outputs depend on the inputs. FIGURE 5.33 Finite-state machine controllers are typically implemented using a block of combinational logic and a register to hold the current state. The outputs of the combina­ tional logic are the next-state number and the control signals to be asserted for the current state. The inputs to the combinational logic are the current state and any inputs used to determine the next state. In this case, the inputs are the instruction register opcode bits. Notice that in the finite-state machine used in this chapter, the outputs depend only on the current state, not on the inputs. The Elaboration explains this in more detail. Combinational control logic Outputs Inputs State register Next state Datapath control outputs Inputs from cache datapath
Hennesey_Page_530_Chunk530
FSM for a Simple Cache Controller Figure 5.34 shows the four states of our simple cache controller: ■ ■Idle: This state waits for a valid read or write request from the processor, which moves the FSM to the Compare Tag state. ■ ■Compare Tag: As the name suggests, this state tests to see if the requested read or write is a hit or a miss. The index portion of the address selects the tag to be compared. If the data in the cache block referred to by the index portion of the address is valid and the tag portion of the address matches the tag, then the requested read or write is a hit. Either the data is read from the selected word or the writ­ten to the selected word, and then the Cache Ready signal is set. If it is a write, the dirty bit is set to 1. Note that a write hit also sets the valid bit and the tag field; while it seems unnecessary, it is included because the tag is a single memory, so to change the dirty bit we also need to change the valid and tag fields. If it is a hit and the block is valid, the FSM returns to the idle state. A miss first updates the cache tag and then goes either to the Write-Back state, if the block at this location has dirty bit value of 1, or to the Allo­cate state if it is 0. 5.7 Using a Finite-State Machine to Control a Simple Cache 533 FIGURE 5.34 Four states of the simple controller. Cache Miss and Old Block is Dirty Cache Miss and Old Block is Clean Valid CPU request Mark Cache Ready Idle Cache Hit Compare Tag If Valid && Hit , Set Valid, SetTag, if Write Set Dirty Memory Ready Memory Ready Memory not Ready Memory not Ready Write Old Block to Memory Write-Back Read new block from Memory Allocate
Hennesey_Page_531_Chunk531
534 Chapter 5 Large and Fast: Exploiting Memory Hierarchy ■ ■Write-Back: This state writes the 128-bit block to memory using the address composed from the tag and cache index. We remain in this state waiting for the Ready signal from memory. When the memory write is complete, the FSM goes to the Allocate state. ■ ■Allocate: The new block is fetched from memory. We remain in this state waiting for the Ready signal from memory. When the memory read is com­ plete, the FSM goes to the Compare Tag state. Although we could have gone to a new state to complete the operation instead of reusing the Compare Tag state, there is a good deal of overlap, including the update of the appropriate word in the block if the access was a write. This simple model could easily be extended with more states to try to improve performance. For example, the Compare Tag state does both the compare and the read or write of the cache data in a single clock cycle. Often the compare and cache access are done in separate states to try to improve the clock cycle time. Another optimization would be to add a write buffer so that we could save the dirty block and then read the new block first so that the processor doesn’t have to wait for two memory accesses on a dirty miss. The cache would then write the dirty block from the write buffer while the processor is operating on the requested data. Section 5.9, on the CD, goes into more detail about the FSM, showing the full controller in a hardware description language and a block diagram of this simple cache. 5.8  Parallelism and Memory Hierarchies: Cache Coherence Given that a multicore multiprocessor means multiple processors on a single chip, these processors very likely share a common physical address space. Caching shared data introduces a new problem, because the view of memory held by two different processors is through their individual caches, which, without any additional precau­tions, could end up seeing two different values. Figure 5.35 illustrates the problem and shows how two different processors can have two different values for the same location. This difficulty is generally referred to as the cache coherence problem. Informally, we could say that a memory system is coherent if any read of a data item returns the most recently written value of that data item. This definition, although intuitively appealing, is vague and simplistic; the reality is much more complex. This simple definition contains two different aspects of memory system behavior, both of which are critical to writing correct shared memory programs. The first aspect, called coherence, defines what values can be returned by a read.
Hennesey_Page_532_Chunk532
The second aspect, called consistency, determines when a written value will be returned by a read. Let’s look at coherence first. A memory system is coherent if 1. A read by a processor P to a location X that follows a write by P to X, with no writes of X by another processor occurring between the write and the read by P, always returns the value written by P. Thus, in Figure 5.35 above, if CPU A were to read X after time step 3, it should see the value 1. 2. A read by a processor to location X that follows a write by another proces­sor to X returns the written value if the read and write are sufficiently sepa­rated in time and no other writes to X occur between the two accesses. Thus, in Figure 5.35, we need a mechanism so that the value 0 in the cache of CPU B is replaced by the value 1 after CPU A stores 1 into memory at address X in time step 3. 3. Writes to the same location are serialized; that is, two writes to the same location by any two processors are seen in the same order by all processors. For example, if CPU B stores 2 into memory at address X after time step 3, processors can never read the value at location X as 2 and then later read it as 1. The first property simply preserves program order—we certainly expect this property to be true in uniprocessors, for example. The second property defines the notion of what it means to have a coherent view of memory: if a processor could continuously read an old data value, we would clearly say that memory was incoherent. The need for write serialization is more subtle, but equally important. Suppose we did not serialize writes, and processor P1 writes location X followed by P2 writing location X. Serializing the writes ensures that every processor will see the FIGURE 5.35 The cache coherence problem for a single memory location (X), read and written by two processors (A and B). We initially assume that neither cache contains the variable and that X has the value 0. We also assume a write-through cache; a write-back cache adds some additional but similar complications. After the value of X has been written by A, A’s cache and the memory both con­tain the new value, but B’s cache does not, and if B reads the value of X, it will receive 0! Time step Event Cache contents for CPU A Cache contents for CPU B Memory contents for location X 0 0 1 CPU A reads X 0 0 2 CPU B reads X 0 0 0 3 CPU A stores 1 into X 1 0 1 5.8 Parallelism and Memory Hierarchies: Cache Coherence 535
Hennesey_Page_533_Chunk533
536 Chapter 5 Large and Fast: Exploiting Memory Hierarchy write done by P2 at some point. If we did not serialize the writes, it might be the case that some processor could see the write of P2 first and then see the write of P1, maintaining the value written by P1 indefinitely. The simplest way to avoid such difficulties is to ensure that all writes to the same location are seen in the same order; this property is called write serialization. Basic Schemes for Enforcing Coherence In a cache coherent multiprocessor, the caches provide both ­migration and replica­ tion of shared data items: ■ ■Migration: A data item can be moved to a local cache and used there in a transparent fashion. Migration reduces both the latency to access a shared data item that is allocated remotely and the bandwidth demand on the shared memory. ■ ■Replication: When shared data are being ­simultaneously read, the caches make a copy of the data item in the local cache. Replication reduces both latency of access and contention for a read shared data item. Supporting this migration and replication is critical to performance in access­ing shared data, so many multiprocessors introduce a hardware protocol to main­tain coherent caches. The protocols to maintain coherence for multiple processors are called cache coherence proto­cols. Key to implementing a cache coherence proto­col is tracking the state of any sharing of a data block. The most popular cache coherence protocol is snooping. Every cache that has a copy of the data from a block of physical memory also has a copy of the sharing status of the block, but no centralized state is kept. The caches are all accessible via some broadcast medium (a bus or network), and all cache controllers monitor or snoop on the medium to determine whether or not they have a copy of a block that is requested on a bus or switch access. In the following section we explain snooping-based cache coherence as imple­ mented with a shared bus, but any communication medium that broadcasts cache misses to all processors can be used to implement a snooping-based coherence scheme. This broadcasting to all caches makes snooping protocols simple to implement but also limits their scalability. Snooping Protocols One method of enforcing coherence is to ensure that a processor has exclusive access to a data item before it writes that item. This style of protocol is called a write invalidate protocol because it invalidates copies in other caches on a write. Exclusive access ensures that no other readable or writable copies of an item exist when the write occurs: all other cached copies of the item are invalidated.
Hennesey_Page_534_Chunk534
Figure 5.36 shows an example of an invalidation protocol for a snooping bus with write-back caches in action. To see how this protocol ensures coherence, ­con­sider a write followed by a read by another processor: since the write requires exclu­ sive access, any copy held by the reading processor must be invalidated (hence the protocol name). Thus, when the read occurs, it misses in the cache, and the cache is forced to fetch a new copy of the data. For a write, we require that the writing processor have exclusive access, preventing any other processor from being able to write simultaneously. If two processors do attempt to write the same data simulta­ neously, one of them wins the race, causing the other proces­sor’s copy to be invali­ dated. For the other processor to complete its write, it must obtain a new copy of the data, which must now contain the updated value. There­fore, this protocol also enforces write serialization. FIGURE 5.36 An example of an invalidation protocol working on a snooping bus for a single cache block (X) with write-back caches. We assume that neither cache initially holds X and that the value of X in memory is 0. The CPU and memory contents show the value after the processor and bus activity have both completed. A blank indicates no activity or no copy cached. When the second miss by B occurs, CPU A responds with the value canceling the response from memory. In addition, both the contents of B’s cache and the memory contents of X are updated. This update of memory, which occurs when a block becomes shared, simplifies the protocol, but it is possible to track the ownership and force the write-back only if the block is replaced. This requires the introduction of an additional state called “owner,” which indicates that a block may be shared, but the owning processor is responsible for updating any other processors and memory when it changes the block or replaces it. Processor activity Bus activity Contents of CPU A’s cache Contents of CPU B’s cache Contents of memory location X 0 CPU A reads X Cache miss for X 0 0 CPU B reads X Cache miss for X 0 0 0 CPU A writes a 1 to X Invalidation for X 1 0 CPU B reads X Cache miss for X 1 1 1 One insight is that block size plays an important role in cache coherency. For example, take the case of snooping on a cache with a block size of eight words, with a single word alternatively writ­ten and read by two processors. Most proto­cols exchange full blocks between processors, thereby increasing coherency bandwidth demands. Large blocks can also cause what is called false shar­ing: when two unrelated shared variables are located in the same cache block, the full block is exchanged between processors even though the processors are accessing different variables. Programmers and compilers should lay out data carefully to avoid false sharing. Hardware/ Software Interface false sharing When two unre­lated shared variables are located in the same cache block and the full block is exchanged between ­processors even though the ­processors are accessing dif­ferent variables. 5.8 Parallelism and Memory Hierarchies: Cache Coherence 537
Hennesey_Page_535_Chunk535
538 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Elaboration: Although the three properties on page 535 are sufficient to ensure coherence, the question of when a written value will be seen is also important. To see why, observe that we cannot require that a read of X in Figure 5.35 instantaneously sees the value writ­ten for X by some other pro­cessor. If, for example, a write of X on one processor precedes a read of X on another processor very shortly beforehand, it may be impossible to ensure that the read returns the value of the data written, since the written data may not even have left the pro­cessor at that point. The issue of exactly when a written value must be seen by a reader is defined by a memory consistency model. We make the following two assumptions. First, a write does not complete (and allow the next write to occur) until all processors have seen the effect of that write. Second, the processor does not change the order of any write with respect to any other memory access. These two con­ditions mean that if a processor writes location X followed by location Y, any processor that sees the new value of Y must also see the new value of X. These restrictions allow the processor to reorder reads, but forces the processor to finish a write in program order. Elaboration: Since input can change memory behind the caches and since output could need the latest value in a write back cache, there is also a cache coherency problem for I/O with the caches of a single processor as well as just between caches of multiple processors. The cache coherence problem for multiprocessors and I/O (see Chapter 6), although similar in origin, has different characteristics that affect the appropriate solution. Unlike I/O, where multiple data copies are a rare event—one to be avoided whenever possi­ble—a program running on multiple proces­sors will normally have copies of the same data in several caches. Elaboration: In addition to the snooping cache coherence protocol where the status of shared blocks is distributed, a directory-based cache coherence protocol keeps the sharing sta­tus of a block of physical memory in just one location, called the directory. Directory-based coherence has slightly higher implementation overhead than snooping, but it can reduce traffic between caches and thus scale to larger processor counts. Advanced Material: Implementing Cache Controllers This section on the CD shows how to implement control for a cache, just as we implemented control for the single-cycle and pipelined datapaths in Chapter 4. This section starts with a description of finite-state machines and the implemention of a cache controller for a simple data cache, including a description of the cache controller in a hardware description language. It then goes into details of an example cache coherence protocol and the difficulties in implementing such a protocol. 5.9
Hennesey_Page_536_Chunk536
5.10 Real Stuff 539 FIGURE 5.37 An Intel Nehalem die processor photo with the components labeled. This 13.5 by 19.6 mm die has 731 million transistors. It contains four processors that each have private 32-KB instruction and 32-LKB instruction caches and a 512-KB L2 cache. The four cores share an 8-MB L3 cache. The two 128-bit memory channels are to DDR3 DRAM. Each core also has a two-level TLB. The memory controller is now on the die, so there is no separate north bridge chip as in Intel Clovertown. Two channel (128 bit) memory interface SMT CPU Core 0 2 MB of 8 MB L3 Cache 2 MB of 8 MB L3 Cache 2 MB of 8 MB L3 Cache 0.5 MB L2 0.5 MB L2 0.5 MB L2 0.5 MB L2 North Bridge & Comunication. Switch Bridge to 2nd Die? Gen.I/O & fuses ↓QP0 ↑QP0 ↓QP1 ↑QP1 13.5 mm 2 MB of 8 MB L3 Cache SMT CPU Core 1 SMT CPU Core 2 SMT CPU Core 3 5.10 Real Stuff: the AMD Opteron X4 (Barcelona) and Intel Nehalem Memory Hierarchies In this section, we will look at the memory hierarchy in two modern microproces­sors: the AMD Opteron X4 (Barcelona) processor and the Intel Nehalem. Figure 5.37 shows the Intel Nehalem die photo, and Figure 1.9 in Chapter 1 shows the AMD Opteron X4 die photo. Both have secondary and tertiary caches on the main processor die. Such integration reduces access time to the lower-level caches and also reduces the number of pins on the chip, since there is no need for a bus to an external secondary cache. Both have on-chip memory controllers, which reduces the latency to main memory.
Hennesey_Page_537_Chunk537
540 Chapter 5 Large and Fast: Exploiting Memory Hierarchy The Memory Hierarchies of the Nehalem and Opteron Figure 5.38 summarizes the address sizes and TLBs of the two processors. Note that the AMD Opteron X4 (Barcelona) has four TLBs and that the virtual and physical addresses do not have to match the word size. The X4 implements only 48 of the potential 64 bits of its virtual space and 48 of the potential 64 bits of its physical address space. Nehalem has three TLBs, and the virtual address is 48 bits and the physical address is 44 bits. Characteristic Intel Nehalem AMD Opteron X4 (Barcelona) Virtual address 48 bits 48 bits Physical address 44 bits 48 bits Page size 4 KB, 2/4 MB 4 KB, 2/4 MB TLB organization 1 TLB for instructions and 1 TLB for data per core Both L1 TLBs are four-way set associative, LRU replacement The L2 TLB is four-way set associative, LRU replacement L1 I-TLB has 128 entries for small pages, 7 per thread for large pages L1 D-TLB has 64 entries for small pages, 32 for large pages The L2 TLB has 512 entries TLB misses handled in hardware 1 L1 TLB for instructions and 1 L1 TLB for data per core Both L1 TLBs fully associative, LRU replacement 1 L2 TLB for instructions and 1 L2 TLB for data per core Both L2 TLBs are four-way set associative, round-robin Both L1 TLBs have 48 entries Both L2 TLBs have 512 entries TLB misses handled in hardware FIGURE 5.38 Address translation and TLB hardware for the Intel Nehalem and AMD Opteron X4. The word size sets the maximum size of the virtual address, but a processor need not use all bits. Both processors provide support for large pages, which are used for things like the operating system or mapping a frame buffer. The large-page scheme avoids using a large number of entries to map a single object that is always present. Nehalem supports two hardware-supported threads per core (see Section 7.5 in Chapter 7). Figure 5.39 shows their caches. Each processor in the X4 has its own L1 64-KB instruction and data caches and its own 512-KB L2 cache. The four pro­cessors share a single 2-MB L3 cache. Nehalem has a similar structure, with each proces­sor having its own L1 32-KB instruction and data caches and its own 512-KB L2 cache, and the four processors share a single 8-MB L3 cache. Figure 5.40 shows the CPI, miss rates per thousand instructions for the L1 and L2 caches, and DRAM accesses per thousand instructions for Opteron X4 running the SPECint 2006 benchmarks. Note that the CPI and cache miss rates are highly correlated. The correlation coefficient of the set of CPIs and the set of L1 misses per 1000 instructions is 0.97. Although we don’t have the actual L3 misses, we can infer the effectiveness of L3 by the reduction in DRAM accesses versus L2 misses. While a few programs benefit significantly from the 2-MB L3 cache—h264avc, hmmer, and bzip2—most do not.
Hennesey_Page_538_Chunk538
Characteristic Intel Nehalem AMD Opteron X4 (Barcelona) L1 cache organization Split instruction and data caches Split instruction and data caches L1 cache size 32 KB each for instructions/data per core 64 KB each for instructions/data per core L1 cache associativity 4-way (I), 8-way (D) set associative 2-way set associative L1 replacement Approximated LRU replacement LRU replacement L1 block size 64 bytes 64 bytes L1 write policy Write-back, Write-allocate Write-back, Write-allocate L1 hit time (load-use) Not Available 3 clock cycles L2 cache organization Unified (instruction and data) per core Unified (instruction and data) per core L2 cache size 256 KB (0.25 MB) 512 KB (0.5 MB) L2 cache associativity 8-way set associative 16-way set associative L2 replacement Approximated LRU replacement Approximated LRU replacement L2 block size 64 bytes 64 bytes L2 write policy Write-back, Write-allocate Write-back, Write-allocate L2 hit time Not Available 9 clock cycles L3 cache organization Unified (instruction and data) Unified (instruction and data) L3 cache size 8192 KB (8 MB), shared 2048 KB (2 MB), shared L3 cache associativity 16-way set associative 32-way set associative L3 replacement Not Available Evict block shared by fewest cores L3 block size 64 bytes 64 bytes L3 write policy Write-back, Write-allocate Write-back, Write-allocate L3 hit time Not Available 38 (?)clock cycles FIGURE 5.39 First-level, second-level, and third-level caches in the Intel Nehalem and AMD Opteron X4 2356 (Barcelona). Techniques to Reduce Miss Penalties Both the Nehalem and the Opteron X4 have additional optimizations that allow them to reduce the miss penalty. The first of these is the return of the requested word first on a miss, as described in the Elaboration on page 473. Both allow the processor to continue to execute instructions that access the data cache during a cache miss. This ­technique, called a nonblocking cache, is commonly used by designers who are attempting to hide the cache miss latency by using out-of-order pro­cessors. They implement two flavors of nonblocking. Hit under miss allows addi­ tional cache hits during a miss, while miss under miss allows multiple outstanding cache misses. The aim of the first of these two is hiding some miss latency with other work, while the aim of the second is overlapping the latency of two different misses. Overlapping a large fraction of miss times for multiple outstanding misses requires a high-bandwidth memory system capable of handling multiple misses in parallel. In desktop systems, the memory may only be able to take limited advan­ tage of this capability, but large servers and multiprocessors often have memory systems capable of handling more than one outstanding miss in parallel. nonblocking cache A cache that allows the processor to make references to the cache while the cache is ­handling an earlier miss. 5.10 Real Stuff 541
Hennesey_Page_539_Chunk539
542 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Both microprocessors prefetch instructions and have a built-in hardware prefetch mechanism for data accesses. They look at a pattern of data misses and use this information to try to predict the next address to start fetching the data before the miss occurs. Such techniques generally work best when accessing arrays in loops. A significant challenge facing cache designers is to support processors like the Nehalem and Opteron X4, which can execute more than one memory instruction per clock cycle. Multiple requests can be supported in the first-level cache by two different techniques. The cache can be multiported, allowing more than one simul­ taneous access to the same cache block. Multiported caches, however, are often too expensive, since the RAM cells in a multiported memory must be much larger than single-ported cells. The alternative scheme is to break the cache into banks and allow multiple, independent accesses, provided the accesses are to different banks. The technique is similar to interleaved main memory (see Figure 5.11).The Opteron X4 L1 data cache supports two 128-bit reads per clock cycle and has eight banks. Nehalem and most other processors follow the policy of inclusion in their mem­ ory hierarchy. This means that a copy of all data in the higher level caches can also be found in the lower-level caches. In contrast, the AMD processors follow the policy of exclusion in their first- and second-level cache, meaning that a cache block can only be found in the first- or second-level caches, but not both. Hence, on an L1 miss when a block is fetched from L2 to L1, the block replaced is sent back to the L2 cache. FIGURE 5.40 CPI, miss rates, and DRAM accesses for the Opteron model X4 2356 (Barcelona) mem­ory hierarchy running SPECint2006. Alas, the L3 miss counters did not work on this chip, so we only have DRAM accesses to infer the effectiveness of the L3 cache. Note that this figure is for the same sys­tems and benchmarks as Figure 1.20 in Chapter 1. Name CPI L1 D cache misses/1000 instr L2 D cache misses/1000 instr DRAM accesses/1000 instr perl 0.75 3.5 1.1 1.3 bzip2 0.85 11.0 5.8 2.5 gcc 1.72 24.3 13.4 14.8 mcf 10.00 106.8 88.0 88.5 go 1.09 4.5 1.4 1.7 hmmer 0.80 4.4 2.5 0.6 sjeng 0.96 1.9 0.6 0.8 libquantum 1.61 33.0 33.1 47.7 h264avc 0.80 8.8 1.6 0.2 omnetpp 2.94 30.9 27.7 29.8 astar 1.79 16.3 9.2 8.2 xalancbmk 2.70 38.0 15.8 11.4 Median 1.35 13.6 7.5 5.4
Hennesey_Page_540_Chunk540
The sophisticated memory hierarchies of these chips and the large fraction of the dies dedicated to caches and TLBs show the significant design effort expended to try to close the gap between processor cycle times and memory latency. Elaboration: The shared L3 cache of Opteron X4 does not always follow exclu­sion. Since the data blocks can be shared between several processors in the L3 cache, it only removes the cache block from L3 if no other processors are sharing it. Hence, the L3 cache proto­col recognizes whether or not the cache block is being shared or only used by a single proces­sor. Elaboration: Just as Opteron X4 does not follow the conventional inclusion property, it also has a novel relationship between the levels of the memory hierarchy. Instead of the memory feeding the L2 cache that in turn feeds the L1 cache, the L2 cache only holds data that has been evicted from the L1 cache. Thus, the L2 cache can be called a victim cache, since it only holds blocks displaced from L1 (“victims”). Similarly, L3 cache is a victim cache for the L2 cache, only con­taining blocks that spill over from L2. If an L1 miss is not found in the L2 cache but found in the L3 cache, the L3 cache supplies the data directly to L1 cache. Hence, an L1 miss can be ser­viced by an L2 hit or an L3 hit or memory. 5.11 Fallacies and Pitfalls As one of the most naturally quantitative aspects of computer architecture, the memory hierarchy would seem to be less vulnerable to fallacies and pitfalls. Not only have there been many fallacies propagated and pitfalls encountered, but some have led to major negative outcomes. We start with a pitfall that often traps students in exercises and exams. Pitfall: Forgetting to account for byte addressing or the cache block size in simu­ lating a cache. When simulating a cache (by hand or by computer), we need to make sure we account for the effect of byte addressing and multiword blocks in determining into which cache block a given address maps. For example, if we have a 32-byte direct-mapped cache with a block size of 4 bytes, the byte address 36 maps into block 1 of the cache, since byte address 36 is block address 9 and (9 modulo 8) = 1. 5.11 Fallacies and Pitfalls 543
Hennesey_Page_541_Chunk541
544 Chapter 5 Large and Fast: Exploiting Memory Hierarchy On the other hand, if address 36 is a word address, then it maps into block (36 mod 8) = 4. Make sure the problem clearly states the base of the address. In like fashion, we must account for the block size. Suppose we have a cache with 256 bytes and a block size of 32 bytes. Into which block does the byte address 300 fall? If we break the address 300 into fields, we can see the answer: 31 30 29 . . . . . . . . . 11 10 9 8 7 6 5 4 3 2 1 0 0 0 0 . . . . . . . . . 0 0 0 1 0 0 1 0 1 1 0 0 Cache block number Block offset Block address Byte address 300 is block address ​ ​ 300  32 ​ ​ = 9 The number of blocks in the cache is ​ ​ 256  32 ​ ​ = 8 Block number 9 falls into cache block number (9 modulo 8) = 1. This mistake catches many people, including the authors (in earlier drafts) and instructors who forget whether they intended the addresses to be in words, bytes, or block numbers. Remember this pitfall when you tackle the exercises. Pitfall: Ignoring memory system behavior when writing programs or when gener­ ating code in a compiler. This could easily be written as a fallacy: “Programmers can ignore memory hierar­ chies in writing code.” We illustrate with an example using matrix multiply, to complement the sort comparison in Figure 5.18. Here is the inner loop of the version of matrix multiply from Chapter 3: for (i=0; i!=500; i=i+1) for (j=0; j!=500; j=j+1) for (k=0; k!=500; k=k+1) x[i][j] = x[i][j] + y[i][k] * z[k][j]; When run with inputs that are 500 × 500 double precision matrices, the CPU runtime of the above loop on a MIPS CPU with a 1-MB secondary cache was about half the speed compared to when the loop order is changed to k,j,i (so i is innermost)! The only difference is how the program accesses memory and the ensuing effect on the memory hierarchy. Further compiler optimizations, using a technique called blocking, can result in a runtime that is another four times faster for this code!
Hennesey_Page_542_Chunk542
Pitfall: Having less set associativity for a shared cache than the number of cores or threads sharing that cache. Without extra care, a parallel program running on 2n processors or threads can easily allocate data structures to addresses that would map to the same set of a shared L2 cache. If the cache is at least 2n-way associative, then these accidental conflicts are hidden by the hardware from the program. If not, programmers could face apparently mysterious performance bugs—actually due to L2 conflict misses—when migrating from, say, a 16-core design to 32-core design if both use 16-way associative L2 caches. Pitfall: Using average memory access time to evaluate the memory hierarchy of an out-of-order processor. If a processor stalls during a cache miss, then you can separately calculate the memory-stall time and the processor execution time, and hence evaluate the mem­ ory hierarchy independently using average memory access time (see page 478). If the processor continues to execute instructions, and may even sustain more cache misses during a cache miss, then the only accurate assessment of the mem­ ory hierarchy is to simulate the out-of-order processor along with the memory hierarchy. Pitfall: Extending an address space by adding segments on top of an unsegmented address space. During the 1970s, many programs grew so large that not all the code and data could be addressed with just a 16-bit address. Computers were then revised to offer 32-bit addresses, either through an unsegmented 32-bit address space (also called a flat address space) or by adding 16 bits of segment to the existing 16-bit address. From a marketing point of view, adding segments that were programmer- visible and that forced the programmer and compiler to decompose programs into segments could solve the addressing problem. Unfortunately, there is trouble any time a programming language wants an address that is larger than one segment, such as indices for large arrays, unrestricted pointers, or reference parameters. Moreover, adding segments can turn every address into two words—one for the segment number and one for the segment offset—causing problems in the use of addresses in registers. Pitfall: Implementing a virtual machine monitor on an instruction set architec­ture that wasn’t designed to be virtualizable. Many architects in the 1970s and 1980s weren’t careful to make sure that all instruc­ tions reading or writing information related to hardware resource information 5.11 Fallacies and Pitfalls 545
Hennesey_Page_543_Chunk543
546 Chapter 5 Large and Fast: Exploiting Memory Hierarchy were privileged. This laissez-faire attitude causes problems for VMMs for all of these architectures, including the x86, which we use here as an example. Figure 5.41 describes the 18 instructions that cause problems for virtualization [Robin and Irvine, 2000]. The two broad classes are instructions that ■ ■Read control registers in user mode that reveals that the guest operating sys­ tem is running in a virtual machine (such as POPF, mentioned earlier) ■ ■Check protection as required by the segmented architecture but assume that the operating system is running at the highest privilege level To simplify implementations of VMMs on the x86, both AMD and Intel have proposed extensions to the architecture via a new mode. Intel’s VT-x provides a new execution mode for running VMs, an architected definition of the VM state, instructions to swap VMs rapidly, and a large set of parameters to select the cir­cumstances where a VMM must be invoked. Altogether, VT-x adds 11 new instructions for the x86. AMD’s Pacifica makes similar proposals. An alternative to modifying the hardware is to make small modifications to the operating system to avoid using the troublesome pieces of the architecture. This Problem category Problem x86 instructions Access sensitive registers without trapping when running in user mode Store global descriptor table register (SGDT) Store local descriptor table register (SLDT) Store interrupt descriptor table register (SIDT) Store machine status word (SMSW) Push flags (PUSHF, PUSHFD) Pop flags (POPF, POPFD) When accessing virtual memory mechanisms in user mode, instructions fail the x86 protection checks Load access rights from segment descriptor (LAR) Load segment limit from segment descriptor (LSL) Verify if segment descriptor is readable (VERR) Verify if segment descriptor is writable (VERW) Pop to segment register (POP CS, POP SS, . . .) Push segment register (PUSH CS, PUSH SS, . . .) Far call to different privilege level (CALL) Far return to different privilege level (RET) Far jump to different privilege level (JMP) Software interrupt (INT) Store segment selector register (STR) Move to/from segment registers (MOVE) FIGURE 5.41 Summary of 18 x86 instructions that cause problems for virtualization [Robin and Irvine, 2000]. The first five instructions in the top group allow a program in user mode to read a control register, such as a descriptor table registers, without causing a trap. The pop flags instruction modifies a control register with sensitive information but fails silently when in user mode. The protection checking of the segmented architecture of the x86 is the downfall of the bottom group, as each of these instructions checks the privilege level implicitly as part of instruction execution when reading a control reg­ister. The checking assumes that the OS must be at the highest privilege level, which is not the case for guest VMs. Only the Move to segment register tries to modify control state, and protection checking foils it as well.
Hennesey_Page_544_Chunk544
technique is called paravirtualization, and the open source Xen VMM is a good example. The Xen VMM provides a guest OS with a virtual machine abstraction that uses only the easy-to-virtualize parts of the physical x86 hardware on which the VMM runs. 5.12 Concluding Remarks The difficulty of building a memory system to keep pace with faster processors is underscored by the fact that the raw material for main memory, DRAMs, is essen­ tially the same in the fastest computers as it is in the slowest and cheapest. It is the principle of locality that gives us a chance to overcome the long latency of memory access—and the soundness of this strategy is demonstrated at all levels of the memory hierarchy. Although these levels of the hierarchy look quite differ­ent in quantitative terms, they follow similar strategies in their opera­ tion and exploit the same properties of locality. Multilevel caches make it possible to use more cache optimizations more easily for two reasons. First, the design parameters of a lower-level cache are different from a first-level cache. For example, because a lower-level cache will be much larger, it is possible to use larger block sizes. Second, a lower-level cache is not constantly being used by the processor, as a first-level cache is. This allows us to consider having the lower-level cache do something when it is idle that may be useful in preventing future misses. Another trend is to seek software help. Efficiently managing the memory hier­ archy using a variety of program transformations and hardware facilities is a major focus of compiler enhancements. Two different ideas are being explored. One idea is to reorganize the program to enhance its spatial and temporal locality. This approach focuses on loop-oriented programs that use large arrays as the major data structure; large linear algebra problems are a typical example. By restructuring the loops that access the arrays, substantially improved locality—and, therefore, cache performance—can be obtained. The discussion on page 544 showed how effective even a simple change of loop structure could be. Another approach is prefetching. In prefetching, a block of data is brought into the cache before it is actually referenced. Many microprocessors use hardware prefetching to try to predict accesses that may be difficult for software to notice. A third approach is special cache-aware instructions that optimize memory transfer. For example, the microprocessors in Section 7.10 in Chapter 7 use an optimization that does not fetch the contents of a block from memory on a write miss because the program is going to write the full block. This optimization significantly reduces memory traffic for one kernel. prefetching A technique in which data blocks needed in the future are brought into the cache early by the use of special instructions that specify the address of the block. 5.12 Concluding Remarks 547
Hennesey_Page_545_Chunk545
548 Chapter 5 Large and Fast: Exploiting Memory Hierarchy As we will see in Chapter 7, memory systems are a central design issue for parallel processors. The growing importance of the memory hierarchy in determining system performance means that this important area will continue to be a focus of both designers and researchers for some years to come. Historical Perspective and Further Reading This history section gives an overview of memory technologies, from mercury delay lines to DRAM, the invention of the memory hierarchy, protection mech­ anisms, and virtual machines, and concludes with a brief history of operating ­systems, including CTSS, MULTICS, UNIX, BSD UNIX, MS-DOS, Windows, and Linux. 5.14 Exercises Contributed by Jichuan Chang, Jacob Leverich, Kevin Lim, and Parthasarathy Ranganathan (all of Hewlett-Packard) Exercise 5.1 In this exercise we consider memory hierarchies for various applications, listed in the following table. a. Software version control b. Making phone calls 5.1.1 [10] <5.1> Assuming both client and server are involved in the process, first name the client and server systems. Where can caches be placed to speed up the process? 5.1.2 [10] <5.1> Design a memory hierarchy for the system. Show the typical size and latency at various levels of the hierarchy. What is the relationship between cache size and its access latency? 5.1.3 [15] <5.1> What are the units of data transfers between hierarchies? What is the relationship between the data location, data size, and transfer latency? 5.13
Hennesey_Page_546_Chunk546
5.1.4 [10] <5.1, 5.2> Communication bandwidth and server processing band­ width are two important factors to consider when designing a memory hierarchy. How can the bandwidths be improved? What is the cost of improving them? 5.1.5 [5] <5.1, 5.8> Now consider multiple clients simultaneously accessing the server. Will such scenarios improve the spatial and temporal locality? 5.1.6 [10] <5.1, 5.8> Give an example of where the cache can provide out-of-date data. How should the cache be designed to mitigate or avoid such issues? Exercise 5.2 In this exercise we look at memory locality properties of matrix computation. The following code is written in C, where elements within the same row are stored contiguously. a. for (I=0; I<8; I++) for (J=0; J<8000; J++) A[I][J]=B[I][0]+A[J][I]; b. for (J=0; J<8000; J++) for (I=0; I<8; I++) A[I][J]=B[I][0]+A[J][I]; 5.2.1 [5] <5.1> How many 32-bit integers can be stored in a 16-byte cache line? 5.2.2 [5] <5.1> References to which variables exhibit temporal locality? 5.2.3 [5] <5.1> References to which variables exhibit spatial locality? Locality is affected by both the reference order and data layout. The same compu­ tation can also be written below in Matlab, which differs from C by contiguously storing matrix elements within the same column. a. for I=1:8 for J=1:8000 A(I,J)=B(I,0)+A(J,I); end end b. for J=1:8000 for I=1:8 A(I,J)=B(I,0)+A(J,I); end end 5.14 Exercises 549
Hennesey_Page_547_Chunk547
550 Chapter 5 Large and Fast: Exploiting Memory Hierarchy 5.2.4 [10] <5.1> How many 16-byte cache lines are needed to store all 32-bit matrix elements being referenced? 5.2.5 [5] <5.1> References to which variables exhibit temporal locality? 5.2.6 [5] <5.1> References to which variables exhibit spatial locality? Exercise 5.3 Caches are important to providing a high-performance memory hierarchy to pro­ cessors. Below is a list of 32-bit memory address references, given as word addresses. a. 3, 180, 43, 2, 191, 88, 190, 14, 181, 44, 186, 253 b. 21, 166, 201, 143, 61, 166, 62, 133, 111, 143, 144, 61 5.3.1 [10] <5.2> For each of these references, identify the binary address, the tag, and the index given a direct-mapped cache with 16 one-word blocks. Also list if each reference is a hit or a miss, assuming the cache is initially empty. 5.3.2 [10] <5.2> For each of these references, identify the binary address, the tag, and the index given a direct-mapped cache with two-word blocks and a total size of 8 blocks. Also list if each reference is a hit or a miss, assuming the cache is initially empty. 5.3.3 [20] <5.2, 5.3> You are asked to optimize a cache design for the given references. There are three direct-mapped cache designs possible, all with a total of 8 words of data: C1 has 1-word blocks, C2 has 2-word blocks, and C3 has 4-word blocks. In terms of miss rate, which cache design is the best? If the miss stall time is 25 cycles, and C1 has an access time of 2 cycles, C2 takes 3 cycles, and C3 takes 5 cycles, which is the best cache design? There are many different design parameters that are important to a cache’s overall performance. The table below lists parameters for different direct-mapped cache designs. Cache Data Size Cache Block Size Cache Access Time a. 32 KB 2 words 1 cycle b. 32 KB 4 words 2 cycle 5.3.4 [15] <5.2> Calculate the total number of bits required for the cache listed in the table, assuming a 32-bit address. Given that total size, find the total size
Hennesey_Page_548_Chunk548
of the closest direct-mapped cache with 16-word blocks of equal size or greater. Explain why the second cache, despite its larger data size, might provide slower performance than the first cache. 5.3.5 [20] <5.2, 5.3> Generate a series of read requests that have a lower miss rate on a 2 KB 2-way set associative cache than the cache listed in the table. Iden­ tify one possible solution that would make the cache listed in the table have an equal or lower miss rate than the 2 KB cache. Discuss the advantages and disadvantages of such a solution. 5.3.6 [15] <5.2> The formula shown on page 457 shows the typical method to index a direct-mapped cache, specifically (Block address) modulo (Number of blocks in the cache). Assuming a 32-bit address and 1024 blocks in the cache, consider a different indexing function, specifically (Block address[31:27] XOR Block address[26:22]). Is it possible to use this to index a direct-mapped cache? If so, explain why and discuss any changes that might need to be made to the cache. If it is not possible, explain why. Exercise 5.4 For a direct-mapped cache design with a 32-bit address, the following bits of the address are used to access the cache. Tag Index Offset a. 31–10 9–5 4–0 b. 31–12 11–6 5–0 5.4.1 [5] <5.2> What is the cache line size (in words)? 5.4.2 [5] <5.2> How many entries does the cache have? 5.4.3 [5] <5.2> What is the ratio between total bits required for such a cache implementation over the data storage bits? Starting from power on, the following byte-addressed cache references are recorded. Address 0 4 16 132 232 160 1024 30 140 3100 180 2180 5.4.4 [10] <5.2> How many blocks are replaced? 5.4.5 [10] <5.2> What is the hit ratio? 5.14 Exercises 551
Hennesey_Page_549_Chunk549
552 Chapter 5 Large and Fast: Exploiting Memory Hierarchy 5.4.6 [20] <5.2> List the final state of the cache, with each valid entry represented as a record of <index, tag, data>. Exercise 5.5 Recall that we have two write policies and write allocation policies, and their com­ binations can be implemented either in L1 or L2 cache. L1 L2 a. Write through, non-write allocate Write back, write allocate b. Write through, write allocate Write back, write allocate 5.5.1 [5] <5.2, 5.5> Buffers are employed between different levels of memory hierarchy to reduce access latency. For this given configuration, list the possible buffers needed between L1 and L2 caches, as well as L2 cache and memory. 5.5.2 [20] <5.2, 5.5> Describe the procedure of handling an L1 write-miss, considering the component involved and the possibility of replacing a dirty block. 5.5.3 [20] <5.2, 5.5> For a multilevel exclusive cache (a block can only reside in one of the L1 and L2 caches), configuration, describe the procedure of handling an L1 write-miss, considering the component involved and the possibility of replacing a dirty block. Consider the following program and cache behaviors. Data Reads per 1000 Instructions Data Writes per 1000 Instructions Instruction Cache Miss Rate Data Cache Miss Rate Block Size (byte) a. 250 100 0.30% 2% 64 b. 200 100 0.30% 2% 64 5.5.4 [5] <5.2, 5.5> For a write-through, write-allocate cache, what are the minimum read and write bandwidths (measured by byte per cycle) needed to achieve a CPI of 2? 5.5.5 [5] <5.2, 5.5> For a write-back, write-allocate cache, assuming 30% of replaced data cache blocks are dirty, what are the minimal read and write bandwidths needed for a CPI of 2? 5.5.6 [5] <5.2, 5.5> What are the minimal bandwidths needed to achieve the performance of CPI=1.5?
Hennesey_Page_550_Chunk550
Exercise 5.6 Media applications that play audio or video files are part of a class of workloads called “streaming” workloads; i.e., they bring in large amounts of data but do not reuse much of it. Consider a video streaming workload that accesses a 512 KB working set sequentially with the following address stream: 0, 2, 4, 6, 8, 10, 12, 14, 16, … 5.6.1 [5] <5.5, 5.3> Assume a 64 KB direct-mapped cache with a 32-byte line. What is the miss rate for the address stream above? How is this miss rate sensitive to the size of the cache or the working set? How would you categorize the misses this workload is experiencing, based on the 3C model? 5.6.2 [5] <5.5, 5.1> Re-compute the miss rate when the cache line size is 16 bytes, 64 bytes, and 128 bytes. What kind of locality is this workload exploiting? 5.6.3 [10] <5.10> “Prefetching” is a technique that leverages predictable address patterns to speculatively bring in additional cache lines when a particular cache line is accessed. One example of prefetching is a stream buffer that prefetches sequentially adjacent cache lines into a separate buffer when a particular cache line is brought in. If the data is found in the prefetch buffer, it is considered as a hit and moved into the cache and the next cache line is prefetched. Assume a two-entry stream buffer and assume that the cache latency is such that a cache line can be loaded before the computation on the previous cache line is completed. What is the miss rate for the address stream above? Cache block size (B) can affect both miss rate and miss latency. Assuming a 1-CPI machine with an average of 1.35 references (both instruction and data) per instruction, help find the optimal block size given the following miss rates for vari­ ous block sizes. 8 16 32 64 128 a. 4% 3% 2% 1.5% 1% b. 8% 7% 6% 5% 4% 5.6.4 [10] <5.2> What is the optimal block size for a miss latency of 20×B cycles? 5.6.5 [10] <5.2> What is the optimal block size for a miss latency of 24+B cycles? 5.6.6 [10] <5.2> For constant miss latency, what is the optimal block size? 5.14 Exercises 553
Hennesey_Page_551_Chunk551
554 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Exercise 5.7 In this exercise, we will look at the different ways capacity affects overall perfor­ mance. In general, cache access time is proportional to capacity. Assume that main memory accesses take 70 ns and that memory accesses are 36% of all instructions. The following table shows data for L1 caches attached to each of two processors, P1 and P2. L1 Size L1 Miss Rate L1 Hit Time a. P1 2 KB 8.0% 0.66 ns P2 4 KB 6.0% 0.90 ns b. P1 16 KB 3.4% 1.08 ns P2 32 KB 2.9% 2.02 ns 5.7.1 [5] <5.3> Assuming that the L1 hit time determines the cycle times for P1 and P2, what are their respective clock rates? 5.7.2 [5] <5.3> What is the AMAT for P1 and P2? 5.7.3 [5] <5.3> Assuming a base CPI of 1.0 without any memory stalls, what is the total CPI for P1 and P2? Which processor is faster? For the next three problems, we will consider the addition of an L2 cache to P1 to presumably make up for its limited L1 cache capacity. Use the L1 cache capacities and hit times from the previous table when solving these problems. The L2 miss rate indicated is its local miss rate. L2 Size L2 Miss Rate L2 Hit Time a. 1 MB 95% 5.62 ns b. 8 MB 68% 23.52 ns 5.7.4 [10] <5.3> What is the AMAT for P1 with the addition of an L2 cache? Is the AMAT better or worse with the L2 cache? 5.7.5 [5] <5.3> Assuming a base CPI of 1.0 without any memory stalls, what is the total CPI for P1 with the addition of an L2 cache? 5.7.6 [10] <5.3> Which processor is faster, now that P1 has an L2 cache? If P1 is faster, what miss rate would P2 need in its L1 cache to match P1’s performance? If P2 is faster, what miss rate would P1 need in its L1 cache to match P2’s performance?
Hennesey_Page_552_Chunk552
Exercise 5.8 This exercise examines the impact of different cache designs, specifically compar­ ing associative caches to the direct-mapped caches from Section 5.2. For these exercises, refer to the table of address streams shown in Exercise 5.3. 5.8.1 [10] <5.3> Using the references from Exercise 5.3, show the final cache contents for a three-way set associative cache with two-word blocks and a total size of 24 words. Use LRU replacement. For each reference identify the index bits, the tag bits, the block offset bits, and if it is a hit or a miss. 5.8.2 [10] <5.3> Using the references from Exercise 5.3, show the final cache contents for a fully associative cache with one-word blocks and a total size of 8 words. Use LRU replacement. For each reference identify the index bits, the tag bits, and if it is a hit or a miss. 5.8.3 [15] <5.3> Using the references from Exercise 5.3, what is the miss rate for a fully associative cache with two-word blocks and a total size of 8 words, using LRU replacement? What is the miss rate using MRU (most recently used) replacement? Finally what is the best possible miss rate for this cache, given any replacement policy? Multilevel caching is an important technique to overcome the limited amount of space that a first level cache can provide while still maintaining its speed. Consider a processor with the following parameters: Base CPI, No Memory Stalls Processor Speed Main Memory Access Time First Level Cache Miss Rate per Instruction Second Level Cache, Direct-Mapped Speed Global Miss Rate with Second Level Cache, Direct-Mapped Second Level Cache, Eight-Way Set Associative Speed Global Miss Rate with Second Level Cache, Eight-Way Set Associative a. 1.5 2 GHz 100 ns 7% 12 cycles 3.5% 28 cycles 1.5% b. 1.0 2 GHz 150 ns 3% 15 cycles 5.0% 20 cycles 2.0% 5.8.4 [10] <5.3> Calculate the CPI for the processor in the table using: 1) only a first level cache, 2) a second level direct-mapped cache, and 3) a second level eight- way set associative cache. How do these numbers change if main memory access time is doubled? If it is cut in half? 5.14 Exercises 555
Hennesey_Page_553_Chunk553
556 Chapter 5 Large and Fast: Exploiting Memory Hierarchy 5.8.5 [10] <5.3> It is possible to have an even greater cache hierarchy than two levels. Given the processor above with a second level, direct-mapped cache, a designer wants to add a third level cache that takes 50 cycles to access and will reduce the global miss rate to 1.3%. Would this provide better performance? In general, what are the advantages and disadvantages of adding a third level cache? 5.8.6 [20] <5.3> In older processors such as the Intel Pentium or Alpha 21264, the second level of cache was external (located on a different chip) from the main processor and the first level cache. While this allowed for large second level caches, the latency to access the cache was much higher, and the bandwidth was typically lower because the second level cache ran at a lower frequency. Assume a 512 KB off- chip second level cache has a global miss rate of 4%. If each additional 512 KB of cache lowered global miss rates by 0.7%, and the cache had a total access time of 50 cycles, how big would the cache have to be to match the performance of the second level direct-mapped cache listed in the table? Of the eight-way set associative cache? Exercise 5.9 For a high-performance system such as a B-tree index for a database, the page size is determined mainly by the data size and disk performance. Assume that on aver­ age a B-tree index page is 70% full with fix-sized entries. The utility of a page is its B-tree depth, calculated as log2(entries). The following table shows that for 16-byte entries, and a 10-year-old disk with a 10 ms latency and 10 MB/s transfer rate, the optimal page size is 16K. Page Size (KB) Page Utility or B-Tree Depth (Number of Disk Accesses Saved) Index Page Access Cost (ms) Utility/Cost 2 6.49 (or log2(2048/16×0.7)) 10.2 0.64 4 7.49 10.4 0.72 8 8.49 10.8 0.79 16 9.49 11.6 0.82 32 10.49 13.2 0.79 64 11.49 16.4 0.70 128 12.49 22.8 0.55 256 13.49 35.6 0.38 5.9.1 [10] <5.4> What is the best page size if entries now become 128 bytes? 5.9.2 [10] <5.4> Based on 5.9.1, what is the best page size if pages are half full? 5.9.3 [20] <5.4> Based on 5.9.2, what is the best page size if using a modern disk with a 3 ms latency and 100 MB/s transfer rate? Explain why future servers are likely to have larger pages.
Hennesey_Page_554_Chunk554
Keeping “frequently used” (or “hot”) pages in DRAM can save disk accesses, but how do we determine the exact meaning of “frequently used” for a given system? Data engineers use the cost ratio between DRAM and disk access to quantify the reuse time threshold for hot pages. The cost of a disk access is $Disk /accesses_per_ sec, while the cost to keep a page in DRAM is $DRAM_MB/page_size. The typical DRAM and disk costs and typical database page sizes at several time points are listed below: Year DRAM Cost ($/MB) Page Size (KB) Disk Cost ($/disk) Disk Access Rate (access/sec) 1987 5000 1 15000 15 1997 15 8 2000 64 2007 0.05 64 80 83 5.9.4 [10] <5.1, 5.4> What are the reuse time thresholds for these three technology generations? 5.9.5 [10] <5.4> What are the reuse time thresholds if we keep using the same 4K page size? What’s the trend here? 5.9.6 [20] <5.4> What other factors can be changed to keep using the same page size (thus avoiding software rewrite)? Discuss their likeliness with current technology and cost trends. Exercise 5.10 As described in Section 5.4, virtual memory uses a page table to track the mapping of virtual addresses to physical addresses. This exercise shows how this table must be updated as addresses are accessed. The following table is a stream of virtual ad­ dresses as seen on a system. Assume 4 KB pages, a 4-entry fully associative TLB, and true LRU replacement. If pages must be brought in from disk, increment the next largest page number. a. 4669, 2227, 13916, 34587, 48870, 12608, 49225 b. 12948, 49419, 46814, 13975, 40004, 12707, 52236 TLB Valid Tag Physical Page Number 1 11 12 1 7 4 1 3 6 0 4 9 5.14 Exercises 557
Hennesey_Page_555_Chunk555
558 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Page table Valid Physical Page or in Disk 1 5 0 Disk 0 Disk 1 6 1 9 1 11 0 Disk 1 4 0 Disk 0 Disk 1 3 1 12 5.10.1 [10] <5.4> Given the address stream in the table, and the initial TLB and page table states shown above, show the final state of the system. Also list for each reference if it is a hit in the TLB, a hit in the page table, or a page fault. 5.10.2 [15] <5.4> Repeat Exercise 5.10.1, but this time use 16 KB pages instead of 4 KB pages. What would be some of the advantages of having a larger page size? What are some of the disadvantages? 5.10.3 [15] <5.3, 5.4> Show the final contents of the TLB if it is 2-way set associative. Also show the contents of the TLB if it is direct mapped. Discuss the importance of having a TLB to high performance. How would virtual memory accesses be handled if there were no TLB? There are several parameters that impact the overall size of the page table. Listed below are several key page table parameters. Virtual Address Size Page Size Page Table Entry Size a. 32 bits 8 KB 4 bytes b. 64 bits 8 KB 6 bytes 5.10.4 [5] <5.4> Given the parameters in the table above, calculate the total page table size for a system running 5 applications that utilize half of the memory available.
Hennesey_Page_556_Chunk556
5.10.5 [10] <5.4> Given the parameters in the table above, calculate the total page table size for a system running 5 applications that utilize half of the memory available, given a two level page table approach with 256 entries. Assume each entry of the main page table is 6 bytes. Calculate the minimum and maximum amount of memory required. 5.10.6 [10] <5.4> A cache designer wants to increase the size of a 4 KB virtually indexed, physically tagged cache. Given the page size listed in the table above, is it possible to make a 16 KB direct-mapped cache, assuming 2 words per block? How would the designer increase the data size of the cache? Exercise 5.11 In this exercise, we will examine space/time optimizations for page tables. The fol­ lowing table shows parameters of a virtual memory system. Virtual Address (bits) Physical DRAM Installed Page Size PTE Size (byte) a. 43 16 GB 4 KB 4 b. 38 8 GB 16 KB 4 5.11.1 [10] <5.4> For a single-level page table, how many page table entries (PTEs) are needed? How much physical memory is needed for storing the page table? 5.11.2 [10] <5.4> Using a multilevel page table can reduce the physical memory consumption of page tables, by only keeping active PTEs in physical memory. How many levels of page tables will be needed in this case? And how many memory references are needed for address translation if missing in TLB? 5.11.3 [15] <5.4> An inverted page table can be used to further optimize space and time. How many PTEs are needed to store the page table? Assuming a hash table implementation, what are the common case and worst case numbers of memory references needed for servicing a TLB miss? The following table shows the contents of a 4-entry TLB. Entry-ID Valid VA Page Modified Protection PA Page 1 1 140 1 RW 30 2 0 40 0 RX 34 3 1 200 1 RO 32 4 1 280 0 RW 31 5.14 Exercises 559
Hennesey_Page_557_Chunk557
560 Chapter 5 Large and Fast: Exploiting Memory Hierarchy 5.11.4 [5] <5.4> Under what scenarios would entry 2’s valid bit be set to zero? 5.11.5 [5] <5.4> What happens when an instruction writes to VA page 30? When would a software managed TLB be faster than a hardware managed TLB? 5.11.6 [5] <5.4> What happens when an instruction writes to VA page 200? Exercise 5.12 In this exercise, we will examine how replacement policies impact miss rate. ­Assume a 2-way set associative cache with 4 blocks. You may find it helpful to draw a table like those found on page 482 to solve the problems in this exercise, as demonstrated below on the address sequence “0, 1, 2, 3, 4.” Address of Memory Block Accessed Hit or Miss Evicted Block Contents of Cache Blocks after Reference Set 0 Set 0 Set 1 Set 1 0 Miss Mem[0] 1 Miss Mem[0] Mem[1] 2 Miss Mem[0] Mem[2] Mem[1] 3 Miss Mem[0] Mem[2] Mem[1] Mem[3] 4 Miss 0 Mem[4] Mem[2] Mem[1] Mem[3] … The following table shows address sequences. Address Sequence a. 0, 2, 4, 8, 10, 12, 14, 16, 0 b. 1, 3, 5, 1, 3, 1, 3, 5, 3 5.12.1 [5] <5.3, 5.5> Assuming an LRU replacement policy, how many hits does this address sequence exhibit? 5.12.2 [5] <5.3, 5.5> Assuming an MRU (most recently used) replacement policy, how many hits does this address sequence exhibit? 5.12.3 [5] <5.3, 5.5> Simulate a random replacement policy by flipping a coin. For example, “heads” means to evict the first block in a set and “tails” means to evict the second block in a set. How many hits does this address sequence exhibit?
Hennesey_Page_558_Chunk558
5.12.4 [10] <5.3, 5.5> Which address should be evicted at each replacement to maximize the number of hits? How many hits does this address sequence exhibit if you follow this “optimal” policy? 5.12.5 [10] <5.3, 5.5> Describe why it is difficult to implement a cache replacement policy that is optimal for all address sequences. 5.12.6 [10] <5.3, 5.5> Assume you could make a decision upon each memory reference whether or not you want the requested address to be cached. What impact could this have on miss rate? Exercise 5.13 To support multiple virtual machines, two levels of memory virtualization are need­ ed. Each virtual machine still controls the mapping of virtual address (VA) to physi­ cal address (PA), while the hypervisor maps the physical address (PA) of each virtual machine to the actual machine address (MA). To accelerate such mappings, a soft­ ware approach called “shadow paging” duplicates each virtual machine’s page tables in the hypervisor, and intercepts VA to PA mapping changes to keep both copies consistent. To remove the complexity of shadow page tables, a hardware approach called nested page table (or extended page table) explicitly supports two classes of page tables (VA⇨PA and PA⇨MA) and can walk such tables purely in hardware. Consider the following sequence of operations: (1) Create process; (2) TLB miss; (3) page fault; (4) context switch; 5.13.1 [10] <5.4, 5.6> What would happen for the given operation sequence for shadow page table and nested page table, respectively? 5.13.2 [10] <5.4, 5.6> Assuming an x86-based 4-level page table in both guest and nested page table, how many memory references are needed to service a TLB miss for native vs. nested page table? 5.13.3 [15] <5.4, 5.6> Among TLB miss rate, TLB miss latency, page fault rate, and page fault handler latency, which metrics are more important for shadow page table? Which are important for nested page table? The following table shows parameters for a shadow paging system. TLB Misses per 1000 Instructions NPT TLB Miss Latency Page Faults per 1000 Instructions Shadowing Page Fault Overhead 0.2 200 cycles 0.001 30,000 cycles 5.14 Exercises 561
Hennesey_Page_559_Chunk559
562 Chapter 5 Large and Fast: Exploiting Memory Hierarchy 5.13.4 [10] <5.6> For a benchmark with native execution CPI of 1, what are the CPI numbers if using shadow page tables vs. NPT (assuming only page table virtualization overhead)? 5.13.5 [10] <5.6> What techniques can be used to reduce page table shadowing induced overhead? 5.13.6 [10] <5.6> What techniques can be used to reduce NPT induced overhead? Exercise 5.14 One of the biggest impediments to widespread use of virtual machines is the per­ formance overhead incurred by running a virtual machine. The table below lists various performance parameters and application behavior. Base CPI Priviliged O/S Accesses per 10,000 Instructions Performance Impact to Trap to the Guest O/S Performance Impact to Trap to VMM I/O Accesses per 10,000 Instructions I/O Access Time (Includes Time to Trap to Guest O/S) a. 1.5 120 15 cycles 175 cycles 30 1100 cycles b. 1.75 90 20 cycles 140 cycles 25 1200 cycles 5.14.1 [10] <5.6> Calculate the CPI for the system listed above assuming that there are no accesses to I/O. What is the CPI if the VMM performance impact doubles? If it is cut in half? If a virtual machine software company wishes to obtain a 10% performance degradation, what is the longest possible penalty to trap to the VMM? 5.14.2 [10] <5.6> I/O accesses often have a large impact on overall system performance. Calculate the CPI of a machine using the performance characteristics above, assuming a non-virtualized system. Calculate the CPI again, this time using a virtualized system. How do these CPIs change if the system has half the I/O accesses? Explain why I/O bound applications have a smaller impact from virtualization. 5.14.3 [30] <5.4, 5.6> Compare and contrast the ideas of virtual memory and virtual machines. How do the goals of each compare? What are the pros and cons of each? List a few cases where virtual memory is desired, and a few cases where virtual machines are desired.
Hennesey_Page_560_Chunk560
5.14.4 [20] <5.6> Section 5.6 discusses virtualization under the assumption that the virtualized system is running the same ISA as the underlying hardware. However, one possible use of virtualization is to emulate non-native ISAs. An example of this is QEMU, which emulates a variety of ISAs such as MIPS, SPARC, and PowerPC. What are some of the difficulties involved in this kind of virtualization? Is it possible for an emulated system to run faster than on its native ISA? Exercise 5.15 In this exercise, we will explore the control unit for a cache controller for a pro­ cessor with a write buffer. Use the finite state machine found in Figure 5.34 as a starting point for designing your own finite state machines. Assume that the cache controller is for the simple direct-mapped cache described on page 529, but you will add a write buffer with a capacity of one block. Recall that the purpose of a write buffer is to serve as temporary storage so that the processor doesn’t have to wait for two memory accesses on a dirty miss. Rather than writing back the dirty block before reading the new block, it buffers the dirty block and immediately begins reading the new block. The dirty block can then be written to main memory while the processor is working. 5.15.1 [10] <5.5, 5.7> What should happen if the processor issues a request that hits in the cache while a block is being written back to main memory from the write buffer? 5.15.2 [10] <5.5, 5.7> What should happen if the processor issues a request that misses in the cache while a block is being written back to main memory from the write buffer? 5.15.3 [30] <5.5, 5.7> Design a finite state machine to enable the use of a write buffer. Exercise 5.16 Cache coherence concerns the views of multiple processors on a given cache block. The following table shows two processors and their read/write operations on two different words of a cache block X (initially X[0] = X[1] = 0). P1 P2 a. X[0] ++; X[1] = 3; X[0] = 5; X[1] +=2; b. X[0] =10; X[1] = 3; X[0] = 5; X[1] +=2; 5.14 Exercises 563
Hennesey_Page_561_Chunk561
564 Chapter 5 Large and Fast: Exploiting Memory Hierarchy 5.16.1 [15] <5.8> List the possible values of the given cache block for a correct cache coherence protocol implementation. List at least one more possible value of the block if the protocol doesn’t ensure cache coherency. 5.16.2 [15] <5.8> For a snooping protocol, list a valid operation sequence on each processor/cache to finish the above read/write operations. 5.16.3 [10] <5.8> What are the best-case and worst-case numbers of cache misses needed to execute the listed read/write instructions? Memory consistency concerns the views of multiple data items. The following ta­ ble shows two processors and their read/write operations on different cache blocks (A and B initially 0). P1 P2 a. A = 1; B = 2; A+=2; B++; C = B; D = A; b. A = 1; B = 2; A=5; B++; C = B; D = A; 5.16.4 [15] <5.8> List the possible values of C and D for an implementation that ensures both consistency assumptions on page 538. 5.16.5 [15] <5.8> List at least one more possible pair of values for C and D if such assumptions are not maintained. 5.16.6 [15] <5.2, 5.8> For various combinations of write policies and write allocation policies, which combinations make the protocol implementation simpler? Exercise 5.17 Both Barcelona and Nehalem are chip multiprocessors (CMPs), having multiple cores and their caches on a single chip. CMP on-chip L2 cache design has interest­ ing trade-offs. The following table shows the miss rates and hit latencies for two benchmarks with private vs. shared L2 cache designs. Assume L1 cache misses once every 32 instructions. Private Shared Benchmark A misses-per-instruction 0.30% 0.12% Benchmark B misses-per-instruction 0.06% 0.03%
Hennesey_Page_562_Chunk562
The next table shows hit latencies. Private Cache Shared Cache Memory a. 5 20 180 b. 10 50 120 5.17.1 [15] <5.10> Which cache design is better for each of these benchmarks? Use data to support your conclusion. 5.17.2 [15] <5.10> Shared cache latency increases with the CMP size. Choose the best design if the shared cache latency doubles. Off-chip bandwidth becomes the bottleneck as the number of CMP cores increases. Choose the best design if off- chip memory latency doubles. 5.17.3 [10] <5.10> Discuss the pros and cons of shared vs. private L2 caches for both single-threaded, multi-threaded, and multiprogrammed workloads, and reconsider them if having on-chip L3 caches. 5.17.4 [15] <5.10> Assume both benchmarks have a base CPI of 1 (ideal L2 cache). If having non-blocking cache improves the average number of concurrent L2 misses from 1 to 2, how much performance improvement does this provide over a shared L2 cache? How much improvement can be achieved over private L2? 5.17.5 [10] <5.10> Assume new generations of processors double the number of cores every 18 months. To maintain the same level of per-core performance, how much more off-chip memory bandwidth is needed for a 2012 processor? 5.17.6 [15] <5.10> Consider the entire memory hierarchy. What kinds of optimizations can improve the number of concurrent misses? Exercise 5.18 In this exercise we show the definition of a web server log and examine code opti­ mizations to improve log processing speed. The data structure for the log is defined as follows: struct entry { int srcIP; // remote IP address char URL[128]; // request URL (e.g., “GET index.html”) long long refTime; // reference time int status; // connection status char browser[64]; // client browser name } log [NUM_ENTRIES]; 5.14 Exercises 565
Hennesey_Page_563_Chunk563
566 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Some processing functions on a log are: a. topK_sourceIP (int hour); b. browser_histogram (int srcIP); // browsers of a given IP 5.18.1 [5] <5.11> Which fields in a log entry will be accessed for the given log processing function? Assuming 64-byte cache blocks and no prefetching, how many cache misses per entry does the given function incur on average? 5.18.2 [10] <5.11> How can you reorganize the data structure to improve cache utilization and access locality? Show your structure definition code. 5.18.3 [10] <5.11> Give an example of another log processing function that would prefer a different data structure layout. If both functions are important, how would you rewrite the program to improve the overall performance? Supplement the discussion with code snippet and data. For the problems below, use data from “Cache Performance for SPEC CPU2000 Benchmarks” (http://www.cs.wisc.edu/multifacet/misc/spec2000cache-data/) for the pairs of benchmarks shown in the following table. a. Mesa / gcc b. mcf / swim 5.18.4 [10] <5.11> For 64 KB data caches with varying set associativities, what are the miss rates broken down by miss types (cold, capacity, and conflict misses) for each benchmark? 5.18.5 [10] <5.11> Select the set associativity to be used by a 64 KB L1 data cache shared by both benchmarks. If the L1 cache has to be directly mapped, select the set associativity for the 1 MB L2 cache. 5.18.6 [20] <5.11> Give an example in the miss rate table where higher set associativity actually increases miss rate. Construct a cache configuration and reference stream to demonstrate this.
Hennesey_Page_564_Chunk564
§5.1, page 457: 1 and 4. (3 is false because the cost of the memory hierarchy varies per computer, but in 2008 the highest cost is usually the DRAM.) §5.2, page 475: 1 and 4: A lower miss penalty can enable smaller blocks, since you don’t have that much latency to amortize, yet higher memory bandwidth usually leads to larger blocks, since the miss penalty is only slightly larger. §5.3, page 491: 1. §5.4, page 517: 1-a, 2-c, 3-b, 4-d. §5.5, page 525: 2. (Both large block sizes and prefetching may reduce compulsory misses, so 1 is false.) Answers to Check Yourself 5.14 Exercises 567
Hennesey_Page_565_Chunk565
6 Combining bandwidth and storage . . . enables swift and reliable access to the ever-expanding troves of content on the proliferating disks and . . . repositories of the Internet. George Gilder The End Is Drawing Nigh, 2000 Storage and Other I/O Topics 6.1 Introduction 570 6.2 Dependability, Reliability, and Availability 573 6.3 Disk Storage 575 6.4 Flash Storage 580 6.5 Connecting Processors, Memory, and I/O Devices 582 6.6 Interfacing I/O Devices to the Processor, Memory, and Operating System 586 Computer Organization and Design. DOI: 10.1016/B978-0-12-374750-1.00006-2 © 2012 Elsevier, Inc. All rights reserved.
Hennesey_Page_566_Chunk566
6.7 I/O Performance Measures: Examples from Disk and File Systems 596 6.8 Designing an I/O System 598 6.9 Parallelism and I/O: Redundant Arrays of Inexpensive Disks 599 6.10 Real Stuff: Sun Fire x4150 Server 606 6.11 Advanced Topics: Networks 612 6.12 Fallacies and Pitfalls 613 6.13 Concluding Remarks 617 6.14 Historical Perspective and Further Reading 618 6.15 Exercises 619 The Five Classic Components of a Computer
Hennesey_Page_567_Chunk567
570 Chapter 6 Storage and Other I/O Topics 6.1 Introduction Although users can get frustrated if their computer hangs and must be rebooted, they become apoplectic if their storage system crashes and they lose information. Thus, the standard for dependability is much higher for storage than for computa­ tion. Networks also plan for failures in communication, including several mecha­ nisms to detect and recover from such failures. Hence, I/O systems generally place much greater emphasis on dependability and cost, while processors and memory focus on performance and cost. I/O systems must also plan for expandability and for diversity of devices, which is not a concern for processors. Expandability is related to storage capacity, which is another design parameter for I/O systems; systems may need a lower bound of storage capacity to fulfill their role. Although performance plays a smaller role for I/O, it is more complex. For example, with some devices we may care primarily about access latency, while FIGURE 6.1 A typical collection of I/O devices. The connections between the I/O devices, ­processor, and memory are historically called buses, although the term means shared parallel wires and most I/O connections today are closer to dedicated serial lines. Communication among the devices and the pro­ cessor uses both interrupts and protocols on the interconnect, as we will see in this chapter. Figure 6.9 shows the organization for a desktop PC. Disk Disk Processor Cache Memory-I/O Interconnect Main memory I/O controller I/O controller I/O controller Graphics output Network Interrupts
Hennesey_Page_568_Chunk568
with others throughput is crucial. Furthermore, performance depends on many aspects of the system: the device characteristics, the connection between the device and the rest of the system, the memory hierarchy, and the operating sys­tem. All of the components, from the individual I/O devices to the processor to the system software, will affect the dependability, expandability, and performance of tasks that include I/O. Figure 6.1 shows the structure of a simple system with its I/O. I/O devices are incredibly diverse. Three characteristics are useful in organizing this wide variety: ■ ■Behavior: Input (read once), output (write only, cannot be read), or ­storage (can be reread and usually rewritten). ■ ■Partner: Either a human or a machine is at the other end of the I/O device, either feeding data on input or reading data on output. ■ ■Data rate: The peak rate at which data can be transferred between the I/O device and the main memory or processor. It is useful to know the maximum demand the device may generate when designing an I/O system. For example, a keyboard is an input device used by a human with a peak data rate of about 10 bytes per second. Figure 6.2 shows some of the I/O devices connected to computers. Device Behavior Partner Data rate (Mbit/sec) Keyboard Input Human 30,000.0001 Mouse Input Human 30,000.0038 Voice input Input Human 30,000.2640 Sound input Input Machine 30,003.0000 Scanner Input Human 30,003.2000 Voice output Output Human 30,000.2640 Sound output Output Human 30,008.0000 Laser printer Output Human 30,003.2000 Graphics display Output Human 800.0000–8000.0000 Cable modem Input or output Machine 0.1280–6.0000 Network/LAN Input or output Machine 100.0000–10000.0000 Network/wireless LAN Input or output Machine 11.0000–54.0000 Optical disk Storage Machine 30,080.0000–220.0000 Magnetic tape Storage Machine 005.0000–120.0000 Flash memory Storage Machine 32.0000–200.0000 Magnetic disk Storage Machine 800.0000–3000.0000 FIGURE 6.2 The diversity of I/O devices. I/O devices can be distinguished by whether they serve as input, output, or storage devices; their communication partner (people or other computers); and their peak communication rates. The data rates span eight orders of magnitude. Note that a network can be an input or an output device, but cannot be used for storage. Transfer rates for devices are always quoted in base 10, so that 10 Mbit/sec = 10,000,000 bits/sec. 6.1 Introduction 571
Hennesey_Page_569_Chunk569
572 Chapter 6 Storage and Other I/O Topics In Chapter 1, we briefly discussed four important I/O de­vices: mice, graphics displays, disks, and networks. In this chapter we go into much more depth on storage and related items. On the CD, there is an advanced topics section on networks, which are well covered in other books. How we should assess I/O performance often depends on the application. In some environments, we may care primarily about system throughput. In these cases, I/O bandwidth will be most important. Even I/O bandwidth can be mea­ sured in two different ways: 1. How much data can we move through the system in a certain time? 2. How many I/O operations can we do per unit of time? Which performance measurement is best may depend on the environment. For example, in many multimedia applications, most I/O requests are for long streams of data, and transfer bandwidth is the important characteristic. In another ­environment, we may wish to process a large number of small, unrelated accesses to an I/O device. An example of such an environment might be a tax-processing office of the U.S. National Income Tax Service (NITS). NITS mostly cares about processing a large number of forms in a given time; each tax form is stored sepa­ rately and is fairly small. A system oriented toward large file transfer may be satis­ factory, but an I/O system that can support the simultaneous transfer of many small files may be cheaper and faster for processing millions of tax forms. In other applications, we care primarily about response time, which you will recall is the total elapsed time to accomplish a particular task. If the I/O requests are extremely large, response time will depend heavily on bandwidth, but in many environments, most accesses will be small, and the I/O system with the lowest latency per access will deliver the best response time. On ­single-user machines such as desktop computers and laptops, response time is the key performance characteristic. A large number of applications, especially in the vast commercial market for computing, require both high throughput and short response times. Examples include automatic teller machines (ATMs), order entry and inventory tracking systems, file servers, and Web servers. In such environments, we care about both how long each task takes and how many tasks we can process in a second. The number of ATM requests you can process per hour doesn’t matter if each one takes 15 minutes—you won’t have any customers left! Similarly, if you can process each ATM request quickly but can only handle a small number of requests at once, you won’t be able to support many ATMs, or the cost of the computer per ATM will be very high. In summary, the three classes of desktop, server, and embedded computers are sensitive to I/O dependability and cost. Desktop and embedded systems are more focused on response time and diversity of I/O devices, while server systems are more focused on throughput and expandability of I/O devices. I/O requests Reads or writes to I/O devices.
Hennesey_Page_570_Chunk570
6.2 Dependability, Reliability, and Availability Users crave dependable storage, but how do you define it? In the computer indus­ try, it is harder than looking it up in the dictionary. After considerable debate, the following is considered the standard definition [Laprie, 1985]: Computer system dependability is the quality of delivered service such that reli­ance can justifiably be placed on this service. The service delivered by a system is its observed actual behavior as perceived by other system(s) interacting with this system’s users. Each module also has an ideal specified behavior, where a service specification is an agreed description of the expected behavior. A system failure occurs when the actual behavior deviates from the specified behavior. Thus, you need a reference specification of expected behavior to be able to determine dependability. Users can then see a system alternating between two states of delivered service with respect to the service specification: 1. Service accomplishment, where the service is delivered as specified 2. Service interruption, where the delivered service is different from the speci­ fied service Transitions from state 1 to state 2 are caused by failures, and transitions from state 2 to state 1 are called restorations. Failures can be permanent or intermittent. The latter is the more difficult case; it is harder to diagnose the problem when a system oscillates between the two states. Permanent failures are far easier to diagnose. This definition leads to two related terms: reliability and availability. Reliability is a measure of the continuous service accomplishment—or, equiva­ lently, of the time to failure—from a reference point. Hence, the mean time to failure (MTTF) of disks in Figure 6.5 below is a reliability measure. A related term is annual failure rate (AFR), which is just the percentage of devices that would be expected to fail in a year for a given MTTF. Service interruption is measured as mean time to repair (MTTR). Mean time between failures (MTBF) is simply the sum of MTTF + MTTR. Although MTBF is widely used, MTTF is often the more appropriate term. Availability is a measure of service accomplishment with respect to the alter­ nation between the two states of accomplishment and interruption. Availabil­ity is statistically quantified as Availability = ​ MTTF  (MTTF + MTTR) ​ 6.2 Dependability, Reliability, and Availability 573
Hennesey_Page_571_Chunk571
574 Chapter 6 Storage and Other I/O Topics Note that reliability and availability are actually quantifiable measures, rather than just synonyms for dependability. What is the cause of failures? Figure 6.3 summarizes many papers that have col­ lected data on reasons for computer systems and telecommunications systems to fail. Clearly, human operators are a significant source of failures. Operator Software Hardware System Year data collected 42% 25% 18% Datacenter (Tandem) 1985 15% 55% 14% Datacenter (Tandem) 1989 18% 44% 39% Datacenter (DEC VAX) 1985 50% 20% 30% Datacenter (DEC VAX) 1993 50% 14% 19% U.S. public telephone network 1996 54% 7% 30% U.S. public telephone network 2000 60% 25% 15% Internet services 2002 FIGURE 6.3 Summary of studies of reasons for failures. Although it is difficult to collect data to determine whether operators are the cause of errors, since operators often record the reasons for failures, these studies did capture that data. There were often other categories, such as environmental reasons for outages, but they were generally small. The top two rows come from a classic paper by Jim Gray [1990], which is still widely quoted almost 20 years after the data was collected. The next two rows are from a paper by Murphy and Gent, who studied causes of outages in VAX systems over time [“Measuring system and software reli­ability using an automated data collection process,” Quality and Reliability Engineering International 11:5, September–October 1995, 341–53]. The fifth and sixth rows are studies of FCC failure data about the U.S. public switched telephone network by Kuhn [“Sources of failure in the public switched telephone network,” IEEE Computer 30:4, April 1997, 31–36] and by Patty Enriquez. The study of three Internet services is from Oppenheimer, Ganapath, and Patterson [2003]. To increase MTTF, you can improve the quality of the components or design systems to continue operation in the presence of components that have failed. Hence, failure needs to be defined with respect to a context. A failure in a compo­ nent may not lead to a failure of the system. To make this distinction clear, the term fault is used to mean failure of a component. Here are three ways to improve MTTF: 1. Fault avoidance: Preventing fault occurrence by construction. 2. Fault tolerance: Using redundancy to allow the service to comply with the service specification despite faults occurring, which applies primarily to hardware faults. Section 6.9 describes the RAID approaches to making storage dependable via fault tolerance. 3. Fault forecasting: Predicting the presence and creation of faults, which applies to hardware and software faults, allowing the component to be replaced before it fails. Shrinking MTTR can help availability as much as increasing MTTF. For example, tools for fault detection, diagnosis, and repair can help reduce the time to repair faults by people, software, and hardware.
Hennesey_Page_572_Chunk572
Which of the following are true about dependability? 1. If a system is up, then all its components are accomplishing their expected service. 2. Availability is a quantitative measure of the percentage of time a system is accomplishing its expected service. 3. Reliability is a quantitative measure of continuous service accomplishment by a system. 4. The major source of outages today is software. 6.3 Disk Storage As mentioned in Chapter 1, magnetic disks rely on a rotating platter coated with a magnetic surface and use a moveable read/write head to access the disk. Disk stor­ age is nonvolatile—the data remains even when power is removed. A magnetic disk consists of a collection of platters (1–4), each of which has two recordable disk surfaces. The stack of platters is rotated at 5400 to 15,000 RPM and has a diameter from 1-inch to just over 3.5 inches. Each disk surface is divided into con­centric circles, called tracks. There are typically 10,000 to 50,000 tracks per sur­face. Each track is in turn divided into sectors that contain the information; each track may have 100 to 500 sectors. Sectors are typically 512 bytes in size, although there is an initiative to increase the sector size to 4096 bytes. The sequence recorded on the magnetic media is a sector number, a gap, the information for that sector including error correction code (see Appendix C, page C-66), a gap, the sector number of the next sector, and so on. Originally, all tracks had the same number of sectors and hence the same num­ ber of bits. With the introduction of zone bit recording (ZBR) in the early 1990s, disk drives changed to a varying number of sectors (and hence bits) per track, instead keeping the spacing between bits constant. ZBR increases the number of bits on the outer tracks and thus increases the drive capacity. As we saw in Chapter 1, to read and write information the read/write heads must be moved so that they are over the correct location. The disk heads for each surface are connected together and move in conjunction, so that every head is over the same track of every surface. The term cylinder is used to refer to all the tracks under the heads at a given point on all surfaces. To access data, the operating system must direct the disk through a three-stage process. The first step is to position the head over the proper track. This operation is called a seek, and the time to move the head to the desired track is called the seek time. Check Yourself nonvolatile Storage device where data retains its value even when power is removed. track One of thousands of con­centric circles that makes up the surface of a magnetic disk. sector One of the segments that make up a track on a mag­netic disk; a sector is the smallest amount of ­information that is read or written on a disk. seek The process of positioning a read/write head over the proper track on a disk. 6.3 Disk Storage 575
Hennesey_Page_573_Chunk573
576 Chapter 6 Storage and Other I/O Topics Disk manufacturers report minimum seek time, maximum seek time, and average seek time in their manuals. The first two are easy to measure, but the aver­ age is open to wide interpretation because it depends on the seek distance. The industry has decided to calculate average seek time as the sum of the time for all possible seeks divided by the number of possible seeks. Average seek times are usually advertised as 3 ms to 13 ms, but, depending on the application and sched­ uling of disk requests, the actual average seek time may be only 25% to 33% of the advertised number because of locality of disk references. This locality arises both because of successive accesses to the same file and because the operating system tries to schedule such accesses together. Once the head has reached the correct track, we must wait for the desired sec­ tor to rotate under the read/write head. This time is called the rotational latency or rotational delay. The average latency to the desired information is halfway around the disk. Because the disks rotate at 5400 RPM to 15,000 RPM, the average rotational latency is between Average rotational latency = ​ 0.5 rotation  5400 RPM ​ = ​ 0.5 rotation  5400 RPM/​( 60 ​ seconds  minute ​ )​ ​ = 0.0056 seconds = 5.6 ms and Average rotational latency = ​ 0.5 rotation  15,000 RPM ​ = ​ 0.5 rotation  15,000 RPM/​( 60 ​ seconds  minute ​ )​ ​ = 0.0020 seconds = 2.0 ms The last component of a disk access, transfer time, is the time to transfer a block of bits. The transfer time is a function of the sector size, the rotation speed, and the recording density of a track. Transfer rates in 2008 were between 70 and 125 MB/sec. The one complication is that most disk controllers have a built-in cache that stores sectors as they are passed over; transfer rates from the cache are typi­cally higher and may be up to 375 MB/sec (3 Gbit/sec) in 2008. Today, most disk transfers are multiple sectors in length. A disk controller usually handles the detailed control of the disk and the transfer between the disk and the memory. The controller adds the final component of disk access time, controller time, which is the overhead the controller imposes in performing an I/O access. The average time to perform an I/O operation will con­ sist of these four times plus any wait time incurred because other processes are using the disk. rotational latency Also called rotational delay. The time required for the desired sector of a disk to rotate under the read/write head; usually assumed to be half the ­rotation time.
Hennesey_Page_574_Chunk574
Disk Read Time What is the average time to read or write a 512-byte sector for a typical disk rotating at 15,000 RPM? The advertised average seek time is 4 ms, the transfer rate is 100 MB/sec, and the controller overhead is 0.2 ms. Assume that the disk is idle so that there is no waiting time. Average disk access time is equal to average seek time + average rotational de­lay + transfer time + controller overhead. Using the advertised average seek time, the answer is 4.0 ms + ​ 0.5 rotation  15,000 RPM ​ + ​ 0.5 KB  100 MB/sec ​ + 0.2 ms = 4.0 + 2.0 + 0.005 + 0.2 = 6.2 ms If the measured average seek time is 25% of the advertised average time, the answer is 1.0 ms + 2.0 ms + 0.005 ms + 0.2 ms = 3.2 ms Notice that when we consider measured average seek time, as opposed to advertised average seek time, the rotational latency can be the largest compo­ nent of the access time. Disk densities have continued to increase for more than 50 years. The impact of this compounded improvement in density and the reduction in physical size of a disk drive has been amazing, as Figure 6.4 shows. The aims of different disk designers have led to a wide variety of drives being available at any particular time. Figure 6.5 shows the characteristics of four ­magnetic disks. In 2008, these disks from a single manufacturer cost between $0.30 and $5.00 per gigabyte. In the broader market, prices generally range between $0.20 and $2.00 per gigabyte, depending on size, interface, and performance. While disks will remain viable for the foreseeable future, the conventional wis­dom about where block numbers are found has not. The assumptions of the sec­tor-track-cylinder model are that nearby blocks are on the same track, blocks in the same cylinder take less time to access since there is no seek time, and some tracks are closer than others. The reason for the breakdown was the raising of the level of the interfaces. Higher-level intelligent interfaces like ATA and SCSI required a microprocessor inside a disk, which lead to performance optimiza­tions. To speed-up sequential transfers, these higher-level interfaces organize disks more like tapes than like random access devices. The logical blocks are ordered in serpentine fashion across a single surface, trying to capture all the sectors that are recorded at the same bit density. Hence, sequential blocks may be on different tracks. We will see an example in Figure 6.19 of the pitfall of assuming the conventional sector-track-cylinder model. EXAMPLE ANSWER Advanced Technology Attachment (ATA) A command set used as a standard for I/O devices that is popular in the PC. Small Computer Systems Interface (SCSI) A command set used as a standard for I/O devices. 6.3 Disk Storage 577
Hennesey_Page_575_Chunk575
578 Chapter 6 Storage and Other I/O Topics FIGURE 6.4 Six magnetic disks, varying in diameter from 14 inches down to 1.8 inches. The pictured disks were introduced over more than 15 years ago and hence are not intended to be represen­ tative of the best capacity of modern disks of these diameters. This photograph does, however, accurately portray their relative physical sizes. The widest disk is the DEC R81, containing four 14-inch diameter plat­ ters and storing 456 MB. It was manufactured in 1985. The 8-inch diameter disk comes from Fujitsu, and this 1984 disk stores 130 MB on six platters. The Micropolis RD53 has five 5.25-inch platters and stores 85 MB. The IBM 0361 also has five platters, but these are just 3.5 inches in diameter. This 1988 disk holds 320 MB. In 2008, the most dense 3.5-inch disk had 2 platters and held 1 TB in the same space, yielding an increase in density of about 3000 times! The Conner CP 2045 has two 2.5-inch platters containing 40 MB and was made in 1990. The smallest disk in this photograph is the Integral 1820. This single 1.8-inch platter contains 20 MB and was made in 1992. Elaboration: These high-level interfaces let disk controllers add caches, which allow for fast access to data that was recently read between transfers requested by the pro­cessor. They use write-through and do not update on a write miss, and often also include prefetch algorithms to try to anticipate demand. Controllers also use a com­ mand queue that allow the disk to decide in what order to perform the commands to maximize performance while maintaining correct behavior. Of course, such capabilities complicate the measurement of disk performance and increase the importance of workload choice when comparing disks.
Hennesey_Page_576_Chunk576
Characteristics Seagate ST33000655SS Seagate ST31000340NS Seagate ST973451SS Seagate ST9160821AS Disk diameter (inches) 3.50 3.50 2.50 2.50 Formatted data capacity (GB) 147 1000 73 160 Number of disk surfaces (heads) 2 4 2 2 Rotation speed (RPM) 15,000 7200 15,000 5400 Internal disk cache size (MB) 16 32 16 8 External interface, bandwidth (MB/sec) SAS, 375 SATA, 375 SAS, 375 SATA, 150 Sustained transfer rate (MB/sec) 73–125 105 79–112 44 Minimum seek (read/write) (ms) 0.2/0.4 0.8/1.0 0.2/0.4 1.5/2.0 Average seek read/write (ms) 3.5/4.0 8.5/9.5 2.9/3.3 12.5/13.0 Mean time to failure (MTTF) (hours) 1,400,000 @ 25°C 1,200,000 @ 25°C 1,600,000 @ 25°C — Annual failure rate (AFR) (percent) 0.62% 0.73% 0.55% — Contact start-stop cycles — 50,000 — >600,000 Warranty (years) 5 5 5 5 Nonrecoverable read errors per bits read <1 sector per 1016 <1 sector per 1015 <1 sector per 1016 <1 sector per 1014 Temperature, shock (operating) 5°–55°C, 60 G 5°–55°C, 63 G 5°–55°C, 60 G 0°–60°C, 350 G Size: dimensions (in.), weight (pounds) 1.0" × 4.0" × 5.8", 1.5 lbs 1.0" × 4.0" × 5.8", 1.4 lbs 0.6" × 2.8" × 3.9", 0.5 lbs 0.4" × 2.8" × 3.9", 0.2 lbs Power: operating/idle/ standby (watts) 15/11/— 11/8/1 8/5.8/— 1.9/0.6/0.2 GB/cu. in., GB/watt 6 GB/cu.in., 10 GB/W 43 GB/cu.in., 91 GB/W 11 GB/cu.in., 9 GB/W 37 GB/cu.in., 84 GB/W Price in 2008, $/GB ~ $250, ~ $1.70/GB ~ $275, ~ $0.30/GB ~ $350, ~ $5.00/GB ~ $100, ~ $0.60/GB FIGURE 6.5 Characteristics of four magnetic disks by a single manufacturer in 2008. The three leftmost drives are for servers and desktops while the rightmost drive is for laptops. Note that the third drive is only 2.5 inches in diameter, but it is a high performance drive with the highest reliability and fastest seek time. The disks shown here are either serial versions of the interface to SCSI (SAS), a standard I/O bus for many sys­tems, or serial version of ATA (SATA), a standard I/O bus for PCs. The transfer rates from the caches is 3–5 times faster than the transfer rate from the disk surface. The much lower cost per gigabyte of the SATA 3.5-inch drive is primarily due to the hyper-competitive PC market, although there are dif­ferences in performance in I/Os per second due to faster rotation and faster seek times for SAS. The service life for these disks is five years. Note that the quoted MTTF assumes nominal power and temperature. Disk lifetimes can be much shorter if temperature and vibration are not controlled. See the link to Seagate at www.seagate.com for more information on these drives. Which of the following are true about disk drives? 1. 3.5-inch disks perform more IOs per second than 2.5-inch disks. 2. 2.5-inch disks offer the highest gigabytes per watt. 3. It takes hours to read the contents of a high capacity disk sequentially. 4. It takes months to read the contents of a high capacity disk using random 512-byte sectors. Check Yourself 6.3 Disk Storage 579
Hennesey_Page_577_Chunk577
580 Chapter 6 Storage and Other I/O Topics 6.4 Flash Storage. Many have tried to invent a technology to replace disks, and many have failed: CCD memory, bubble memory, and holographic memory were all found want­ing. By the time a new technology would ship, disks made advances as predicted earlier, costs dropped accordingly, and the challenging product would be unattractive in the marketplace. The first credible challenger is flash memory. This semiconductor memory is nonvolatile like disks, but latency is 100–1000 times faster than disk, and it is smaller, more power efficient, and more shock resistant. Equally important, because of the popularity of flash memory in cell phones, digital cameras, and MP3 players, there is a large market to pay for the investment in improving flash mem­ory technology. Recently, flash memory cost per gigabyte has been falling 50% per year. In 2008, the price per gigabyte of flash was $4 to $10 per gigabyte, or about 2 to 40 times higher than disk and 5 to 10 times lower than DRAM. Figure 6.6 com­pares three flash-based products. Characteristics Kingston SecureDigital (SD) SD4/8 GB Transend Type I CompactFlash TS16GCF133 RiDATA Solid State Disk 2.5 inch SATA Formatted data capacity (GB) 8 16 32 Bytes per sector 512 512 512 Data transfer rate (read/write MB/sec) 4 20/18 68/50 Power operating/standby (W) 0.66/0.15 0.66/0.15 2.1/— Size: height × width × depth (inches) 0.94 × 1.26 × 0.08 1.43 × 1.68 × 0.13 0.35 × 2.75 × 4.00 Weight in grams (454 grams/pound) 2.5 11.4 52 Mean time between failures (hours) > 1,000,000 > 1,000,000 > 4,000,000 GB/cu. in., GB/watt 84 GB/cu.in., 12 GB/W 51 GB/cu.in., 24 GB/W 8 GB/cu.in., 16 GB/W Best price (2008) ~ $30 ~ $70 ~ $300 FIGURE 6.6 Characteristics of three flash storage products. The CompactFlash standard package was proposed by Sandisk Corporation in 1994 for the PCMCIA-ATA cards of portable PCs. Because it follows the ATA interface, it simulates a disk interface, including seek commands, logical tracks, and so on. The RiDATA product imitates an SATA 2.5-inch disk interface. Although its cost per gigabyte is higher than disks, flash memory is popular in mobile devices in part because it comes in smaller capacities. As a result, the 1-inch
Hennesey_Page_578_Chunk578
diameter hard disks are disappearing from some embedded markets. For example, in 2008 the Apple iPod Shuffle MP3 player sold for $50 and held 1 GB, while the small­est disk holds 4 GB and sells for more than the whole MP3 player. Flash memory is a type of electrically erasable programmable read-only mem­ ory (EEPROM). The first flash memory, called NOR flash because of the similarity of the storage cell to a standard NOR gate, was a direct competitor with other EEPROMs and is randomly addressable like any memory. A few years later, NAND flash memory offered greater storage density, but memory could only be read and written in blocks as wiring needed for random accesses was removed. NAND flash is much less expensive per gigabyte and much more popular than NOR flash; all of the products in Figure 6.6 use NAND flash. Figure 6.7 compares the key characteristics of NOR versus NAND flash memory. Unlike disks and DRAM, but like other EEPROM technologies, flash memory bits wear out (see Figure 6.7). To cope with such limits, most NAND flash prod­ucts include a controller to spread the writes by remapping blocks that have been written many times to less trodden blocks. This technique is called wear leveling. With wear leveling, consumer products like cell phones, digital cameras, MP3 players, or memory keys are very unlikely to exceed the write limits in the flash. Such controllers lower the potential performance of flash, but they are needed unless higher-level software monitors block wear. However, controllers can also improve yield by mapping out memory cells that were manufactured incorrectly. Write limits are one reason flash memory is not popular in desktop and server computers. However, in 2008 the first laptops are being sold with flash memory instead of hard disks at a considerable price premium to offer faster boot times, smaller size, and longer battery life. There are also flash memories available in standard disk form factors, as Figure 6.6 shows. Combining both ideas, hybrid hard disks include, say, a gigabyte of flash memory so that laptops can boot more quickly and save energy by allowing the disks to remain idle more frequently. In the coming years, it appears that flash will compete successfully with hard disks for many battery-operated devices. As capacity increases and the cost per Characteristics NOR Flash Memory NAND Flash Memory Typical use BIOS memory USB key Minimum access size (bytes) 512 bytes 2048 bytes Read time (microseconds) 0.08 25 Write time (microseconds) 10.00 1500 to erase + 250 Read bandwidth (MBytes/second) 10 40 Write bandwidth (MBytes/second) 0.4 8 Wearout (writes per cell) 100,000 10,000 to 100,000 Best price/GB (2008) $65 $4 FIGURE 6.7 Characteristics of NOR versus NAND flash memory in 2008. These devices can read bytes and 16-bit words despite their large access sizes. 6.4 Flash Storage 581
Hennesey_Page_579_Chunk579
582 Chapter 6 Storage and Other I/O Topics gigabyte continues to decline, it will be interesting to see whether the higher performance and energy efficiency of flash memory will yield opportunities in the desktop and server markets as well. Which of the following are true about flash memory? 1. Like DRAM, flash is a semiconductor memory. 2. Like disks, flash does not lose information if it loses power. 3. The read access time of NOR flash is similar to DRAM. 4. The read bandwidth of NAND flash is similar to disk. 6.5 Connecting Processors, Memory, and I/O Devices In a computer system, the various subsystems must have interfaces to one another. For example, the memory and processor need to com­municate, as do the proces­ sor and the I/O devices. For many years, this has been done with a bus. A bus is a shared communication link, which uses one set of wires to connect multiple sub­ systems. The two major advantages of the bus organization are versatility and low cost. By defining a single connection scheme, new devices can easily be added, and peripherals can even be moved between computer systems that use the same kind of bus. Furthermore, buses are cost-effective, because a single set of wires is shared in multiple ways. The major disadvantage of a bus is that it creates a communication bottle­neck, possibly limiting the maximum I/O throughput. When I/O must pass through a single bus, the bandwidth of that bus limits the maximum I/O throughput. Designing a bus system capable of meeting the demands of the pro­cessor as well as connecting large numbers of I/O devices to the machine pre­sents a major challenge. Buses are traditionally classified as processor-memory buses or I/O buses. ­Processor-memory buses are short, generally high speed, and matched to the memory system so as to maximize memory-­processor bandwidth. I/O buses, by contrast, can be lengthy, can have many types of devices connected to them, and often have a wide range in the data bandwidth of the devices connected to them. I/O buses do not typically interface directly to the memory but use either a ­processor- memory or a backplane bus to connect to memory. Other buses with different characteristics have emerged for special functions, such as graphics buses. One reason bus design is so difficult is that the maximum bus speed is largely limited by physical factors: the length of the bus and the number of devices. These physical limits prevent us from running the bus arbitrarily fast. In addition, the Check Yourself processor-memory bus A bus that connects processor and memory and that is short, gen­erally high speed, and matched to the memory system so as to maximize memory- processor bandwidth. backplane bus A bus that is designed to allow processors, memory, and I/O devices to coexist on a single bus.
Hennesey_Page_580_Chunk580
need to support a range of devices with widely varying ­latencies and data transfer rates also makes bus design challenging. As it became difficult to run many parallel wires at high speed due to clock skew and reflection (see Appendix C), the industry transitioned from parallel shared buses to high-speed serial point-to-point interconnections with switches. Thus, such I/O networks have generally replaced I/O buses in our systems. As a result of this transition, this section has been revised in this edition to emphasize the general problem of connecting I/O devices, processors, and mem­ ory, rather than focusing exclusively on buses. Connection Basics Let’s consider a typical I/O transaction. A transaction in­cludes two parts: sending the address and receiving or sending the data. Bus transactions are typically defined by what they do to memory. A read transac­tion transfers data from mem­ ory (to either the processor or an I/O de­vice), and a write transaction writes data to the memory. Clearly, this terminology is confusing. To avoid this, we’ll try to use the terms input and output, which are always defined from the perspective of the processor: an input operation is inputting data from the device to memory, where the processor can read it, and an output operation is outputting data to a device from memory where the processor wrote it. The I/O interconnect serves as a way of expanding the machine and connecting new peripherals. To make this easier, the computer industry has developed several standards. The standards serve as a specification for the computer manufacturer and for the peripheral manufacturer. A standard assures the computer designer that peripherals will be available for a new machine, and it ensures the peripheral builder that users will be able to hook up their new equipment. Figure 6.8 sum­ marizes the key characteristics of the five popular I/O standards: Firewire, USB, PCI Express (PCIe), Serial ATA (SATA), and Serial Attached SCSI (SAS). They connect a variety of devices to the desktop computer, from keyboards to cameras to disks. Traditional buses are synchronous. That means the bus includes a clock in the con­trol lines and a fixed protocol for communicating that is relative to the clock. For example, for performing a read from memory, we might have a protocol that transmits the address and read command on the first clock cycle, using the control lines to indicate the type of request. The memory might then be required to respond with the data word on the fifth clock. This type of protocol can be imple­mented easily in a small finite-state machine. Because the protocol is predeter­ mined and involves little logic, the bus can run fast, and the interface logic will be small. Synchronous buses have two major disadvantages, however. First, every device on the bus must run at the same clock rate. Second, because of clock skew problems, synchronous buses cannot be long if they are fast (see Appendix C). These problems led to asynchronous interconnects, which are not clocked. Because they are not clocked, asynchronous interconnects can accom­modate a wide variety of devices, and the bus can be lengthened without worrying about I/O transaction A sequence of operations over the interconnect that ­includes a request and may include a response, either of which may carry data. A trans­action is initiated by a single request and may take many individual bus operations. synchronous bus A bus that includes a clock in the control lines and a fixed protocol for communicating that is relative to the clock. asynchronous interconnect Uses a handshaking protocol for coordinating usage rather than a clock; can ­accommodate a wide variety of devices of dif­fering speeds. 6.5 Connecting Processors, Memory, and I/O Devices 583
Hennesey_Page_581_Chunk581
584 Chapter 6 Storage and Other I/O Topics clock skew or synchronization problems. All the examples in Figure 6.8 are asyn­chronous. To coordinate the transmission of data between sender and receiver, an asyn­ chronous bus uses a handshaking protocol. A handshaking protocol consists of a series of steps in which the sender and receiver proceed to the next step only when both parties agree. The protocol is implemented with an additional set of control lines. The I/O Interconnects of the x86 Processors Figure 6.9 shows the I/O system of a traditional PC. The processor connects to periph­erals via two main chips. The chip next to the processor is the memory controller hub, commonly called the north bridge, and the one connected to it is the I/O controller hub, called the south bridge. The north bridge is basically a DMA controller, connecting the processor to memory, possibly a graphics card, and the south bridge chip. The south bridge connects the north bridge to a cornucopia of I/O buses. Intel, AMD, NVIDIA, and others offer a wide variety of these chip sets to connect the processor to the out­side world. Figure 6.10 shows three examples of the chip sets. Note that AMD swallowed the north bridge chip in the Opteron and later products, thereby reducing the chip count and the latency to memory and graphics cards by skipping a chip crossing. As Moore’s law continues, an increasing number of I/O controllers that were ­formerly available as optional cards that connected to I/O buses have been co-opted into these chip sets. For example, the AMD Opteron X4 and the Intel Nehalem handshaking protocol A series of steps used to coordinate asynchronous bus transfers in which the sender and receiver proceed to the next step only when both parties agree that the current step has been completed. Characteristic Firewire (1394) USB 2.0 PCI Express Serial ATA Serial Attached SCSI Intended use External External Internal Internal External Devices per channel 63 127 1 1 4 Basic data width (signals) 4 2 2 per lane 4 4 Theoretical peak bandwidth 50 MB/sec (Firewire 400) or 100 MB/sec (Firewire 800) 0.2 MB/sec (low speed), 1.5 MB/sec (full speed), or 60 MB/sec (high speed) 250 MB/sec per lane (1x); PCIe cards come as 1x, 2x, 4x, 8x, 16x, or 32x 300 MB/ sec 300 MB/sec Hot pluggable Yes Yes Depends on form factor Yes Yes Maximum bus length (copper wire) 4.5 meters 5 meters 0.5 meters 1 meter 8 meters Standard name IEEE 1394, 1394b USB Implementors Forum PCI-SIG SATA-IO T10 committee FIGURE 6.8 Key characteristics of five dominant I/O standards. The intended use column indicates whether it is designed to be used with cables external to the computer or just inside the computer with short cables or wire on printed circuit boards. PCIe can sup­port simultaneous reads and writes, so some publications double the bandwidth per lane assuming a 50/50 split of read versus write band­width.
Hennesey_Page_582_Chunk582
include the north bridge inside the microprocessor, and the south bridge chip of the Intel 975 includes a RAID controller (see Section 6.9). These I/O interconnects provide electrical connectivity among I/O devices, processors, and memory, and also define the lowest-level protocol for commu­ nication. Above this basic level, we must define hardware and software protocols for controlling data transfers between I/O devices and memory, and for the ­pro­ cessor to specify commands to the I/O devices. These topics are covered in the next section. Both networks and buses connect components together. Which of the following are true about them? 1. I/O networks and I/O buses are almost always standardized. 2. I/O networks and I/O buses are almost always synchronous. Check Yourself Parallel ATA (100 MB / sec) PCIe x16 (or 2 PCIe x8) (4 GB / sec) PCIe x4 (1 GB / sec) PCIe x4 (1 GB / sec) ESI (2 GB/sec) PCIe x8 (2 GB/sec) Serial ATA (300 MB/sec) Disk Intel Xeon 5300 processor Intel Xeon 5300 processor Memory controller hub (north bridge) 5000P Main memory DIMMs FB DDR2 667 (5.3 GB/sec) Disk LPC (1 MB/sec) Keyboard, mouse, ... USB 2.0 (60 MB/sec) I/O controller hub (south bridge) Entreprise South Bridge 2 Front Side Bus (1333 MHz, 10.5 GB / sec) CD / DVD PCI-X bus (1 GB / sec) PCI-X bus (1 GB / sec) FIGURE 6.9 Organization of the I/O system on an Intel server using the Intel 5000P chip set. If you assume reads and writes are each half the traffic, you can double the bandwidth per link for PCIe. 6.5 Connecting Processors, Memory, and I/O Devices 585
Hennesey_Page_583_Chunk583
586 Chapter 6 Storage and Other I/O Topics 6.6 Interfacing I/O Devices to the Processor, Memory, and Operating System A bus or network protocol defines how a word or block of data should be commu­ nicated on a set of wires. This still leaves several other tasks that must be per­formed to actually cause data to be transferred from a device and into the memory address space of some user program. This section focuses on these tasks and will answer such questions as the following: ■ ■How is a user I/O request transformed into a device command and commu­ nicated to the device? ■ ■How is data actually transferred to or from a memory location? ■ ■What is the role of the operating system? Intel 5000P chip set Intel 975X chip set AMD 580X CrossFire Target segment Server Performance PC Server/Performance PC Front Side Bus (64 bit) 1066/1333 MHz 800/1066 MHz — Memory controller hub (“north bridge”) Product name Blackbird 5000P MCH 975X MCH Pins 1432 1202 Memory type, speed DDR2 FBDIMM 667/533 DDR2 800/667/533 Memory buses, widths 4 × 72 1 × 72 Number of DIMMs, DRAM/DIMM 16, 1 GB/2 GB/4 GB 4, 1 GB/2 GB Maximum memory capacity 64 GB 8 GB Memory error correction available? Yes No PCIe/External Graphics Interface 1 PCIe x16 or 2 PCIe x 1 PCIe x16 or 2 PCIe x8 South bridge interface PCIe x8, ESI PCIe x8 I/O controller hub (“south bridge”) Product name 6321 ESB ICH7 580X CrossFire Package size, pins 1284 652 549 PCI-bus: width, speed Two 64-bit, 133 MHz 32-bit, 33 MHz, 6 masters — PCI Express ports Three PCIe x4 Two PCIe x16, Four PCI x1 Ethernet MAC controller, interface — 1000/100/10 Mbit — USB 2.0 ports, controllers 6 8 10 ATA ports, speed One 100 Two 100 One 133 Serial ATA ports 6 2 4 AC-97 audio controller, interface — Yes Yes I/O management SMbus 2.0, GPIO SMbus 2.0, GPIO ASF 2.0, GPIO FIGURE 6.10 Two I/O chip sets from Intel and one from AMD. Note that the north bridge functions are included on the AMD micropro­cessor, as they are on the more recent Intel Nehalem.
Hennesey_Page_584_Chunk584
As we will see in answering these questions, the operating system plays a major role in handling I/O, acting as the interface between the hardware and the pro­gram that requests I/O. The responsibilities of the operating system arise from three characteristics of I/O systems: 1. Multiple programs using the processor share the I/O system. 2. I/O systems often use interrupts (externally generated exceptions) to com­ municate information about I/O operations. Because interrupts cause a transfer to kernel or supervisor mode, they must be handled by the operat­ ing system (OS). 3. The low-level control of an I/O device is complex, because it requires man­ aging a set of concurrent events and because the requirements for correct device control are often very detailed. The three characteristics of I/O systems above lead to several different functions the OS must provide: ■ ■The OS guarantees that a user’s program accesses only the portions of an I/O device to which the user has rights. For example, the OS must not allow a program to read or write a file on disk if the owner of the file has not granted access to this program. In a system with shared I/O ­devices, protec­tion could not be provided if user programs could perform I/O directly. ■ ■The OS provides abstractions for accessing devices by supplying routines that handle low-level device operations. ■ ■The OS handles the interrupts generated by I/O devices, just as it handles the exceptions generated by a program. ■ ■The OS tries to provide equitable access to the shared I/O resources, as well as schedule accesses to enhance system throughput. To perform these functions on behalf of user programs, the operating system must be able to communicate with the I/O devices and to prevent the user pro­gram from communicating with the I/O devices directly. Three types of commu­nication are required 1. The OS must be able to give commands to the I/O devices. These com­mands include not only operations like read and write, but also other oper­ations to be done on the device, such as a disk seek. Hardware/ Software Interface 6.6 Interfacing I/O Devices to the Processor, Memory, and Operating System 587
Hennesey_Page_585_Chunk585
588 Chapter 6 Storage and Other I/O Topics 2. The device must be able to notify the OS when the I/O device has com­pleted an operation or has encountered an error. For example, when a disk completes a seek, it will notify the OS. 3. Data must be transferred between memory and an I/O device. For example, the block being read on a disk read must be moved from disk to memory. In the next few subsections, we will see how these communications are performed. Giving Commands to I/O Devices To give a command to an I/O device, the processor must be able to address the device and to supply one or more command words. Two methods are used to address the device: memory-mapped I/O and special I/O instructions. In memory- mapped I/O, portions of the address space are assigned to I/O devices. Reads and writes to those addresses are interpreted as commands to the I/O device. For example, a write operation can be used to send data to an I/O device where the data will be interpreted as a command. When the processor places the address and data on the memory bus, the memory system ignores the operation because the address indicates a portion of the memory space used for I/O. The device con­troller, however, sees the operation, records the data, and transmits it to the device as a command. User programs are prevented from issuing I/O operations directly, because the OS does not provide access to the address space assigned to the I/O devices, and thus the addresses are protected by the address translation. Memory-mapped I/O can also be used to transmit data by writing or reading to select addresses. The device uses the address to determine the type of command, and the data may be provided by a write or obtained by a read. In any event, the address encodes both the device identity and the type of transmission between processor and device. Actually performing a read or write of data to fulfill a program request usually requires several separate I/O operations. Furthermore, the processor may have to interrogate the status of the device between individual commands to determine whether the command completed successfully. For example, a simple printer has two I/O device registers—one for status information and one for data to be printed. The Status register contains a done bit, set by the printer when it has printed a character, and an error bit, indicating that the printer is jammed or out of paper. Each byte of data to be printed is put into the Data register. The proces­sor must then wait until the printer sets the done bit before it can place another character in the buffer. The processor must also check the error bit to determine if a problem has occurred. Each of these operations requires a separate I/O device access. memory-mapped I/O An I/O scheme in which portions of address space are assigned to I/O devices, and reads and writes to those addresses are interpreted as commands to the I/O device.
Hennesey_Page_586_Chunk586
Elaboration: The alternative to memory-mapped I/O is to use dedicated I/O instruc­tions in the processor. These I/O instructions can specify both the device number and the command word (or the location of the command word in memory). The processor communicates the device address via a set of wires normally included as part of the I/O bus. The actual command can be transmitted over the data lines in the bus. Exam­ples of computers with I/O instructions are the Intel x86 and the IBM 370 computers. By making the I/O instructions illegal to execute when not in kernel or supervisor mode, user programs can be prevented from accessing the devices directly. Communicating with the Processor The process of periodically checking status bits to see if it is time for the next I/O operation, as in the previous example, is called polling. Polling is the simplest way for an I/O device to communicate with the processor. The I/O device simply puts the information in a Status register, and the processor must come and get the information. The processor is totally in control and does all the work. Polling can be used in several different ways. Real-time embedded applications poll the I/O devices, since the I/O rates are predetermined and it makes I/O over­ head more predictable, which is helpful for real time. As we will see, this allows polling to be used even when the I/O rate is somewhat higher. The disadvantage of polling is that it can waste a lot of processor time, because processors are so much faster than I/O devices. The processor may read the Status register many times, only to find that the device has not yet com­pleted a compara­ tively slow I/O operation, or that the mouse has not budged since the last time it was polled. When the device completes an operation, we must still read the status to determine whether it was successful. The overhead in a polling interface was recognized long ago, leading to the invention of interrupts to notify the processor when an I/O device requires atten­ tion from the processor. Interrupt-driven I/O, which is used by almost all systems for at least some devices, employs I/O interrupts to indicate to the processor that an I/O device needs attention. When a device wants to notify the processor that it has completed some operation or needs attention, it causes the processor to be interrupted. An I/O interrupt is just like the exceptions we saw in Chapters 4 and 5, with two important distinctions: 1. An I/O interrupt is asynchronous with respect to the instruction execution. That is, the interrupt is not associated with any instruction and does not prevent the instruction completion. This is very different from either page fault exceptions or exceptions such as arithmetic overflow. Our control unit need only check for a pending I/O interrupt at the time it starts a new instruction. I/O instruction A dedicated instruction that is used to give a command to an I/O device and that specifies both the device number and the command word (or the location of the command word in memory). polling The process of periodi­cally checking the status of an I/O device to determine the need to service the device. interrupt-driven I/O An I/O scheme that employs interrupts to indicate to the processor that an I/O device needs attention. 6.6 Interfacing I/O Devices to the Processor, Memory, and Operating System 589
Hennesey_Page_587_Chunk587
590 Chapter 6 Storage and Other I/O Topics 2. In addition to the fact that an I/O interrupt has occurred, we would like to convey further information, such as the identity of the device generating the interrupt. Furthermore, the interrupts represent devices that may have dif­ ferent priorities and whose interrupt requests have different urgencies asso­ ciated with them. To communicate information to the processor, such as the identity of the ­device raising the interrupt, a system can use either vectored interrupts or an exception Cause register. When the processor recognizes the interrupt, the device can send either the vector address or a status field to place in the Cause register. As a result, when the OS gets control, it knows the identity of the device that caused the interrupt and can immediately interrogate the device. An interrupt mecha­nism eliminates the need for the processor to poll the device and instead allows the processor to focus on executing programs. Interrupt Priority Levels To deal with the different priorities of the I/O devices, most interrupt mechanisms have several levels of priority; UNIX operating systems use four to six levels. These priorities indicate the order in which the processor should process interrupts. Both internally generated exceptions and external I/O interrupts have priorities; typically, I/O interrupts have lower priority than internal exceptions. There may be multiple I/O interrupt priorities, with high-speed devices associated with the higher priorities. To support priority levels for interrupts, MIPS provides the primitives that let the operating system implement the policy, similar to the way that MIPS handles TLB misses. Figure 6.11 shows the key registers, and Section B.7 in Appendix B gives more details. The Status register determines who can interrupt the computer. If the interrupt enable bit is 0, then none can interrupt. A more refined blocking of interrupts is available in the interrupt mask field. There is a bit in the mask corresponding to each bit in the pending interrupt field of the Cause register. To enable the corre­ sponding interrupt, there must be a 1 in the mask field at that bit position. Once an interrupt occurs, the operating system can find the reason in the exception code field of the Status register: 0 means an interrupt occurred, with other values for the exceptions mentioned in Chapter 5. Here are the steps that must occur in handling an interrupt: 1. Logically AND the pending interrupt field and the interrupt mask field to see which enabled interrupts could be the culprit. Copies are made of these two registers using the mfc0 instruction. 2. Select the higher priority of these interrupts. The software convention is that the leftmost is the highest priority.
Hennesey_Page_588_Chunk588
3. Save the interrupt mask field of the Status register. 4. Change the interrupt mask field to disable all interrupts of equal or lower priority. 5. Save the processor state needed to handle the interrupt. 6. To allow higher-priority interrupts, set the interrupt enable bit of the Cause register to 1. 7. Call the appropriate interrupt routine. 8. Before restoring state, set the interrupt enable bit of the Cause register to 0. This allows you to restore the interrupt mask field. Appendix B shows an exception handler for a simple I/O task on pages B-36 to B-37. How do the interrupt priority levels (IPLs) correspond to these mechanisms? The IPL is an operating system invention. It is stored in the memory of the process, and every process is given an IPL. At the lowest IPL, all interrupts are permitted. Conversely, at the highest IPL, all interrupts are blocked. Raising and lowering the IPL involves changes to the interrupt mask field of the Status register. 15 8 4 1 0 Interrupt mask User mode Exception level Interrupt enable 15 31 8 6 2 Pending interrupts Branch delay Exception code FIGURE 6.11 The Cause and Status registers. This version of the Cause register corresponds to the MIPS-32 architecture. The earlier MIPS I architecture had three nested sets of kernel/user and interrupt enable bits to support nested interrupts. Section B.7 in Appendix B has more details about these registers. 6.6 Interfacing I/O Devices to the Processor, Memory, and Operating System 591
Hennesey_Page_589_Chunk589
592 Chapter 6 Storage and Other I/O Topics Elaboration: The two least significant bits of the pending interrupt and interrupt mask fields are for software interrupts, which are lower priority. These are typically used by higher-priority interrupts to leave work for lower-priority interrupts to do once the immedi- ate reason for the interrupt is handled. Once the higher-priority interrupt is finished, the lower-priority tasks will be noticed and handled. Transferring the Data between a Device and Memory We have seen two different methods that enable a device to communicate with the processor. These two techniques—polling and I/O interrupts—form the basis for two methods of implementing the transfer of data between the I/O device and memory. Both these techniques work best with lower-­bandwidth devices, where we are more interested in reducing the cost of the device controller and interface than in providing a high-bandwidth transfer. Both polling and interrupt-driven transfers put the burden of moving data and managing the transfer on the proces­ sor. After looking at these two schemes, we will examine a scheme more suitable for higher-performance devices or collections of devices. We can use the processor to transfer data between a device and memory based on polling. In real-time applications, the processor loads data from I/O device registers and stores them into memory. An alternative mechanism is to make the transfer of data interrupt driven. In this case, the OS would still transfer data in small numbers of bytes from or to the device. But because the I/O operation is interrupt driven, the OS simply works on other tasks while data is being read from or written to the device. When the OS recognizes an interrupt from the device, it reads the status to check for errors. If there are none, the OS can supply the next piece of data, for example, by a sequence of memory-mapped writes. When the last byte of an I/O request has been transmitted and the I/O operation is completed, the OS can inform the pro­ gram. The processor and OS do all the work in this process, accessing the device and memory for each data item transferred. Interrupt-driven I/O relieves the processor from having to wait for every I/O event, although if we used this method for transferring data from or to a hard disk, the overhead could still be intolerable, since it could consume a large frac­tion of the processor when the disk was transferring. For high-bandwidth devices like hard disks, the transfers consist primarily of relatively large blocks of data (hundreds to thousands of bytes). Thus, computer designers invented a mecha­nism for offloading the processor and having the device controller transfer data directly to or from the memory without involving the processor. This mechanism is called direct memory access (DMA). The interrupt mechanism is still used by the device to communicate with the processor, but only on completion of the I/O transfer or when an error occurs. DMA is implemented with a specialized controller that transfers data between an I/O device and memory independent of the processor. The DMA controller direct memory access (DMA) A mechanism that provides a device controller with the ability to transfer data directly to or from the memory without involving the processor.
Hennesey_Page_590_Chunk590
becomes the master and directs the reads or writes between itself and mem­ory. There are three steps in a DMA transfer: 1. The processor sets up the DMA by supplying the identity of the device, the operation to perform on the device, the memory address that is the source or destination of the data to be transferred, and the number of bytes to transfer. 2. The DMA starts the operation on the device and arbitrates for the interconnect. When the data is available (from the device or memory), it transfers the data. The DMA device supplies the memory address for the read or the write. If the request requires more than one transfer, the DMA unit generates the next memory address and initiates the next transfer. Using this mechanism, a DMA unit can complete an entire transfer, which may be thousands of bytes in length, without bothering the processor. Many DMA controllers contain some memory to allow them to deal flexi­bly either with delays in transfer or with those incurred while waiting to become the master. 3. Once the DMA transfer is complete, the controller interrupts the processor, which can then determine by interrogating the DMA device or examining memory whether the entire operation completed successfully. There may be multiple DMA devices in a computer system. For example, in a system with a single processor-memory bus and multiple I/O buses, each I/O bus controller will often contain a DMA processor that handles any transfers between a device on the I/O bus and the memory. Unlike either polling or interrupt-driven I/O, DMA can be used to interface a hard disk without consuming all the processor cycles for a single I/O. Of course, if the processor is also contending for memory, it will be delayed when the memory is busy doing a DMA transfer. By using caches, the processor can avoid having to access memory most of the time, thereby leaving most of the memory bandwidth free for use by I/O devices. Elaboration: To further reduce the need to interrupt the processor and occupy it in handling an I/O request that may involve doing several actual operations, the I/O con­ troller can be made more intelligent. Intelligent controllers are often called I/O proces­ sors (as well as I/O controllers or channel controllers). These specialized processors basically execute a series of I/O operations, called an I/O program. The program may be stored in the I/O processor, or it may be stored in memory and fetched by the I/O processor. When using an I/O processor, the operating system typically sets up an I/O program that indicates the I/O operations to be done as well as the size and transfer address for any reads or writes. The I/O processor then takes the operations from the I/O program and interrupts the processor only when the entire program is completed. DMA processors are essentially special-purpose processors (usually single-chip and nonprogrammable), while I/O processors are often implemented with general-purpose microprocessors, which run a specialized I/O program. master A unit on the I/O interconnect that can initiate transfer ­requests. 6.6 Interfacing I/O Devices to the Processor, Memory, and Operating System 593
Hennesey_Page_591_Chunk591
594 Chapter 6 Storage and Other I/O Topics Direct Memory Access and the Memory System When DMA is incorporated into an I/O system, the relationship between the mem­ory system and processor changes. Without DMA, all accesses to the mem­ory system come from the processor and thus proceed through address trans­lation and cache access as if the processor generated the references. With DMA, there is another path to the memory system—one that does not go through the address translation mechanism or the cache hierarchy. This difference generates some problems in both virtual memory systems and systems with caches. These problems are usually solved with a combination of hardware techniques and soft­ware support. The difficulties in having DMA in a virtual memory system arise because pages have both a physical and a virtual address. DMA also creates problems for systems with caches, because there can be two copies of a data item: one in the cache and one in memory. Because the DMA processor issues memory requests directly to the memory rather than through the processor cache, the value of a memory loca­tion seen by the DMA unit and the processor may differ. Consider a read from disk that the DMA unit places directly into memory. If some of the locations into which the DMA writes are in the cache, the processor will receive the old value when it does a read. Similarly, if the cache is write-back, the DMA may read a value directly from memory when a newer value is in the cache, and the value has not been written back. This is called the stale data problem or coherence problem (see Chapter 5). We have looked at three different methods for transferring data between an I/O device and memory. In moving from polling to an interrupt-driven to a DMA interface, we shift the burden for managing an I/O operation from the processor to a progressively more intelligent I/O controller. These methods have the advan­tage of freeing up processor cycles. Their disadvantage is that they increase the cost of the I/O system. Because of this, a given computer ­system can choose which point along this spectrum is appropriate for the I/O devices connected to it. Before discussing the design of I/O systems, let’s look briefly at performance measures of them in the next section. In ranking the three ways of doing I/O, which statements are true? 1. If we want the lowest latency for an I/O operation to a single I/O device, the order is polling, DMA, and interrupt driven. 2. In terms of lowest impact on processor utilization from a single I/O device, the order is DMA, interrupt driven, and polling. Check Yourself
Hennesey_Page_592_Chunk592
In a system with virtual memory, should DMA work with virtual addresses or physical addresses? The obvious problem with virtual addresses is that the DMA unit will need to translate the virtual addresses to physical addresses. The major problem with the use of a physical address in a DMA transfer is that the transfer cannot easily cross a page boundary. If an I/O request crossed a page boundary, then the memory locations to which it was being transferred would not necessar­ily be contiguous in the virtual memory. Consequently, if we use physical addresses, we must constrain all DMA transfers to stay within one page. One method to allow the system to initiate DMA transfers that cross page boundaries is to make the DMA work on virtual addresses. In such a system, the DMA unit has a small number of map entries that provide virtual-to-physical mapping for a transfer. The operating system provides the mapping when the I/O is initiated. By using this mapping, the DMA unit need not worry about the loca­ tion of the virtual pages involved in the transfer. Another technique is for the operating system to break the DMA transfer into a series of transfers, each confined within a single physical page. The transfers are then chained together and handed to an I/O processor or intelligent DMA unit that executes the entire sequence of transfers; alternatively, the operating system can individually request the transfers. Whichever method is used, the operating system must still cooperate by not remapping pages while a DMA transfer involving that page is in progress. The coherency problem for I/O data is avoided by using one of three major tech­ niques. One approach is to route the I/O activity through the cache. This ensures that reads see the latest value while writes update any data in the cache. Routing all I/O through the cache is expensive and potentially has a large negative perfor­ mance impact on the processor, since the I/O data is rarely used immediately and may displace useful data that a running program needs. A second choice is to have the OS selectively invalidate the cache for an I/O read or force write-backs to occur for an I/O write (often called cache flushing). This approach requires some small amount of hardware support and is probably more efficient if the software can perform the function easily and efficiently. Because this flushing of large parts of the cache need only happen on DMA block accesses, it will be relatively infre­quent. The third approach is to provide a hardware mechanism for selectively flushing (or invalidating) cache entries. Hardware invalidation to ensure cache coherence is typical in multiprocessor systems, and the same technique can be used for I/O; Chapter 5 discusses this topic in detail. Hardware/ Software Interface Hardware/ Software Interface 6.6 Interfacing I/O Devices to the Processor, Memory, and Operating System 595
Hennesey_Page_593_Chunk593
596 Chapter 6 Storage and Other I/O Topics 6.7 I/O Performance Measures: Examples from Disk and File Systems How should we compare I/O systems? This is a complex question, because I/O performance depends on many aspects of the system, and different applications stress different aspects of the I/O system. Furthermore, a design can make com­ plex tradeoffs between response time and throughput, making it impossible to measure just one aspect in isolation. For example, handling a request as early as possible generally minimizes response time, although greater throughput can be achieved if we try to handle related requests together. Accordingly, we may increase throughput on a disk by grouping requests that access locations that are close together. Such a policy will increase the response time for some requests, probably leading to a larger variation in response time. Although throughput will be higher, some benchmarks constrain the maximum response time to any request, making such optimizations potentially problematic. In this section, we give some examples of measurements proposed for deter­ mining the performance of storage systems. These benchmarks are affected by a variety of system features, including the disk technology, the way disks are con­ nected, the memory system, the processor, and the file system provided by the operating system. Before we discuss these benchmarks, we need to address a confusing point about terminology and units. The performance of I/O systems depends on the rate at which the system transfers data. The transfer rate depends on the clock rate, which is typically given in GHz = 109 cycles per second. The transfer rate is usually quoted in GB/sec. In I/O systems, GBs are measured using base 10 (i.e., 1 GB = 109 = 1,000,000,000 bytes), unlike main memory where base 2 is used (i.e., 1 GB = 230 = 1,073,741,824 bytes). In addition to adding confusion, this difference introduces the need to convert between base 10 (1K = 1000) and base 2 (1K = 1024), because many I/O accesses are for data blocks that have a size that is a power of 2. Rather than complicate all our examples by accurately converting one of the two measurements, we make note here of this distinction and the fact that treating the two measures as if the units were identical introduces a small error. We illus­ trate this error in Section 6.12. Transaction Processing I/O Benchmarks Transaction processing (TP) applications involve both a response time require­ ment and a performance measurement based on throughput. Furthermore, most of the I/O accesses are small. Because of this, TP applications are chiefly con­cerned with I/O rate, measured as the number of accesses per second, as opposed to data rate, measured as bytes of data per second. TP applications generally involve changes to a large database, with the system meeting some response time requirements transaction processing A type of application that ­involves han­dling small short operations (called transactions) that typi­cally require both I/O and com­putation. Transaction processing applications typi­cally have both response time requirements and a perfor­ mance measurement based on the throughput of transactions. I/O rate Performance measure of I/Os per unit time, such as reads per second. data rate Performance mea­sure of bytes per unit time, such as GB/second.
Hennesey_Page_594_Chunk594
as well as gracefully handling certain types of failures. These applications are extremely critical and cost-sensitive. For example, banks normally use TP systems because they are concerned about a range of characteristics. These include making sure transactions aren’t lost, handling transactions quickly, and minimizing the cost of processing each transaction. Although dependability in the face of failure is an absolute requirement in such systems, both response time and throughput are critical to building cost-effective systems. A number of transaction processing benchmarks have been developed. The best-known set of benchmarks is a series developed by the Transaction Processing Council (TPC). TPC-C, initially created in 1992, simulates a complex query environment. TPC-H models ad hoc decision support—the queries are unrelated, and knowl­edge of past queries cannot be used to optimize future queries; the result is that query execution times can be very long. TPC-W is a Web-based transaction benchmark that simulates the activities of a business-oriented transactional Web server. It exercises the database system as well as the underlying Web server soft­ware. TPC-App is an application server and Web services benchmark. The most recent is TPC-E, which simulates the transaction processing workload of a broker­age firm. The TPC benchmarks are described at www.tpc.org. All the TPC benchmarks measure performance in transactions per second. In addition, they include a response time requirement, so that throughput perfor­ mance is measured only when the response time limit is met. To model real-world systems, higher transaction rates are also associated with larger systems, both in terms of users and the size of the database to which the transactions are applied. Hence, storage capacity must scale with performance. Finally, the system cost for a benchmark system must also be included, allowing accurate comparisons of cost/ performance. File System and Web I/O Benchmarks In addition to processor benchmarks, SPEC offers both a file server benchmark (SPECSFS) and a Web server benchmark (SPECWeb). SPECSFS is a benchmark for measuring NFS (Network File System) performance using a script of file server requests; it tests the performance of the I/O system, including both disk and net­ work I/O, as well as the processor. SPECSFS is a throughput-oriented benchmark but with important response time requirements. SPECWeb is a Web server bench­ mark that simulates multiple clients requesting both static and dynamic pages from a server, as well as clients posting data to the server (see Chapter 1). The most recent SPEC effort is to measure power. SPECPower measures power and performance characteristics of small servers. Sun recently announced filebench, a file system benchmark frame­work. Instead of a standard workload, it provides a language that lets you describe the workload you’d like to run on your file systems. However, there are examples of file workloads that are supposed to emulate common applications of file sys­tems. 6.7 I/O Performance Measures: Examples from Disk and File Systems 597
Hennesey_Page_595_Chunk595
598 Chapter 6 Storage and Other I/O Topics Are the following true or false? Unlike processor benchmarks, I/O benchmarks 1. concentrate on throughput rather than latency 2. can require that the data set scale in size or number of users to achieve per­ formance milestones 3. often report cost performance 6.8 Designing an I/O System There are two primary types of specifications that designers encounter in I/O sys­ tems: latency constraints and bandwidth constraints. In both cases, knowledge of the traffic pattern affects the design and analysis. Latency constraints involve ensuring that the latency to complete an I/O opera­ tion is bounded by a certain amount. In the simple case, the system may be unloaded, and the designer must ensure that some latency bound is met either because it is critical to the application or because the device must receive certain guaranteed service to prevent errors. Likewise, determining the latency on an unloaded system is relatively easy, since it involves tracing the path of the I/O operation and summing the individual latencies. Finding the average latency (or distribution of latency) under a load is much harder. Such problems are tackled either by queuing theory (when the behavior of the workload requests and I/O service times can be approx­imated by simple distributions) or by simulation (when the behavior of I/O events is complex). Both topics are beyond the limits of this text. Designing an I/O system to meet a set of bandwidth constraints given a work­ load is the other typical problem designers face. Alternatively, the ­designer may be given a partially configured I/O system and be asked to balance the system to main­ tain the maximum bandwidth achievable, as dictated by the preconfigured portion of the system. This latter design problem is a simplified version of the first. The general approach to designing such a system is as follows: 1. Find the weakest link in the I/O system, which is the component in the I/O path that will constrain the design. Depending on the workload, this com­ ponent can be anywhere, including the processors, the memory system, the I/O controllers, or the devices. Both the workload and configuration limits may dictate where the weakest link is located. 2. Configure this component to sustain the required bandwidth. 3. Determine the requirements for the rest of the system and configure them to support this bandwidth. Check Yourself
Hennesey_Page_596_Chunk596
The easiest way to understand this methodology is with an example. We’ll do a simple analysis of the I/O system of the Sun Fire x4150 server in Section 6.10 to show how this methodology works. 6.9 Parallelism and I/O: Redundant Arrays of Inexpensive Disks Amdahl’s law in Chapter 1 reminds us that neglecting I/O in this parallel revolu­ tion is foolhardy. A simple example demonstrates this. Impact of I/O on System Performance Suppose we have a benchmark that executes in 100 seconds of elapsed time, of which 90 seconds is CPU time and the rest is I/O time. Suppose the number of processors doubles every two years, but the processors remain the same speed, and I/O time doesn’t improve. How much faster will our program run at the end of six years? We know that Elapsed time = CPU time + I/O time 100 = 90 + I/O time I/O time = 10 seconds The new CPU times and the resulting elapsed times are computed in the fol­ lowing table. EXAMPLE ANSWER After n years CPU time I/O time Elapsed time % I/O time 0 years 90 seconds 10 seconds 100 seconds 10% 2 years ​ 90  2 ​ = 45 seconds 10 seconds 55 seconds 18% 4 years ​ 45  2 ​ = 23 seconds 10 seconds 33 seconds 31% 6 years ​ 23  2 ​ = 11 seconds 10 seconds 21 seconds 47% 6.9 Parallelism and I/O: Redundant Arrays of Inexpensive Disks 599
Hennesey_Page_597_Chunk597
600 Chapter 6 Storage and Other I/O Topics The improvement in CPU performance after six years is ​ 90  11 ​ = 8 However, the improvement in elapsed time is only ​ 100  21 ​ = 4.7 and the I/O time has increased from 10% to 47% of the elapsed time. Hence, the parallel revolution needs to come to I/O as well as to computation, or the effort spent in parallelizing could be squandered whenever programs do I/O, which they all must do. Accelerating I/O performance was the original motivation of disk arrays (see Section 6.14 on the CD). In the late 1980s, the high performance storage of choice was large, expensive disks, such as the larger ones in Figure 6.4. The argument was that by replacing a few large disks with many small disks, performance would improve because there would be more read heads. This shift is a good match for multiple processors as well, since many read/write heads mean the storage system could support many more independent accesses as well as large transfers spread across many disks. That is, you could get both high I/Os per second and high data transfer rates. In addition to higher performance, there could be advantages in cost, power, and floor space, since smaller disks are generally more efficient per gigabyte than larger disks. The flaw in the argument was that disk arrays could make reliability much worse. These smaller, inexpensive drives had lower MTTF ratings than the large drives, but more importantly, by replacing a single drive with, say, 50 small drives, the failure rate would go up by at least a factor of 50! The solution was to add redundancy so that the system could cope with disk failures without losing information. By having many small disks, the cost of extra redundancy to improve dependability is small, relative to the solutions for a few large disks. Thus, dependability was more affordable if you constructed a redundant array of inexpensive disks. This observation led to its name: redundant arrays of inexpensive disks, abbreviated RAID. In retrospect, although its invention was motivated by performance, depen­ dability was the key reason for the widespread popularity of RAID. The parallel revolution has resurfaced the original performance side of the argument for RAID. The rest of this section surveys the options for dependability and their impacts on cost and performance. How much redundancy do you need? Do you need extra information to find the faults? Does it matter how you organize the data and the extra check i­nforma­tion on these disks? The paper that coined the term gave an evolutionary answer to these questions, starting with the simplest but most expensive solution. redundant arrays of ­inexpensive disks (RAID) An ­organization of disks that uses an array of small and inexpen­sive disks so as to increase both performance and reliability.
Hennesey_Page_598_Chunk598
Figure 6.12 shows the evolution and example cost in number of extra check disks. To keep track of the evolution, the authors numbered the stages of RAID, and they are still used today. No Redundancy (RAID 0) Simply spreading data over multiple disks, called striping, automatically forces accesses to several disks. Striping across a set of disks makes the collection appear to software as a single large disk, which simplifies storage management. It also improves performance for large accesses, since many disks can operate at once. Video-editing systems, for example, often stripe their data and may not worry about dependability as much as, say, databases. RAID 0 is something of a misnomer, as there is no redundancy. However, RAID levels are often left to the operator to set when creating a storage system, and RAID 0 is often listed as one of the options. Hence, the term RAID 0 has become widely used. striping Allocation of logically sequential blocks to separate disks to allow higher perfor­mance than a single disk can deliver. FIGURE 6.12 RAID for an example of four data disks showing extra check disks per RAID level and companies that use each level. Figures 6.13 and 6.14 explain the difference between RAID 3, RAID 4, and RAID 5. RAID 0 (No redundancy) Widely used Data disks RAID 1 (Mirroring) EMC, HP(Tandem), IBM RAID 2 (Error detection and correction code) Unused RAID 3 (Bit-interleaved parity) Storage concepts RAID 4 (Block-interleaving parity) Network appliance RAID 5 (Distributed block- interleaved parity) Widely used RAID 6 (P + Q redundancy) Recently popular Redundant check disks 6.9 Parallelism and I/O: Redundant Arrays of Inexpensive Disks 601
Hennesey_Page_599_Chunk599
602 Chapter 6 Storage and Other I/O Topics Mirroring (RAID 1) This traditional scheme for tolerating disk failure, called mirroring or shadowing, uses twice as many disks as does RAID 0. Whenever data is written to one disk, that data is also written to a redundant disk, so that there are always two copies of the information. If a disk fails, the system just goes to the “mirror” and reads its contents to get the desired information. Mirroring is the most expensive RAID solution, since it requires the most disks. Error Detecting and Correcting Code (RAID 2) RAID 2 borrows an error detection and correction scheme most often used for memories (see Appendix C). Since RAID 2 has fallen into disuse, we’ll not describe it here. Bit-Interleaved Parity (RAID 3) The cost of higher availability can be reduced to 1/n, where n is the number of disks in a protection group. Rather than have a complete copy of the original data for each disk, we need only add enough redundant information to restore the lost information on a failure. Reads or writes go to all disks in the group, with one ­extra disk to hold the check information in case there is a failure. RAID 3 is popu­lar in applications with large data sets, such as multimedia and some scientific codes. Parity is one such scheme. Readers unfamiliar with parity can think of the redundant disk as having the sum of all the data in the other disks. When a disk fails, then you subtract all the data in the good disks from the parity disk; the remaining information must be the missing information. Parity is simply the sum modulo two. Unlike RAID 1, many disks must be read to determine the missing data. The assumption behind this technique is that taking longer to recover from failure but spending less on redundant storage is a good tradeoff. Block-Interleaved Parity (RAID 4) RAID 4 uses the same ratio of data disks and check disks as RAID 3, but they access data differently. The parity is stored as blocks and associated with a set of data blocks. In RAID 3, every access went to all disks. However, some applications prefer smaller accesses, allowing independent accesses to occur in parallel. That is the purpose of the RAID levels 4 to 6. Since error detection information in each sector is checked on reads to see if the data is correct, such “small reads” to each disk can occur independently as long as the minimum access is one sector. In the RAID context, a small access goes to just one disk in a protection group while a large access goes to all the disks in a protection group. Writes are another matter. It would seem that each small write would demand that all other disks be accessed to read the rest of the information needed to mirroring Writing the identi­cal data to multiple disks to increase data availability. protection group The group of data disks or blocks that share a common check disk or block.
Hennesey_Page_600_Chunk600