text
stringlengths
139
4.06k
source
stringlengths
16
26
of a register until the instruction updating the register is no longer speculative. Other processors buffer the result, typically in a structure called a reorder buffer, and the actual update to the register file occurs later as part of the commit. Stores to memory must be buffered until commit time either in a store buffer (see Chapter 5) or in the reorder buffer. The commit unit allows the store to write to memory from the buffer when the buffer has a valid address and valid data, and when the store is no longer dependent on predicted branches. Elaboration: Memory accesses benefit from nonblocking caches, which continue servic­ing cache accesses during a cache miss (see Chapter 5). Out-of-order execution processors need the cache design to allow instructions to execute during a miss. State whether the following techniques or components are associated primarily with a software- or hardware-based approach to exploiting ILP. In some cases, the answer may be both. 1. Branch prediction 2. Multiple issue 3. VLIW 4. Superscalar 5. Dynamic scheduling 6. Out-of-order execution 7. Speculation 8. Reorder buffer 9. Register renaming Check Yourself FIGURE 4.73 Record of Intel and Sun Microprocessors in terms of pipeline complexity, number of cores, and power. The Pen­tium 4 pipeline stages do not include the commit stages. If we included them, the Pentium 4 pipelines would be even deeper. Microprocessor Year Clock Rate Pipeline Stages Issue Width Out-of-Order/ Speculation Cores/ Chip Power Intel 486 1989 25 MHz 5 1 No 1 5 W Intel Pentium 1993 66 MHz 5 2 No 1 10 W Intel Pentium Pro 1997 200 MHz 10 3 Yes 1 29 W Intel Pentium 4 Willamette 2001 2000 MHz 22 3 Yes 1 75 W Intel Pentium 4 Prescott 2004 3600 MHz 31 3 Yes 1 103 W Intel Core 2006 2930 MHz 14 4 Yes 2 75 W UltraSPARC IV+ 2005 2100 MHz 14 4 No 1 90 W Sun UltraSPARC T1 (Niagara) 2005 1200 MHz 6 1 No 8 70 W 4.10 Parallelism and Advanced Instruction-Level Parallelism 403
Hennesey_Page_401_Chunk401
404 Chapter 4 The Processor 4.11 Real Stuff: the AMD Opteron X4 (Barcelona) Pipeline Like most modern computers, x86 microprocessors employ sophisticated pipelining approaches. These processors, however, are still faced with the challenge of implementing the complex x86 instruction set, described in Chapter 2. Both AMD and Intel fetch x86 instructions and translate them internal to MIPS-like instructions, which AMD calls RISC operations (Rops) and Intel calls micro- operations. The RISC operations are then executed by a sophisticated, dynamically scheduled, speculative pipeline capable of sustaining an execution rate of three RISC operations per clock cycle in the AMD Opteron X4 (Barcelona). This section focuses on that RISC operation pipeline. When we consider the design of sophisticated, dynamically scheduled proces­ sors, the design of the functional units, the cache and register file, instruction issue, and overall pipeline control become intermingled, making it difficult to separate the datapath from the pipeline. Because of this, many engineers and researchers have adopted the term microarchitecture to refer to the detailed internal architecture of a processor. Figure 4.74 shows the microarchitecture of the X4, focusing on the structures for executing the RISC operations. Another way to look at the X4 is to see the pipeline stages that a typical instruc- tion goes through. Figure 4.75 shows the pipeline structure and the typical number of clock cycles spent in each; of course, the number of clock cycles varies due to the nature of dynamic scheduling as well as the requirements of individual RISC operations. Elaboration: Opteron X4 uses a scheme for resolving antidependences and incorrect specu­lation that uses a reorder buffer together with register renaming. Register renaming explicitly renames the architectural registers in a processor (16 in the case of the 64‑bit version of the x86 architecture) to a larger set of physical registers (72 in the X4). X4 uses register renaming to remove antidependences. Register renaming requires the processor to maintain a map between the architectural registers and the physical registers, indicating which physical register is the most current copy of an architectural register. By keeping track of the renamings that have occurred, register renaming offers another approach to recovery in the event of incor­rect speculation: simply undo the mappings that have occurred since the first incorrectly specu­lated instruction. This will cause the state of the processor to return to the last correctly executed instruction, keeping the correct mapping between the architectural and physical regis­ters. Are the following statements true or false? 1. The Opteron X4 multiple-issue pipeline directly executes x86 instructions. 2. X4 uses dynamic scheduling but no speculation. microarchitecture The orga­nization of the processor, including the major functional units, their interconnection, and control. architectural registers The instruction set of visible registers of a processor; for example, in MIPS, these are the 32 integer and 16 floating- point registers. Check Yourself
Hennesey_Page_402_Chunk402
3. The X4 microarchitecture has many more registers than x86 requires. 4. X4 uses less than half the pipeline stages of the earlier Pentium 4 Prescott (see Figure 4.73). FIGURE 4.74 The microarchitecture of AMD Opteron X4. The extensive queues allow up to 106 RISC operations to be outstanding, includ­ing 24 integer operations, 36 floating point/SSE operations, and 44 loads and stores. The load and store units are actually separated into two parts, with the first part handling address calculation in the Integer ALU units and the second part responsible for the actual memory reference. There is an extensive bypass network among the functional units; since the pipeline is dynamic rather than static, bypassing is done by tagging results and tracking source operands, so as to allow a match when a result is produced for an instruction in one of the queues that needs the result. Instruction prefetch and decode Branch prediction Register file Integer ALU Integer ALU. Multiplier Integer ALU Floating point Adder/ SSE Floating point Multiplier/ SSE Floating point Misc Data cache Instruction cache RISC-operation queue Dispatch and register renaming Integer and floating-point operation queue Load/Store queue Commit unit 4.11 Real Stuff: The AMD Opteron X4 (Barcelona) Pipeline 405
Hennesey_Page_403_Chunk403
406 Chapter 4 The Processor The Opteron X4 combines a 12-stage pipeline and aggressive multiple issue to achieve high performance. By keeping the latencies for back-to-back operations low, the impact of data dependences is reduced. What are the most serious potential per­formance bottlenecks for programs running on this processor? The following list includes some potential performance problems, the last three of which can apply in some form to any high-performance pipelined processor. ■ ■The use of x86 instructions that do not map to a few simple RISC operations ■ ■Branches that are difficult to predict, causing misprediction stalls and restarts when speculation fails ■ ■Long dependences—typically caused by long-running instructions or data cache misses—that lead to stalls ■ ■Performance delays arising in accessing memory (see Chapter 5) that cause the processor to stall 4.12 Advanced Topic: an Introduction to Digital Design Using a Hardware Design Language to Describe and Model a Pipeline and More Pipelining Illustrations Modern digital design is done using hardware description languages and modern computer-aided synthesis tools that can create detailed hardware designs from the descriptions using both libraries and logic synthesis. Entire books are written on such languages and their use in digital design. This section, which appears on the CD, gives a brief introduction and shows how a hardware design language, Verilog in this case, can be used to describe the MIPS control both behaviorally and in a Understanding Program Performance Number of clock cycles Reorder buffer allocation + register renaming Instruction Fetch Scheduling + dispatch unit Decode and translate Execution Data Cache/ Commit RISC-operation queue Reorder buffer 2 2 3 2 2 1 FIGURE 4.75 The Opteron X4 pipeline showing the pipeline flow for a typical instruction and the number of clock cycles for the major steps in the 12-stage pipeline for integer RISC-operations. The floating point execution queue is 17 stages long. The major buffers where RISC-operations wait are also shown.
Hennesey_Page_404_Chunk404
form suitable for hardware synthesis. It then provides a series of behavioral models in Verilog of the MIPS five-stage pipeline. The initial model ignores hazards, and additions to the model highlight the changes for forwarding, data hazards, and branch hazards. We then provide about a dozen illustrations using the single-cycle graphical pipeline representation for readers who want to see more detail on how pipelines work for a few sequences of MIPS instructions. 4.13 Fallacies and Pitfalls Fallacy: Pipelining is easy. Our books testify to the subtlety of correct pipeline execution. Our advanced book had a pipeline bug in its first edition, despite its being reviewed by more than 100 people and being class-tested at 18 universities. The bug was uncovered only when someone tried to build the computer in that book. The fact that the Verilog to describe a pipeline like that in Opteron X4 will be thousands of lines is an indication of the complexity. Beware! Fallacy: Pipelining ideas can be implemented independent of technology. When the number of transistors on-chip and the speed of transistors made a five- stage pipeline the best solution, then the delayed branch (see the first Elaboration on page 381) was a simple solution to control hazards. With longer pipelines, superscalar execution, and dynamic branch prediction, it is now redundant. In the early 1990s, dynamic pipeline scheduling took too many resources and was not required for high performance, but as transistor budgets continued to double and logic became much faster than memory, then multiple functional units and dynamic pipelining made more sense. Today, concerns about power are leading to less aggressive designs. Pitfall: Failure to consider instruction set design can adversely impact pipelining. Many of the difficul­ties of pipelining arise because of instruction set complica­tions. Here are some examples: ■ ■Widely variable instruction lengths and running times can lead to imbal­ance among pipeline stages and severely compli­cate hazard detection in a design pipelined at the instruction set level. This problem was overcome, initially in the DEC VAX 8500 in the late 1980s, using the micropipelined scheme that the Opteron X4 employs today. Of course, the overhead of translation and maintaining correspondence between the micro-operations and the actual instructions remains. ■ ■Sophisticated addressing modes can lead to different sorts of problems. Addressing modes that update registers complicate hazard detection. Other 4.13 Fallacies and Pitfalls 407
Hennesey_Page_405_Chunk405
408 Chapter 4 The Processor addressing modes that require multiple memory accesses sub­stantially complicate pipeline control and make it difficult to keep the pipeline flowing smoothly. Perhaps the best example is the DEC Alpha and the DEC NVAX. In com­parable technology, the newer instruction set architecture of the Alpha allowed an imple­ mentation whose performance is more than twice as fast as NVAX. In another example, Bhandarkar and Clark [1991] compared the MIPS M/2000 and the DEC VAX 8700 by counting clock cycles of the SPEC benchmarks; they ­concluded that although the MIPS M/2000 executes more instructions, the VAX on average executes 2.7 times as many clock cycles, so the MIPS is faster. 4.14 Concluding Remarks As we have seen in this chapter, both the datapath and control for a processor can be designed starting with the instruction set architecture and an understanding of the basic characteristics of the technology. In Section 4.3, we saw how the datapath for a MIPS processor could be constructed based on the architecture and the deci- sion to build a single-cycle implementation. Of course, the underlying technology also affects many design decisions by dictating what components can be used in the datapath, as well as whether a ­single-cycle implementation even makes sense. Pipelining improves throughput but not the inherent execution time, or instruction latency, of instructions; for some instructions, the latency is similar in length to the single-cycle approach. Multiple instruction issue adds additional datapath hardware to allow multiple instructions to begin every clock cycle, but at an increase in effective latency. Pipelining was presented as reducing the clock cycle time of the simple single-cycle datapath. Multiple instruction issue, in com­parison, clearly focuses on reducing clock cycles per instruction (CPI). Pipelining and multiple issue both attempt to exploit instruction-level parallel­ ism. The presence of data and control dependences, which can become hazards, are the primary limitations on how much parallelism can be exploited. Scheduling and speculation, both in hardware and in software, are the primary techniques used to reduce the performance impact of dependences. The switch to longer pipelines, multiple instruction issue, and dynamic sched­ uling in the mid-1990s has helped sustain the 60% per year processor perfor­mance increase that started in the early 1980s. As mentioned in Chapter 1, these micro­ processors preserved the sequential programming model, but they eventu­ally ran into the power wall. Thus, the industry has been forced to try multi­processors, which exploit parallelism at much coarser levels (the subject of Chapter 7). This trend has also caused designers to reassess the power-performance implications Nine-tenths of wisdom con­sists of being wise in time. American proverb instruction latency The inherent execution time for an instruction.
Hennesey_Page_406_Chunk406
of some of the inventions since the mid-1990s, resulting in a simplifi­cation of pipelines in the more recent versions of microarchitectures. To sustain the advances in processing performance via parallel processors, Amdahl’s law suggests that another part of the system will become the bottleneck. That bottleneck is the topic of the next chapter: the memory system. 4.15 Historical Perspective and Further Reading This section, which appears on the CD, discusses the history of the first pipelined processors, the earliest superscalars, and the development of out-of-order and speculative techniques, as well as important developments in the accompanying compiler technology. 4.16 Exercises Contributed by Milos Prvulovic of Georgia Tech Exercise 4.1 Different instructions utilize different hardware blocks in the basic single-cycle implementation. The next three problems in this exercise refer to the following instruction: Instruction Interpretation a. AND Rd,Rs,Rt Reg[Rd] = Reg[Rs] AND Reg[Rt] b. SW Rt,Offs(Rs) Mem[Reg[Rs] + Offs] = Reg[Rt] 4.1.1 [5] <4.1> What are the values of control signals generated by the control in Figure 4.2 for this instruction? 4.1.2 [5] <4.1> Which resources (blocks) perform a useful function for this instruction? 4.1.3 [10] <4.1> Which resources (blocks) produce outputs, but their outputs are not used for this instruction? Which resources produce no outputs for this instruction? 4.16 Exercises 409
Hennesey_Page_407_Chunk407
410 Chapter 4 The Processor Different execution units and blocks of digital logic have different latencies (time needed to do their work). In Figure 4.2 there are seven kinds of major blocks. Laten- cies of blocks along the critical (longest-latency) path for an instruction determine the minimum latency of that instruction. For the remaining three problems in this exercise, assume the following resource latencies: I-Mem Add Mux ALU Regs D-Mem Control a. 200ps 70ps 20ps 90ps 90ps 250ps 40ps b. 750ps 200ps 50ps 250ps 300ps 500ps 300ps 4.1.4 [5] <4.1> What is the critical path for an MIPS AND instruction? 4.1.5 [5] <4.1> What is the critical path for an MIPS load (LD) instruction? 4.1.6 [10] <4.1> What is the critical path for an MIPS BEQ instruction? Exercise 4.2 The basic single-cycle MIPS implementation in Figure 4.2 can only implement some instructions. New instructions can be added to an existing ISA, but the deci- sion whether or not to do that depends, among other things, on the cost and com- plexity such an addition introduces into the processor datapath and control. The first three problems in this exercise refer to this new instruction: Instruction Interpretation a. SEQ Rd,Rs,Rt Reg[Rd] = Boolean value (0 or 1) of (Reg[Rs] == Reg[Rs]) b. LWI Rt,Rd(Rs) Reg[Rt] = Mem[Reg[Rd]+Reg[Rs]] 4.2.1 [10] <4.1> Which existing blocks (if any) can be used for this instruction? 4.2.2 [10] <4.1> Which new functional blocks (if any) do we need for this instruction? 4.2.3 [10] <4.1> What new signals do we need (if any) from the control unit to support this instruction? When processor designers consider a possible improvement to the processor datapath, the decision usually depends on the cost/performance trade-off. In the ­following three problems, assume that we are starting with a datapath from Figure 4.2, where I-Mem, Add, Mux, ALU, Regs, D-Mem, and Control blocks have laten- cies of 400ps, 100ps, 30ps, 120ps, 200ps, 350ps, and 100ps, respectively, and costs of 1000, 30, 10, 100, 200, 2000, and 500, respectively. The remaining three problems in this exercise refer to the following processor improvement:
Hennesey_Page_408_Chunk408
Improvement Latency Cost Benefit a. Add Multiplier to ALU +300ps for ALU +600 for ALU Lets us add MUL instruction. Allows us to execute 5% fewer instructions (MUL no longer emulated). b. Simpler Control +100ps for Control –400 for Control Control becomes slower but cheaper logic. 4.2.4 [10] <4.1> What is the clock cycle time with and without this improvement? 4.2.5 [10] <4.1> What is the speedup achieved by adding this improvement? 4.2.6 [10] <4.1> Compare the cost/performance ratio with and without this improvement. Exercise 4.3 Problems in this exercise refer to the following logic block: Logic Block a. Small Multiplexor (Mux) with four 8-bit data inputs b. Small 8-bit ALU that can do either AND, OR, or NOT 4.3.1 [5] <4.1, 4.2> Does this block contain logic only, flip-flops only, or both? 4.3.2 [20] <4.1, 4.2> Show how this block can be implemented. Use only AND, OR, NOT, and D Flip-Flops. 4.3.3 [10] <4.1, 4.2> Repeat Problem 4.3.2, but the AND and OR gates you use must all be 2-input gates. Cost and latency of digital logic depends on the kinds of basic logic elements (gates) that are available and on the properties of these gates. The remaining three problems in this exercise refer to these gates, latencies, and costs: NOT 2-Input AND or OR Each Additional Input for AND/OR D-Element Latency Cost Latency Cost Latency Cost Latency Cost a. 10ps 2 12ps 4 +2ps +1 30ps 10 b. 20ps 2 40ps 3 +30ps +1 80ps 9 4.16 Exercises 411
Hennesey_Page_409_Chunk409
412 Chapter 4 The Processor 4.3.4 [5] <4.1, 4.2> What is the latency of your implementation from 4.3.2? 4.3.5 [5] <4.1, 4.2> What is the cost of your implementation from 4.3.2? 4.3.6 [20] <4.1, 4.2> Change your design to minimize the latency, then to mini- mize the cost. Compare the cost and latency of these two optimized designs. Exercise 4.4 When implementing a logic expression in digital logic, one must use the available logic gates to implement an operator for which a gate is not available. Problems in this exercise refer to the following logic expressions: Control Signal 1 Control Signal 2 a. (((A AND B) XOR C) OR (A XOR C)) OR (A XOR B) (A XOR B) OR (A XOR C) b. (((A OR B) AND C) OR ((A OR C) OR (A OR B)) (A AND C) OR (B AND C) 4.4.1 [5] <4.2> Implement the logic for the Control signal 1. Your circuit should directly implement the given expression (do not reorganize the expression to “opti- mize” it), using NOT gates and 2-input AND, OR, and XOR gates. 4.4.2 [10] Assuming that all gates have equal latencies, what is the length (in gates) of the critical path in your circuit from 4.4.1? 4.4.3 [10] <4.2> When multiple logic expressions are implemented, it is possible to reduce implementation cost by using the same signals in more than one expres- sion. Repeat 4.4.1, but implement both Control signal 1 and Control signal 2, and try to “share” circuitry between expressions whenever possible. For the remaining three problems in this exercise, we assume that the following basic digital logic elements are available, and that their latency and cost are as follows: NOT 2-Input AND 2-Input OR 2-Input XOR Latency Cost Latency Cost Latency Cost Latency Cost a. 10ps 2 12ps 4 20ps 5 30ps 10 b. 20ps 2 40ps 3 50ps 3 50ps 8 4.4.4 [10] <4.2> What is the length of the critical path in your circuit from 4.4.3? 4.4.5 [10] <4.2> What is the cost of your circuit from 4.4.3?
Hennesey_Page_410_Chunk410
4.4.6 [10] <4.2> What fraction of the cost was saved in your circuit from 4.4.3 by implementing these two control signals together instead of separately? Exercise 4.5 The goal of this exercise is to help you familiarize yourself with the design and operation of sequential logical circuits. Problems in this exercise refer to this ALU operation: ALU Operation a. Add (X+Y) b. Subtract-one (X–1) in 2’s complement 4.5.1 [20] <4.2> Design a circuit with 1-bit data inputs and a 1-bit data output that accomplishes this operation serially, starting with the least-significant bit. In a serial implementation, the circuit is processing input operands bit by bit, generat- ing output bits one by one. For example, a serial AND circuit is simply an AND gate; in cycle N we give it the Nth bit from each of the operands and we get the Nth bit of the result. In addition to data inputs, the circuit has a Clk (clock) input and a “Start” input that is set to 1 only in the very first cycle of the operation. In your design, you can use D Flip-Flops and NOT, AND, OR, and XOR gates. 4.5.2 [20] <4.2> Repeat 4.5.1, but now design a circuit that accomplishes this operation 2 bits at a time. In the rest of this exercise, we assume that the following basic digital logic elements are available, and that their latency and cost are as follows: NOT AND OR XOR D-Element Latency Cost Latency Cost Latency Cost Latency Cost Latency Cost a. 10ps 2 12ps 4 12ps 4 14ps 6 30ps 10 b. 50ps 1 100ps 2 90ps 2 120ps 3 160ps 2 The time given for a D-element is its setup time. The data input of a flip-flop must have the correct value one setup-time before the clock edge (end of clock cycle) that stores that value into the flip-flop. 4.5.3 [10] <4.2> What is the cycle time for the circuit you designed in 4.5.1? How long does it take to perform the 32-bit operation? 4.5.4 [10] <4.2> What is the cycle time for the circuit you designed in 4.5.2? What is the speedup achieved by using this circuit instead of the one from 4.5.1 for a 32-bit operation? 4.16 Exercises 413
Hennesey_Page_411_Chunk411
414 Chapter 4 The Processor 4.5.5 [10] <4.2> Compute the cost for the circuit you designed in 4.5.1, and then for the circuit you designed in 4.5.2. 4.5.6 [5] <4.2> Compare cost/performance ratios for the two circuits you designed in 4.5.1 and 4.5.2. For this problem, performance of a circuit is the inverse of the time needed to perform a 32-bit operation. Exercise 4.6 Problems in this exercise assume that logic blocks needed to implement a proces- sor’s datapath have the following latencies: I-Mem Add Mux ALU Regs D-Mem Sign-Extend Shift-Left-2 a. 200ps 70ps 20ps 90ps 90ps 250ps 15ps 10ps b. 750ps 200ps 50ps 250ps 300ps 500ps 100ps 0ps 4.6.1 [10] <4.3> If the only thing we need to do in a processor is fetch consecu- tive instructions (Figure 4.6), what would the cycle time be? 4.6.2 [10] <4.3> Consider a datapath similar to the one in Figure 4.11, but for a processor that only has one type of instruction: unconditional PC-relative branch. What would the cycle time be for this datapath? 4.6.3 [10] <4.3> Repeat 4.6.2, but this time we need to support only conditional PC-relative branches. The remaining three problems in this exercise refer to the following logic block (resource) in the datapath: Resource a. Shift-left-2 b. Registers 4.6.4 [10] <4.3> Which kinds of instructions require this resource? 4.6.5 [20] <4.3> For which kinds of instructions (if any) is this resource on the critical path? 4.6.6 [10] <4.3> Assuming that we only support BEQ and ADD instructions, dis- cuss how changes in the given latency of this resource affect the cycle time of the processor. Assume that the latencies of other resources do not change.
Hennesey_Page_412_Chunk412
Exercise 4.7 In this exercise we examine how latencies of individual components of the data- path affect the clock cycle time of the entire datapath, and how these components are utilized by instructions. For problems in this exercise, assume the following latencies for logic blocks in the datapath: I-Mem Add Mux ALU Regs D-Mem Sign-Extend Shift-Left-2 a. 200ps 70ps 20ps 90ps 90ps 250ps 15ps 10ps b. 750ps 200ps 50ps 250ps 300ps 500ps 100ps 5ps 4.7.1 [10] <4.3> What is the clock cycle time if the only types of instructions we need to support are ALU instructions (ADD, AND, etc.)? 4.7.2 [10] <4.3> What is the clock cycle time if we only have to support LW instructions? 4.7.3 [20] <4.3> What is the clock cycle time if we must support ADD, BEQ, LW, and SW instructions? For the remaining problems in this exercise, assume that there are no pipeline stalls and that the breakdown of executed instructions is as follows: ADD ADDI NOT BEQ LW SW a. 20% 20% 0% 25% 25% 10% b. 30% 10% 0% 10% 30% 20% 4.7.4 [10] <4.3> In what fraction of all cycles is the data memory used? 4.7.5 [10] <4.3> In what fraction of all cycles is the input of the sign-extend circuit needed? What is this circuit doing in cycles in which its input is not needed? 4.7.6 [10] <4.3> If we can improve the latency of one of the given datapath com- ponents by 10%, which component should it be? What is the speedup from this improvement? Exercise 4.8 When silicon chips are fabricated, defects in materials (e.g., silicon) and manufac- turing errors can result in defective circuits. A very common defect is for one wire to affect the signal in another. This is called a cross-talk fault. A special class of 4.16 Exercises 415
Hennesey_Page_413_Chunk413
416 Chapter 4 The Processor cross-talk faults is when a signal is connected to a wire that has a constant logical value (e.g., a power supply wire). In this case we have a stuck-at-0 or a stuck-at-1 fault, and the affected signal always has a logical value of 0 or 1, respectively. The following problems refer to the following signal from Figure 4.24: Signal a. Registers, input Write Register, bit 0 b. Add unit in upper right corner, ALU result, bit 0 4.8.1 [10] <4.3, 4.4> Let us assume that processor testing is done by filling the PC, registers, and data and instruction memories with some values (you can choose which values), letting a single instruction execute, then reading the PC, memories, and registers. These values are then examined to determine if a particular fault is present. Can you design a test (values for PC, memories, and registers) that would determine if there is a stuck-at-0 fault on this signal? 4.8.2 [10] <4.3, 4.4> Repeat 4.8.1 for a stuck-at-1 fault. Can you use a sin- gle test for both stuck-at-0 and stuck-at-1? If yes, explain how; if no, explain why not. 4.8.3 [60] <4.3, 4.4> If we know that the processor has a stuck-at-1 fault on this signal, is the processor still usable? To be usable, we must be able to convert any program that executes on a normal MIPS processor into a program that works on this processor. You can assume that there is enough free instruction memory and data memory to let you make the program longer and store additional data. Hint: the processor is usable if every instruction “broken” by this fault can be replaced with a sequence of “working” instructions that achieve the same effect. The following problems refer to the following fault: Fault a. Stuck-at-0 b. Becomes 0 if RegDst control signal is 0, no fault otherwise 4.8.4 [10] <4.3, 4.4> Repeat 4.8.1, but now the fault to test for is whether the “MemRead” control signal has this fault. 4.8.5 [10] <4.3, 4.4> Repeat 4.8.1, but now the fault to test for is whether the “Jump” control signal has this fault.
Hennesey_Page_414_Chunk414
4.8.6 [40] <4.3, 4.4> Using a single test described in 4.8.1, we can test for faults in several different signals, but typically not all of them. Describe a series of tests to look for this fault in all Mux outputs (every output bit from each of the five Muxes). Try to do this with as few single-instruction tests as possible. Exercise 4.9 In this exercise we examine the operation of the single-cycle datapath for a particu- lar instruction. Problems in this exercise refer to the following MIPS instruction: Instruction a. SW R4,–100(R16) b. SLT R1,R2,R3 4.9.1 [10] <4.4> What is the value of the instruction word? 4.9.2 [10] <4.4> What is the register number supplied to the register file’s “Read register 1” input? Is this register actually read? How about “Read register 2”? 4.9.3 [10] <4.4> What is the register number supplied to the register file’s “Write register” input? Is this register actually written? Different instructions require different control signals to be asserted in the data- path. The remaining problems in this exercise refer to the following two control signals from Figure 4.24: Control Signal 1 Control Signal 2 a. ALUSrc Branch b. Jump RegDst 4.9.4 [20] <4.4> What is the value of these two signals for this instruction? 4.9.5 [20] <4.4> For the datapath from Figure 4.24, draw the logic diagram for the part of the control unit that implements just the first signal. Assume that we only need to support LW, SW, BEQ, ADD, and J (jump) instructions. 4.9.6 [20] <4.4> Repeat 4.9.5, but now implement both of these signals. 4.16 Exercises 417
Hennesey_Page_415_Chunk415
418 Chapter 4 The Processor Exercise 4.10 In this exercise we examine how the clock cycle time of the processor affects the design of the control unit, and vice versa. Problems in this exercise assume that the logic blocks used to implement the datapath have the following latencies: I-Mem Add Mux ALU Regs D-Mem Sign-Extend Shift-Left-2 ALU Ctrl a. 200ps 70ps 20ps 90ps 90ps 250ps 15ps 10ps 30ps b. 750ps 200ps 50ps 250ps 300ps 500ps 100ps 5ps 70ps 4.10.1 [10] <4.2, 4.4> To avoid lengthening the critical path of the datapath shown in Figure 4.24, how much time can the control unit take to generate the MemWrite signal? 4.10.2 [20] <4.2, 4.4> Which control signal in Figure 4.24 has the most slack and how much time does the control unit have to generate it if it wants to avoid being on the critical path? 4.10.3 [20] <4.2, 4.4> Which control signal in Figure 4.24 is the most critical to generate quickly and how much time does the control unit have to generate it if it wants to avoid being on the critical path? The remaining problems in this exercise assume that the time needed by the con- trol unit to generate individual control signals is as follows RegDst Jump Branch MemRead MemtoReg ALUOp MemWrite ALUSrc RegWrite a. 500ps 500ps 450ps 200ps 450ps 200ps 500ps 100ps 500ps b. 1100ps 1000ps 1100ps 800ps 1200ps 300ps 1300ps 400ps 1200ps 4.10.4 [20] <4.4> What is the clock cycle time of the processor? 4.10.5 [20] <4.4> If you can speed up the generation of control signals, but the cost of the entire processor increases by $1 for each 5ps improvement of a sin- gle control signal, which control signals would you speed up and by how much to maximize performance? What is the cost (per processor) of this performance improvement? 4.10.6 [30] <4.4> If the processor is already too expensive, instead of paying to speed it up as we did in 4.10.5, we want to minimize its cost without further slow- ing it down. If you can use slower logic to implement control signals, saving $1 of the processor cost for each 5ps you add to the latency of a single control signal, which control signals would you slow down and by how much to reduce the pro- cessor’s cost without slowing it down?
Hennesey_Page_416_Chunk416
Exercise 4.11 In this exercise we examine in detail how an instruction is executed in a single-cycle datapath. Problems in this exercise refer to a clock cycle in which the processor fetches the following instruction word: Instruction word a. 10101100011000100000000000010100 b. 00000000100000100000100000101010 4.11.1 [5] <4.4> What are the outputs of the sign-extend and the jump “Shift left 2” unit (near the top of Figure 4.24) for this instruction word? 4.11.2 [10] <4.4> What are the values of the ALU control unit’s inputs for this instruction? 4.11.3 [10] <4.4> What is the new PC address after this instruction is executed? Highlight the path through which this value is determined. The remaining problems in this exercise assume that data memory is all zeros and that the processor’s registers have the following values at the beginning of the cycle in which the above instruction word is fetched: R0 R1 R2 R3 R4 R5 R6 R8 R12 R31 a. 0 –1 2 –3 –4 10 6 8 2 –16 b. 0 256 –128 19 –32 13 –6 –1 16 –2 4.11.4 [10] <4.4> For each Mux, show the values of its data output during the execution of this instruction and these register values. 4.11.5 [10] <4.4> For the ALU and the two add units, what are their data input values? 4.11.6 [10] <4.4> What are the values of all inputs for the “Registers” unit? Exercise 4.12 In this exercise, we examine how pipelining affects the clock cycle time of the pro- cessor. Problems in this exercise assume that individual stages of the datapath have the following latencies: IF ID EX MEM WB a. 250ps 350ps 150ps 300ps 200ps b. 200ps 170ps 220ps 210ps 150ps 4.16 Exercises 419
Hennesey_Page_417_Chunk417
420 Chapter 4 The Processor 4.12.1 [5] <4.5> What is the clock cycle time in a pipelined and non-pipelined processor? 4.12.2 [10] <4.5> What is the total latency of an LW instruction in a pipelined and non-pipelined processor? 4.12.3 [10] <4.5> If we can split one stage of the pipelined datapath into two new stages, each with half the latency of the original stage, which stage would you split and what is the new clock cycle time of the processor? The remaining problems in this exercise assume that instructions executed by the processor are broken down as follows: ALU BEQ LW SW a. 45% 20% 20% 15% b. 55% 15% 15% 15% 4.12.4 [10] <4.5> Assuming there are no stalls or hazards, what is the utilization of the data memory? 4.12.5 [10] <4.5> Assuming there are no stalls or hazards, what is the utilization of the write-register port of the “Registers” unit? 4.12.6 [30] <4.5> Instead of a single-cycle organization, we can use a multi- cycle organization where each instruction takes multiple cycles but one instruction finishes before another is fetched. In this organization, an instruction only goes through stages it actually needs (e.g., ST only takes 4 cycles because it does not need the WB stage). Compare clock cycle times and execution times with single-cycle, multi-cycle, and pipelined organization. Exercise 4.13 In this exercise, we examine how data dependences affect execution in the basic 5-stage pipeline described in Section 4.5. Problems in this exercise refer to the fol- lowing sequence of instructions: Instruction Sequence a. SW R16,–100(R6) LW R4,8(R16) ADD R5,R4,R4 b. OR R1,R2,R3 OR R2,R1,R4 OR R1,R1,R2
Hennesey_Page_418_Chunk418
4.13.1 [10] <4.5> Indicate dependences and their type. 4.13.2 [10] <4.5> Assume there is no forwarding in this pipelined processor. Indicate hazards and add NOP instructions to eliminate them. 4.13.3 [10] <4.5> Assume there is full forwarding. Indicate hazards and add NOP instructions to eliminate them. Without Forwarding With Full Forwarding With ALU-ALU Forwarding Only a. 250ps 300ps 290ps b. 180ps 240ps 210ps 4.13.4 [10] <4.5> What is the total execution time of this instruction sequence without forwarding and with full forwarding? What is the speedup achieved by adding full forwarding to a pipeline that had no forwarding? 4.13.5 [10] <4.5> Add NOP instructions to this code to eliminate hazards if there is ALU-ALU forwarding only (no forwarding from the MEM to the EX stage). 4.13.6 [10] <4.5> What is the total execution time of this instruction sequence with only ALU-ALU forwarding? What is the speedup over a no-forwarding pipe- line? Exercise 4.14 In this exercise, we examine how resource hazards, control hazards, and ISA design can affect pipelined execution. Problems in this exercise refer to the following frag- ment of MIPS code: Instruction sequence a. SW R16,12(R6) LW R16,8(R6) BEQ R5,R4,Label ; Assume R5 != R4 ADD R5,R1,R4 SLT R5,R15,R4 b. SW R2,0(R3) OR R1,R2,R3 BEQ R2,R0,Label ; Assume R2 == R0 OR R2,R2,R0 Label: ADD R1,R4,R3 4.14.1 [10] <4.5> For this problem, assume that all branches are perfectly pre- dicted (this eliminates all control hazards) and that no delay slots are used. If we 4.16 Exercises 421
Hennesey_Page_419_Chunk419
422 Chapter 4 The Processor only have one memory (for both instructions and data), there is a structural haz- ard every time we need to fetch an instruction in the same cycle in which another instruction accesses data. To guarantee forward progress, this hazard must always be resolved in favor of the instruction that accesses data. What is the total execution time of this instruction sequence in the 5-stage pipeline that only has one memory? We have seen that data hazards can be eliminated by adding NOPs to the code. Can you do the same with this structural hazard? Why? 4.14.2 [20] <4.5> For this problem, assume that all branches are perfectly pre- dicted (this eliminates all control hazards) and that no delay slots are used. If we change load/store instructions to use a register (without an offset) as the address, these instructions no longer need to use the ALU. As a result, MEM and EX stages can be overlapped and the pipeline has only 4 stages. Change this code to accom- modate this changed ISA. Assuming this change does not affect clock cycle time, what speedup is achieved in this instruction sequence? 4.14.3 [10] <4.5> Assuming stall-on-branch and no delay slots, what speedup is achieved on this code if branch outcomes are determined in the ID stage, relative to the execution where branch outcomes are determined in the EX stage? The remaining problems in this exercise assume that individual pipeline stages have the following latencies: IF ID EX MEM WB a. 200ps 120ps 150ps 190ps 100ps b. 150ps 200ps 200ps 200ps 100ps 4.14.4 [10] <4.5> Given these pipeline stage latencies, repeat the speedup cal- culation from 4.14.2, but take into account the (possible) change in clock cycle time. When EX and MEM are done in a single stage, most of their work can be done in parallel. As a result, the resulting EX/MEM stage has a latency that is the larger of the original two, plus 20ps needed for the work that could not be done in parallel. 4.14.5 [10] <4.5> Given these pipeline stage latencies, repeat the speedup calculation from 4.14.3, taking into account the (possible) change in clock cycle time. Assume that the latency ID stage increases by 50% and the latency of the EX stage decreases by 10ps when branch outcome resolution is moved from EX to ID. 4.14.6 [10] <4.5> Assuming stall-on-branch and no delay slots, what is the new clock cycle time and execution time of this instruction sequence if BEQ address
Hennesey_Page_420_Chunk420
computation is moved to the MEM stage? What is the speedup from this change? Assume that the latency of the EX stage is reduced by 20ps and the latency of the MEM stage is unchanged when branch outcome resolution is moved from EX to MEM. Exercise 4.15 In this exercise, we examine how the ISA affects pipeline design. Problems in this exercise refer to the following new instruction: a. ADDM Rd,Rt+Offs(Rs) Rd=Rt+Mem[Offs+Rs] b. BEQM Rd,Rt,Offs(Rs) if Rt=Mem[Offs+Rs] then PC = Rd 4.15.1 [20] <4.5> What must be changed in the pipelined datapath to add this instruction to the MIPS ISA? 4.15.2 [10] <4.5> Which new control signals must be added to your pipeline from 4.15.1? 4.15.3 [20] <4.5, 4.13> Does support for this instruction introduce any new haz- ards? Are stalls due to existing hazards made worse? 4.15.4 [10] <4.5, 4.13> Give an example of where this instruction might be useful and a sequence of existing MIPS instructions that are replaced by this instruction. 4.15.5 [10] <4.5, 4.11, 4.13> If this instruction already exists in a legacy ISA, explain how it would be executed in a modern processor like AMD Barcelona. The last problem in this exercise assumes that each use of the new instruction replaces the given number of original instructions, that the replacement can be made once in the given number of original instructions, and that each time the new instruction is executed the given number of extra stall cycles is added to the program’s execution time: Replaces Once in every Extra Stall Cycles a. 2 30 2 b. 3 40 1 4.15.6 [10] <4.5> What is the speedup achieved by adding this new instruction? In your calculation, assume that the CPI of the original program (without the new instruction) is 1. 4.16 Exercises 423
Hennesey_Page_421_Chunk421
424 Chapter 4 The Processor Exercise 4.16 The first three problems in this exercise refer to the following MIPS instruction: Instruction a. SW R16,–100(R6) b. OR R2,R1,R0 4.16.1 [5] <4.6> As this instruction executes, what is kept in each register located between two pipeline stages? 4.16.2 [5] <4.6> Which registers need to be read, and which registers are actually read? 4.16.3 [5] <4.6> What does this instruction do in the EX and MEM stages? The remaining three problems in this exercise refer to the following loop. Assume that perfect branch prediction is used (no stalls due to control hazards), that there are no delay slots, and that the pipeline has full forwarding support. Also assume that many iterations of this loop are executed before the loop exits. Loop a. Loop: ADD R1,R2,R1 LW R2,0(R1) LW R2,16(R2) SLT R1,R2,R4 BEQ R1,R9,Loop b. Loop: LW R1,0(R1) AND R1,R1,R2 LW R1,0(R1) LW R1,0(R1) BEQ R1,R0,Loop 4.16.4 [10] <4.6> Show a pipeline execution diagram for the third iteration of this loop, from the cycle in which we fetch the first instruction of that iteration up to (but not including) the cycle in which we can fetch the first instruction of the next iteration. Show all instructions that are in the pipeline during these cycles (not just those from the third iteration). 4.16.5 [10] <4.6> How often (as a percentage of all cycles) do we have a cycle in which all five pipeline stages are doing useful work? 4.16.6 [10] <4.6> At the start of the cycle in which we fetch the first instruction of the third iteration of this loop, what is stored in the IF/ID register?
Hennesey_Page_422_Chunk422
Exercise 4.17 Problems in this exercise assume that instructions executed by a pipelined proces- sor are broken down as follows: ADD BEQ LW SW a. 40% 30% 25% 5% b. 60% 10% 20% 10% 4.17.1 [5] <4.6> Assuming there are no stalls and that 60% of all conditional branches are taken, in what percentage of clock cycles does the branch adder in the EX stage generate a value that is actually used? 4.17.2 [5] <4.6> Assuming there are no stalls, how often (percentage of all cycles) do we actually need to use all three register ports (two reads and a write) in the same cycle? 4.17.3 [5] <4.6> Assuming there are no stalls, how often (percentage of all cycles) do we use the data memory? Each pipeline stage in Figure 4.33 has some latency. Additionally, pipelining introduces registers between stages (Figure 4.35), and each of these adds an addi- tional latency. The remaining problems in this exercise assume the following latencies for logic within each pipeline stage and for each register between two stages: IF ID EX MEM WB Pipeline Register a. 200ps 120ps 150ps 190ps 100ps 15ps b. 150ps 200ps 200ps 200ps 100ps 15ps 4.17.4 [5] <4.6> Assuming there are no stalls, what is the speedup achieved by pipelining a single-cycle datapath? 4.17.5 [10] <4.6> We can convert all load/store instructions into register-based (no offset) and put the memory access in parallel with the ALU. What is the clock cycle time if this is done in the single-cycle and in the pipelined datapath? Assume that the latency of the new EX/MEM stage is equal to the longer of their latencies. 4.17.6 [10] <4.6> The change in 4.17.5 requires many existing LW/SW instruc- tions to be converted into two-instruction sequences. If this is needed for 50% of these instructions, what is the overall speedup achieved by changing from the 5-stage pipeline to the 4-stage pipeline where EX and MEM are done in parallel? 4.16 Exercises 425
Hennesey_Page_423_Chunk423
426 Chapter 4 The Processor Exercise 4.18 The first three problems in this exercise refer to the execution of the following instruction in the pipelined datapath from Figure 4.51, and assume the following clock cycle time, ALU latency, and Mux latency: Instruction Clock Cycle Time ALU Latency Mux Latency a. LW R1,32(R2) 50ps 30ps 15ps b. OR R1,R5,R6 200ps 170ps 25ps 4.18.1 [10] <4.6> For each stage of the pipeline, what are the values of the control signals asserted by this instruction in that pipeline stage? 4.18.2 [10] <4.6, 4.7> How much time does the control unit have to generate the ALUSrc control signal? Compare this to a single-cycle organization. 4.18.3 What is the value of the PCSrc signal for this instruction? This signal is generated early in the MEM stage (only a single AND gate). What would be a rea- son in favor of doing this in the EX stage? What is the reason against doing it in the EX stage? The remaining problems in this exercise refer to the following signals from ­Figure 4.48: Signal 1 Signal 2 a. ALUSrc PCSrc b. Branch RegWrite 4.18.4 [5] <4.6> For each of these signals, identify the pipeline stage in which it is generated and the stage in which it is used. 4.18.5 [5] <4.6> For which MIPS instruction(s) are both of these signals set to 1? 4.18.6 [10] <4.6> One of these signals goes back through the pipeline. Which signal is it? Is this a time-travel paradox? Explain. Exercise 4.19 This exercise is intended to help you understand the cost/complexity/performance trade-offs of forwarding in a pipelined processor. Problems in this exercise refer to pipelined datapaths from Figure 4.45. These problems assume that, of all the instructions executed in a processor, the following fraction of these instructions
Hennesey_Page_424_Chunk424
have a particular type of RAW data dependence. The type of RAW data dependence is identified by the stage that produces the result (EX or MEM) and the instruction that consumes the result (1st instruction that follows the one that produces the result, 2nd instruction that follows, or both). We assume that the register write is done in the first half of the clock cycle and that register reads are done in the second half of the cycle, so “EX to 3rd” and “MEM to 3rd” dependences are not counted because they cannot result in data hazards. Also, assume that the CPI of the proces- sor is 1 if there are no data hazards. EX to 1st Only MEM to 1st Only EX to 2nd only MEM to 2nd Only EX to 1st and MEM to 2nd Other RAW Dependences a. 5% 20% 5% 10% 10% 10% b. 20% 10% 15% 10% 5% 0% 4.19.1 [10] <4.7> If we use no forwarding, what fraction of cycles are we stalling due to data hazards? 4.19.2 [5] <4.7> If we use full forwarding (forward all results that can be for- warded), what fraction of cycles are we staling due to data hazards? 4.19.3 [10] <4.7> Let us assume that we cannot afford to have three-input Muxes that are needed for full forwarding. We have to decide if it is better to forward only from the EX/MEM pipeline register (next-cycle forwarding) or only from the MEM/WB pipeline register (two-cycle forwarding). Which of the two options results in fewer data stall cycles? The remaining three problems in this exercise refer to the following latencies for individual pipeline stages. For the EX stage, latencies are given separately for a pro- cessor without forwarding and for a processor with different kinds of forwarding. IF ID EX (no FW) EX (full FW) EX (FW from EX/MEM only) EX (FW from MEM/WB only) MEM WB a. 150ps 100ps 120ps 150ps 140ps 130ps 120ps 100ps b. 300ps 200ps 300ps 350ps 330ps 320ps 290ps 100ps 4.19.4 [10] <4.7> For the given hazard probabilities and pipeline stage latencies, what is the speedup achieved by adding full forwarding to a pipeline that had no forwarding? 4.19.5 [10] <4.7> What would be the additional speedup (relative to a proces- sor with forwarding) if we added time-travel forwarding that eliminates all data 4.16 Exercises 427
Hennesey_Page_425_Chunk425
428 Chapter 4 The Processor ­hazards? Assume that the yet-to-be-invented time-travel circuitry adds 100ps to the latency of the full-forwarding EX stage. 4.19.6 [20] <4.7> Repeat 4.19.3 but this time determine which of the two options results in shorter time per instruction. Exercise 4.20 Problems in this exercise refer to the following instruction sequences: Instruction Sequence a. ADD R1,R2,R1 LW R2,0(R1) LW R1,4(R1) OR R3,R1,R2 b. LW R1,0(R1) AND R1,R1,R2 LW R2,0(R1) LW R1,0(R3) 4.20.1 [5] <4.7> Find all data dependences in this instruction sequence. 4.20.2 [10] <4.7> Find all hazards in this instruction sequence for a 5-stage pipe- line with and then without forwarding. 4.20.3 [10] <4.7> To reduce clock cycle time, we are considering a split of the MEM stage into two stages. Repeat 4.20.2 for this 6-stage pipeline. The remaining three problems in this exercise assume that, before any of the above is executed, all values in data memory are zeroes and that registers R0 through R3 have the following initial values: R0 R1 R2 R3 a. 0 –1 31 1500 b. 0 4 63 3000 4.20.4 [5] <4.7> Which value is the first one to be forwarded and what is the value it overrides? 4.20.5 [10] <4.7> If we assume forwarding will be implemented when we design the hazard detection unit, but then we forget to actually implement forwarding, what are the final register values after this instruction sequence?
Hennesey_Page_426_Chunk426
4.20.6 [10] <4.7> For the design described in 4.20.5, add NOPs to this instruction sequence to ensure correct execution in spite of missing support for forwarding. Exercise 4.21 This exercise is intended to help you understand the relationship between forward- ing, hazard detection, and ISA design. Problems in this exercise refer to the follow- ing sequences of instructions, and assume that it is executed on a 5-stage pipelined datapath: Instruction sequence a. ADD R5,R2,R1 LW R3,4(R5) LW R2,0(R2) OR R3,R5,R3 SW R3,0(R5) b. LW R2,0(R1) AND R1,R2,R1 LW R3,0(R2) LW R1,0(R1) SW R1,0(R2) 4.21.1 [5] <4.7> If there is no forwarding or hazard detection, insert NOPs to ensure correct execution. 4.21.2 [10] <4.7> Repeat 4.21.1 but now use NOPs only when a hazard cannot be avoided by changing or rearranging these instructions. You can assume register R7 can be used to hold temporary values in your modified code. 4.21.3 [10] <4.7> If the processor has forwarding, but we forgot to implement the hazard detection unit, what happens when this code executes? 4.21.4 [20] <4.7> If there is forwarding, for the first five cycles during the execu- tion of this code, specify which signals are asserted in each cycle by hazard detec- tion and forwarding units in Figure 4.60. 4.21.5 [10] <4.7> If there is no forwarding, what new inputs and output signals do we need for the hazard detection unit in Figure 4.60? Using this instruction sequence as an example, explain why each signal is needed. 4.21.6 [20] <4.7> For the new hazard detection unit from 4.21.5, specify which output signals it asserts in each of the first five cycles during the execution of this code. 4.16 Exercises 429
Hennesey_Page_427_Chunk427
430 Chapter 4 The Processor Exercise 4.22 This exercise is intended to help you understand the relationship between delay slots, control hazards, and branch execution in a pipelined processor. In this exer- cise, we assume that the following MIPS code is executed on a pipelined processor with a 5-stage pipeline, full forwarding, and a predict-taken branch predictor: a. Label1: LW R2,0(R2) BEQ R2,R0,Label ; Taken once, then not taken OR R2,R2,R3 SW R2,0(R5) b. LW R2,0(R1) Label1: BEQ R2,R0,Label2 ; Not taken once, then taken LW R3,0(R2) BEQ R3,R0,Label1 ; Taken ADD R1,R3,R1 Label2: SW R1,0(R2) 4.22.1 [10] <4.8> Draw the pipeline execution diagram for this code, assuming there are no delay slots and that branches execute in the EX stage. 4.22.2 [10] <4.8> Repeat 4.22.1, but assume that delay slots are used. In the given code, the instruction that follows the branch is now the delay slot instruction for that branch. 4.22.3 [20] <4.8> One way to move the branch resolution one stage earlier is to not need an ALU operation in conditional branches. The branch instructions would be “BEZ Rd,Label” and “BNEZ Rd,Label”, and it would branch if the reg- ister has and does not have a zero value, respectively. Change this code to use these branch instructions instead of BEQ. You can assume that register R8 is available for you to use as a temporary register, and that an SEQ (set if equal) R-type instruction can be used. Section 4.8 describes how the severity of control hazards can be reduced by moving branch execution into the ID stage. This approach involves a dedicated comparator in the ID stage, as shown in Figure 4.62. However, this approach potentially adds to the latency of the ID stage, and requires additional forwarding logic and hazard detection. 4.22.4 [10] <4.8> Using the first branch instruction in the given code as an example, describe the hazard detection logic needed to support branch execution in the ID stage as in Figure 4.62. Which type of hazard is this new logic supposed to detect?
Hennesey_Page_428_Chunk428
4.22.5 [10] <4.8> For the given code, what is the speedup achieved by moving branch execution into the ID stage? Explain your answer. In your speedup calcula- tion, assume that the additional comparison in the ID stage does not affect clock cycle time. 4.22.6 [10] <4.8> Using the first branch instruction in the given code as an example, describe the forwarding support that must be added to support branch execution in the ID stage. Compare the complexity of this new forwarding unit to the complexity of the existing forwarding unit in Figure 4.62. Exercise 4.23 The importance of having a good branch predictor depends on how often condi- tional branches are executed. Together with branch predictor accuracy, this will determine how much time is spent stalling due to mispredicted branches. In this exercise, assume that the breakdown of dynamic instructions into various instruc- tion categories is as follows: R-Type BEQ JMP LW SW a. 40% 25% 5% 25% 5% b. 60% 8% 2% 20% 10% Also, assume the following branch predictor accuracies: Always-Taken Always-Not-Taken 2-Bit a. 45% 55% 85% b. 65% 35% 98% 4.23.1 [10] <4.8> Stall cycles due to mispredicted branches increase the CPI. What is the extra CPI due to mispredicted branches with the always-taken predic- tor? Assume that branch outcomes are determined in the EX stage, that there are no data hazards, and that no delay slots are used. 4.23.2 [10] <4.8> Repeat 4.23.1 for the “always-not-taken” predictor. 4.23.3 [10] <4.8> Repeat 4.23.1 for the 2-bit predictor. 4.23.4 [10] <4.8> With the 2-bit predictor, what speedup would be achieved if we could convert half of the branch instructions in a way that replaces a branch instruction with an ALU instruction? Assume that correctly and incorrectly pre- dicted instructions have the same chance of being replaced. 4.16 Exercises 431
Hennesey_Page_429_Chunk429
432 Chapter 4 The Processor 4.23.5 [10] <4.8> With the 2-bit predictor, what speedup would be achieved if we could convert half of the branch instructions in a way that replaced each branch instruction with two ALU instructions? Assume that correctly and incorrectly pre- dicted instructions have the same chance of being replaced. 4.23.6 [10] <4.8> Some branch instructions are much more predictable than others. If we know that 80% of all executed branch instructions are easy-to-predict loop-back branches that are always predicted correctly, what is the accuracy of the 2-bit predictor on the remaining 20% of the branch instructions? Exercise 4.24 This exercise examines the accuracy of various branch predictors for the following repeating pattern (e.g., in a loop) of branch outcomes: Branch Outcomes a. T, T, NT, NT b. T, NT, T, T, NT 4.24.1 [5] <4.8> What is the accuracy of always-taken and always-not-taken pre- dictors for this sequence of branch outcomes? 4.24.2 [5] <4.8> What is the accuracy of the two-bit predictor for the first 4 branches in this pattern, assuming that the predictor starts off in the bottom left state from Figure 4.63 (predict not taken)? 4.24.3 [10] <4.8> What is the accuracy of the two-bit predictor if this pattern is repeated forever? 4.24.4 [30] <4.8> Design a predictor that would achieve a perfect accuracy if this pattern is repeated forever. You predictor should be a sequential circuit with one output that provides a prediction (1 for taken, 0 for not taken) and no inputs other than the clock and the control signal that indicates that the instruction is a conditional branch. 4.24.5 [10] <4.8> What is the accuracy of your predictor from 4.24.4 if it is given a repeating pattern that is the exact opposite of this one? 4.24.6 [20] <4.8> Repeat 4.24.4, but now your predictor should be able to even- tually (after a warm-up period during which it can make wrong predictions) start perfectly predicting both this pattern and its opposite. Your predictor should have an input that tells it what the real outcome was. Hint: this input lets your predictor determine which of the two repeating patterns it is given.
Hennesey_Page_430_Chunk430
Exercise 4.25 This exercise explores how exception handling affects pipeline design. The first three problems in this exercise refer to the following two instructions: Instruction 1 Instruction 2 a. BNE R1,R2,Label LW R1,0(R1) b. JUMP Label SW R5,0(R1) 4.25.1 [5] <4.9> Which exceptions can each of these instructions trigger? For each of these exceptions, specify the pipeline stage in which it is detected. 4.25.2 [10] <4.9> If there is a separate handler address for each exception, show how the pipeline organization must be changed to be able to handle this exception. You can assume that the addresses of these handlers are known when the processor is designed. 4.25.3 [10] <4.9> If the second instruction from this table is fetched right after the instruction from the first table, describe what happens in the pipeline when the first instruction causes the first exception you listed in 4.25.1. Show the pipeline execution diagram from the time the first instruction is fetched until the time the first instruction of the exception handler is completed. The remaining three problems in this exercise assume that exception handlers are located at the following addresses: Overflow Invalid Data Address Undefined Instruction Invalid Instruction Address Hardware Malfunction a. 0x1000CB05 0x1000D230 0x1000D780 0x1000E230 00x1000F254 b. 0x450064E8 0xC8203E20 0xC8203E20 0x678A0000 0x00000010 4.25.4 [5] <4.9> What is the address of the exception handler in 4.25.3? What happens if there is an invalid instruction at that address in instruction memory? 4.25.5 [20] <4.9> In vectored exception handling, the table of exception handler addresses is in data memory at a known (fixed) address. Change the pipeline to implement this exception handling mechanism. Repeat 4.25.3 using this modified pipeline and vectored exception handling. 4.25.6 [15] <4.9> We want to emulate vectored exception handling (described in 4.25.5) on a machine that has only one fixed handler address. Write the code that should be at that fixed address. Hint: this code should identify the exception, get the right address from the exception vector table, and transfer execution to that handler. 4.16 Exercises 433
Hennesey_Page_431_Chunk431
434 Chapter 4 The Processor Exercise 4.26 This exercise explores how exception handling affects control unit design and pro- cessor clock cycle time. The first three problems in this exercise refer to the follow- ing MIPS instruction that triggers an exception: Instruction Exception a. BNE R1,R2,Label Invalid target address b. SUB R2,R4,R5 Arithmetic overflow 4.26.1 [10] <4.9> For each stage of the pipeline, determine the values of excep- tion-related control signals from Figure 4.66 as this instruction passes through that pipeline stage. 4.26.2 [5] <4.9> Some of the control signals generated in the ID stage are stored into the ID/EX pipeline register, and some go directly into the EX stage. Explain why, using this instruction as an example. 4.26.3 [10] <4.9> We can make the EX stage faster if we check for exceptions in the stage after the one in which the exceptional condition occurs. Using this instruction as an example, describe the main disadvantage of this approach. The remaining three problems in this exercise assume that pipeline stages have the following latencies: IF ID EX MEM WB a. 220ps 150ps 250ps 200ps 200ps b. 175ps 150ps 200ps 175ps 140ps 4.26.4 [10] <4.9> If an overflow exception occurs once for every 100,000 instruc- tions executed, what is the overall speedup if we move overflow checking into the MEM stage? Assume that this change reduces EX latency by 30ns and that the IPC achieved by the pipelined processor is 1 when there are no exceptions. 4.26.5 [20] <4.9> Can we generate exception control signals in EX instead of in ID? Explain how this will work or why it will not work, using the “BNE R4,R5,Label” instruction and these pipeline stage latencies as an example. 4.26.6 [10] <4.9> Assuming that each Mux has a latency of 40ps, determine how much time does the control unit have to generate the flush signals? Which signal is the most critical?
Hennesey_Page_432_Chunk432
Exercise 4.27 This exercise examines how exception handling interacts with branch and load/ store instructions. Problems in this exercise refer to the following branch instruc- tion and the corresponding delay slot instruction: Branch and Delay Slot a. BEQ R5,R4,Label SLT R5,R15,R4 b. BEQ R1,R0,Label LW R1,0(R1) 4.27.1 [20] <4.9> Assume that this branch is correctly predicted as taken, but then the instruction at “Label” is an undefined instruction. Describe what is done in each pipeline stage for each cycle, starting with the cycle in which the branch is decoded up to the cycle in which the first instruction of the exception handler is fetched. 4.27.2 [10] <4.9> Repeat 4.27.1, but this time assume that the instruction in the delay slot also causes a hardware error exception when it is in MEM stage. 4.27.3 [10] <4.9> What is the value in the EPC if the branch is taken but the delay slot causes an exception? What happens after the execution of the exception handler is completed? The remaining three problems in this exercise also refer to the following store instruction: Store Instruction a. SW R5,–40(R15) b. SW R1,0(R1) 4.27.4 [10] <4.9> What happens if the branch is taken, the instruction at “Label” is an invalid instruction, the first instruction of the exception handler is the SW instruction given above, and this store accesses an invalid data address? 4.27.5 [10] <4.9> If LD/ST address computation can overflow, can we delay overflow exception detection into the MEM stage? Use the given store instruction to explain what happens. 4.27.6 [10] <4.9> For debugging, it is useful to be able to detect when a par- ticular value is written to a particular memory address. We want to add two new registers, WADDR and WVAL. The processor should trigger an exception when the 4.16 Exercises 435
Hennesey_Page_433_Chunk433
436 Chapter 4 The Processor value equal to WVAL is about to be written to address WADDR. How would you change the pipeline to implement this? How would this SW instruction be handled by your modified datapath? Exercise 4.28 In this exercise we compare the performance of 1-issue and 2-issue processors, tak- ing into account program transformations that can be made to optimize for 2-issue execution. Problems in this exercise refer to the following loop (written in C): C Code a. for(i=0;i!=j;i+=2) a[i+1]=a[i]; b. for(i=0;i!=j;i+=2) b[i]=a[i]–a[i+1]; When writing MIPS code, assume that variables are kept in registers as follows, and that all registers except those indicated as Free are used to keep various variables, so they cannot be used for anything else. i j a b c Free a. R2 R8 R9 R10 R11 R3,R4,R5 b. R5 R6 R1 R2 R3 R10,R11,R12 4.28.1 [10] <4.10> Translate this C code into MIPS instructions. Your trans- lation should be direct, without rearranging instructions to achieve better ­performance. 4.28.2 [10] <4.10> If the loop exits after executing only two iterations, draw a pipeline diagram for your MIPS code from 4.28.1 executed on a 2-issue processor shown in Figure 4.69. Assume the processor has perfect branch prediction and can fetch any two instructions (not just consecutive instructions) in the same cycle. 4.28.3 [10] <4.10> Rearrange your code from 4.28.1 to achieve better perfor- mance on a 2-issue statically scheduled processor from Figure 4.69. 4.28.4 [10] <4.10> Repeat 4.28.2, but this time use your MIPS code from 4.28.3. 4.28.5 [10] <4.10> What is the speedup of going from a 1-issue processor to a 2-issue processor from Figure 4.69? Use your code from 4.28.1 for both 1-issue and 2-issue, and assume that 1,000,000 iterations of the loop are executed. As in
Hennesey_Page_434_Chunk434
4.28.2, assume that the processor has perfect branch predictions, and that a 2-issue processor can fetch any two instructions in the same cycle. 4.28.6 [10] <4.10> Repeat 4.28.5, but this time assume that in the 2-issue pro- cessor one of the instructions to be executed in a cycle can be of any kind, and the other must be a non-memory instruction. Exercise 4.29 In this exercise, we consider the execution of a loop in a statically scheduled super- scalar processor. To simplify the exercise, assume that any combination of instruc- tion types can execute in the same cycle, e.g., in a 3-issue superscalar, the three instructions can be 3 ALU operations, 3 branches, 3 load/store instructions, or any combination of these instructions. Note that this only removes a resource con- straint, but data and control dependences must still be handled correctly. Problems in this exercise refer to the following loop: Loop a. Loop: ADDI R1,R1,4 LW R2,0(R1) LW R3,16(R1) ADD R2,R2,R1 ADD R2,R2,R3 BEQ R2,zero,Loop b. Loop: LW R1,0(R1) AND R1,R1,R2 LW R2,0(R2) BEQ R1,zero,Loop 4.29.1 [10] <4.10> If many (e.g., 1,000,000) iterations of this loop are executed, determine the fraction of all register reads that are useful in a 2-issue static super- scalar processor. 4.29.2 [10] <4.10> If many (e.g., 1,000,000) iterations of this loop are exe- cuted, determine the fraction of all register reads that are useful in a 3-issue static superscalar processor. Compare this to your result for a 2-issue processor from 4.29.1. 4.29.3 [10] <4.10> If many (e.g., 1,000,000) iterations of this loop are executed, determine the fraction of cycles in which two or three register write ports are used in a 3-issue static superscalar processor. 4.29.4 [20] <4.10> Unroll this loop once and schedule it for a 2-issue static superscalar processor. Assume that the loop always executes an even number of 4.16 Exercises 437
Hennesey_Page_435_Chunk435
438 Chapter 4 The Processor iterations. You can use registers R10 through R20 when changing the code to elimi- nate dependences. 4.29.5 [20] <4.10> What is the speedup of using your code from 4.29.4 instead of the original code with a 2-issue static superscalar processor? Assume that the loop has many (e.g., 1,000,000) iterations. 4.29.6 [10] <4.10> What is the speedup of using your code from 4.29.4 instead of the original code with a pipelined (1-issue) processor? Assume that the loop has many (e.g., 1,000,000) iterations. Exercise 4.30 In this exercise, we make several assumptions. First, we assume that an N-issue superscalar processor can execute any N instructions in the same cycle, regardless of their types. Second, we assume that every instruction is independently chosen, without regard for the instruction that precedes or follows it. Third, we assume that there are no stalls due to data dependences, that no delay slots are used, and that branches execute in the EX stage of the pipeline. Finally, we assume that instruc- tions executed in the program are distributed as follows: ALU Correctly Predicted BEQ Incorrectly Predicted BEQ LW SW a. 40% 20% 5% 25% 10% b. 45% 4% 1% 30% 20% 4.30.1 [5] <4.10> What is the CPI achieved by a 2-issue static superscalar proces- sor on this program? 4.30.2 [10] <4.10> In a 2-issue static superscalar whose predictor can only han- dle one branch per cycle, what speedup is achieved by adding the ability to predict two branches per cycle? Assume a stall-on-branch policy for branches that the pre- dictor cannot handle. 4.30.3 [10] <4.10> In a 2-issue static superscalar processor that only has one reg- ister write port, what speedup is achieved by adding a second register write port? 4.30.4 [5] <4.10> For a 2-issue static superscalar processor with a classic 5-stage pipeline, what speedup is achieved by making the branch prediction perfect? 4.30.5 [10] <4.10> Repeat 4.30.4, but for a 4-issue processor. What conclusion can you draw about the importance of good branch prediction when the issue width of the processor is increased? 4.30.6  <4.10> Repeat 4.30.5, but now assume that the 4-issue processor has 50 pipeline stages. Assume that each of the original 5 stages is broken into 10 new stages, and that branches are executed in the first of ten new EX stages. What
Hennesey_Page_436_Chunk436
conclusion can you draw about the importance of good branch prediction when the pipeline depth of the processor is increased? Exercise 4.31 Problems in this exercise refer to the following loop, which is given as x86 code and also as an MIPS translation of that code. You can assume that this loop executes many itera- tions before it exits. When determining performance, this means that you only need to determine what the performance would be in the “steady state,” not for the first few and the last few iterations of the loop. Also, you can assume full forwarding support and perfect branch prediction without delay slots, so the only hazards you have to worry about are resource hazards and data hazards. Note that most x86 instructions in this problem have two operands each. The last (usually second) operand of the instruction indicates both the first source data value and the destination. If the operation needs a second source data value, it is indicated by the other operand of the instruction. For example, “sub (edx),eax” reads the memory location pointed by register edx, subtracts that value from register eax, and puts the result back in register eax. x86 Instructions MIPS-like Translation a. Label: mov –4(esp), eax mov –4(esp), edx add (edi,eax,4),edx mov edx, –4(esp) mov –4(esp),eax cmp 0, (edi,eax,4) jne Label Label: lw r2,–4(sp) lw r3,–4(sp) sll r2,r2,2 add r2,r2,r4 lw r2,0(r2) add r3,r3,r2 sw r3,–4(sp) lw r2,–4(sp) sll r2,r2,2 add r2,r2,r4 lw r2,0(r2) bne r2,zero,Label b. Label: add 4, edx mov (edx), eax add 4(edx), eax add 8(edx), eax mov eax, –4(edx) test edx, edx jl Label Label: addi r4,r4,4 lw r3,0(r4) lw r2,4(r4) add r2,r2,r3 lw r3,8(r4) add r2,r2,r3 sw r2,–4(r4) slt r1,r4,zero bne r1,zero,Label 4.31.1 [20] <4.11> What CPI would be achieved if the MIPS version of this loop is executed on a 1-issue processor with static scheduling and a 5-stage pipeline? 4.31.2 [20] <4.11> What CPI would be achieved if the X86 version of this loop is executed on a 1-issue processor with static scheduling and a 7-stage pipeline? The stages of the pipeline are IF, ID, ARD, MRD, EXE, and WB. Stages IF and ID are similar to those in the 5-stage MIPS pipeline. ARD computes the address of the memory location to be read, MRD performs the memory read, EXE executes 4.16 Exercises 439
Hennesey_Page_437_Chunk437
440 Chapter 4 The Processor the operation, and WB writes the result to register or memory. The data memory has a read port (for instructions in the MRD stage) and a separate write port (for instructions in the WB stage). 4.31.3 [20] <4.11> What CPI would be achieved if the X86 version of this loop is executed on a processor that internally translates these instructions into MIPS-like micro-operations, then executes these micro-operations on a 1-issue 5-stage pipe- line with static scheduling. Note that the instruction count used in CPI computa- tion for this processor is the X86 instruction count. 4.31.4 [20] <4.11> What CPI would be achieved if the MIPS version of this loop is executed on a 1-issue processor with dynamic scheduling? Assume that our pro- cessor is not doing register renaming, so you can only reorder instructions that have no data dependences. 4.31.5 [30] <4.10, 4.11> Assuming that there are many free registers available, rename the MIPS version of this loop to eliminate as many data dependences as possible between instructions in the same iteration of the loop. Now repeat 4.31.4, using your new renamed code. 4.31.6 [20] <4.10, 4.11> Repeat 4.31.4, but this time assume that the processor assigns a new name to the result of each instruction as that instruction is decoded, and then renames registers used by subsequent instructions to use correct register values. Exercise 4.32 Problems in this exercise assume that branches represent the following fraction of all executed instructions, and the following branch predictor accuracy. Assume that the processor is never stalled by data and resource dependences, i.e., the pro- cessor always fetches and executes the maximum number of instructions per cycle if there are no control hazards. For control dependences, the processor uses branch prediction and continues fetching from the predicted path. If the branch has been mispredicted, when the branch outcome is resolved the instructions fetched after the mispredicted branch are discarded, and in the next cycle the processor starts fetching from the correct path. Branches as a % of All Executed Instructions Branch Prediction Accuracy a. 25 95% b. 25 99% 4.32.1 [5] <4.11> How many instructions are expected to be executed between the time one branch misprediction is detected and the time the next branch mis- prediction is detected?
Hennesey_Page_438_Chunk438
The remaining problems in this exercise assume the following pipeline depth and that the branch outcome is determined in the following pipeline stage (counting from stage 1): Pipeline Depth Branch Outcome Known in Stage a. 15 12 b. 30 20 4.32.2 [5] <4.11> In a 4-issue processor with these pipeline parameters, how many branch instructions can be expected to be “in progress” (already fetched but not yet committed) at any given time? 4.32.3 [5] <4.11> How many instructions are fetched from the wrong path for each branch misprediction in a 4-issue processor? 4.32.4 [10] <4.11> What is the speedup achieved by changing the processor from 4-issue to 8-issue? Assume that the 8-issue and the 4-issue processor differ only in the number of instructions per cycle, and are otherwise identical (pipeline depth, branch resolution stage, etc.). 4.32.5 [10] <4.11> What is the speedup of executing branches 1 stage earlier in a 4-issue processor? 4.32.6 [10] <4.11> What is the speedup of executing branches 1 stage earlier in an 8-issue processor? Discuss the difference between this result and the result from 4.32.5. Exercise 4.33 This exercise explores how branch prediction affects performance of a deeply pipe- lined multiple-issue processor. Problems in this exercise refer to a processor with the following number of pipeline stages and instructions issued per cycle: Pipeline Depth Issue Width a. 15 2 b. 30 8 4.33.1 [10] <4.11> How many register read ports should the processor have to avoid any resource hazards due to register reads? 4.33.2 [10] <4.11> If there are no branch mispredictions and no data depen- dences, what is the expected performance improvement over a 1-issue processor with the classical 5-stage pipeline? Assume that the clock cycle time decreases in proportion to the number of pipeline stages. 4.16 Exercises 441
Hennesey_Page_439_Chunk439
442 Chapter 4 The Processor 4.33.3 [10] <4.11> Repeat 4.33.2, but this time every executed instruction has a RAW data dependence to the instruction that executes right after it. You can assume that no stall cycles are needed, i.e., forwarding allows consecutive instruc- tions to execute in back-to-back cycles. For the remaining three problems in this exercise, unless the problem specifies oth- erwise, assume the following statistics about what percentage of instructions are branches, predictor accuracy, and performance loss due to branch mispredictions: Branches as a Fraction of All Executed Instructions Branches Execute in Stage Predictor Accuracy Performance Loss a. 10% 9 96% 5% b. 10% 5 98% 1% 4.33.4 [10] <4.11> If we have the given fraction of branch instructions and branch prediction accuracy, what percentage of all cycles are entirely spent fetch- ing wrong-path instructions? Ignore the performance loss number. 4.33.5 [20] <4.11> If we want to limit stalls due to mispredicted branches to no more than the given percentage of the ideal (no stalls) execution time, what should be our branch prediction accuracy? Ignore the given predictor accuracy number. 4.33.6 [10] <4.11> What should the branch prediction accuracy be if we are will- ing to have a speedup of 0.5 (one half) relative to the same processor with an ideal branch predictor? Exercise 4.34 This exercise is designed to help you understand the discussion of the “Pipelining is easy” fallacy from Section 4.13. The first four problems in this exercise refer to the following MIPS instruction: Instruction Interpretation a. AND Rd,Rs,Rt Reg[Rd]=Reg[Rs] AND Reg[Rt] b. SW Rt,Offs(Rs) Mem[Reg[Rs]+Offs] = Reg[Rt] 4.34.1 [10] <4.13> Describe a pipelined datapath needed to support only this instruction. Your datapath should be designed with the assumption that the only instructions that will ever be executed are instances of this instruction. 4.34.2 [10] <4.13> Describe the requirements of forwarding and hazard detec- tion units for your datapath from 4.34.1.
Hennesey_Page_440_Chunk440
4.34.3 [10] <4.13> What needs to be done to support undefined instruction exceptions in your datapath from 4.34.1? Note that the undefined instruction exception should be triggered whenever the processor encounters any other kind of instruction. The remaining two problems in this exercise also refer to this MIPS instruction: Instruction Interpretation a. ADD Rd,Rs,Rt Reg[Rd] =Reg[Rs] +Reg[Rt] b. ADDI Rt,Rs,Imm Reg[Rt] =Reg[Rs] +Imm 4.34.4 [10] <4.13> Describe how to extend your datapath from 4.34.1 so it can also support this instruction. Your extended datapath should be designed to only support instances of these two instructions. 4.34.5 [10] <4.13> Repeat 4.34.2 for your extended datapath from 4.34.4. 4.34.6 [10] <4.13> Repeat 4.34.3 for your extended datapath from 4.34.4. Exercise 4.35 This exercise is intended to help you better understand the relationship between ISA design and pipelining. Problems in this exercise assume that we have a mul- tiple-issue pipelined processor with the following number of pipeline stages, instructions issued per cycle, stage in which branch outcomes are resolved, and branch predictor accuracy: Pipeline Depth Issue Width Branches Execute in Stage Branch Predictor Accuracy Branches as a % of Instructions a. 15 2 10 90% 25% b. 25 4 15 96% 15% 4.35.1 [5] <4.8, 4.13> Control hazards can be eliminated by adding branch delay slots. How many delay slots must follow each branch if we want to eliminate all control hazards in this processor? 4.35.2 [10] <4.8, 4.13> What is the speedup that would be achieved by using four branch delay slots to reduce control hazards in this processor? Assume that there are no data dependences between instructions and that all four delay slots can be filled with useful instructions without increasing the number of executed instructions. To make your computations easier, you can also assume that the mis- predicted branch instruction is always the last instruction to be fetched in a cycle, i.e., no instructions that are in the same pipeline stage as the branch are fetched from the wrong path. 4.16 Exercises 443
Hennesey_Page_441_Chunk441
444 Chapter 4 The Processor 4.35.3 [10] <4.8, 4.13> Repeat 4.35.2, but now assume that 10% of executed branches have all four delay slots filled with useful instruction, 20% have only three useful instructions in delay slots (the fourth delay slot is an NOP), 30% have only two useful instructions in delay slots, and 40% have no useful instructions in their delay slots. The remaining four problems in this exercise refer to the following C loop: a. for(i=0;i!=j;i++){ c+=a[i]; } b. for(i=0;i!=j;i+=2){ c+=a[i]–a[i+1]; } 4.35.4 [10] <4.8, 4.13> Translate this C loop into MIPS instructions, assuming that our ISA requires one delay slot for every branch. Try to fill delay slots with non-NOP instructions when possible. You can assume that variables a, b, c, i, and j are kept in registers r1, r2, r3, r4, and r5. 4.35.5 [10] <4.7, 4.13> Repeat 4.35.4 for a processor that has two delay slots for every branch. 4.35.6 [10] <4.10, 4.13> How many iterations of your loop from 4.35.4 can be “in flight” within this processor’s pipeline? We say that an iteration is “in flight” when at least one of its instructions has been fetched and has not yet been committed. Exercise 4.36 This exercise is intended to help you better understand the last pitfall from Section 4.13—failure to consider pipelining in instruction set design. The first four prob- lems in this exercise refer to the following new MIPS instruction: Instruction Interpretation a. SWINC Rt,Offset(Rs) Mem[Reg[Rs] +Offset] =Reg[Rt] Reg[Rs] =Reg[Rs] +4 b. SWI Rt,Rd(Rs) Mem[Reg[Rd] +Reg[Rs]]= Reg[Rt] 4.36.1 [10] <4.11, 4.13> Translate this instruction into MIPS micro-operations. 4.36.2 [10] <4.11, 4.13> How would you change the 5-stage MIPS pipeline to add support for micro-op translation needed to support this new instruction?
Hennesey_Page_442_Chunk442
4.36.3 [20] <4.13> If we want to add this instruction to the MIPS ISA, discuss the changes to the pipeline (which stages, which structures in which stage) that are needed to directly (without micro-ops) support this instruction. 4.36.4 [10] <4.13> How often do you expect this instruction can be used? Do you think that we would be justified if we added this instruction to the MIPS ISA? The remaining two problems in this exercise are about adding a new ADDM instruction to the ISA. In a processor to which ADDM has been added, these prob- lems assume the following breakdown of clock cycles according to which instruc- tion is completed in that cycle (or which stall is preventing an instruction from completing): ADD BEQ LW SW ADDM Control Stalls Data Stalls a. 25% 20% 20% 10% 3% 10% 12% b. 25% 10% 25% 20% 5% 10% 5% 4.36.5 [10] <4.13> Given this breakdown of execution cycles in the proces- sor with direct support for the ADDM instruction, what speedup is achieved by replacing this instruction with a 3-instruction sequence (LW, ADD, and then SW)? Assume that the ADDM instruction is somehow (magically) supported with a classi- cal 5-stage pipeline without creating resource hazards. 4.36.6 [10] <4.13> Repeat 4.36.5, but now assume that ADDM was supported by adding a pipeline stage. When ADDM is translated, this extra stage can be removed and, as a result, half of the existing data stalls are eliminated. Note that the data stall elimination applies only to stalls that existed before ADDM translation, not to stalls added by the ADDM translation itself. Exercise 4.37 This exercise explores some of the tradeoffs involved in pipelining, such as clock cycle time and utilization of hardware resources. The first three problems in this exercise refer to the following MIPS code. The code is written with an assumption that the processor does not use delay slots. a. SW R16,–100(R6) LW R16,8(R6) BEQ R5,R4,Label ; Assume R5 != R4 ADD R5,R16,R4 SLT R5,R15,R4 b. OR R1,R2,R3 SW R1,0(R2) BEQ R1,R0,Label ; Assume R1 == R0 OR R2,R1,R0 Label: ADD R1,R1,R3 4.16 Exercises 445
Hennesey_Page_443_Chunk443
446 Chapter 4 The Processor 4.37.1 [5] <4.3, 4.14> Which parts of the basic single-cycle datapath are used by all of these instructions? Which parts are the least utilized? 4.37.2 [10] <4.6, 4.14> What is the utilization for the read and for the write port of the data memory unit? 4.37.3 [10] <4.6, 4.14> Assume that we already have a single-cycle design. How many bits in total do we need for pipeline registers to implement the pipelined design? The remaining three problems in this exercise assume that components of the dat- apath have the following latencies: I-Mem Add Mux ALU Regs D-Mem Sign-Extend Shift-Left-2 a. 200ps 70ps 20ps 90ps 90ps 250ps 15ps 10ps b. 750ps 200ps 50ps 250ps 300ps 500ps 100ps 5ps 4.37.4 [10] <4.3, 4.5, 4.14> Given these latencies for individual elements of the datapath, compare clock cycle times of the single-cycle and the 5-stage pipelined datapath. 4.37.5 [10] <4.3, 4.5, 4.14> Repeat 4.37.4, but now assume that we only want to support ADD instructions. 4.37.6 [20] <4.3, 4.5, 4.14> If it costs $1 to reduce the latency of a single compo- nent of the datapath by 1ps, what would it cost to reduce the clock cycle time by 20% in the single-cycle and in the pipelined design? Exercise 4.38 This exercise explores energy efficiency and its relationship with performance. Problems in this exercise assume the following energy consumption for activity in Instruction memory, Registers, and Data memory. You can assume that the other components of the datapath spend a negligible amount of energy. I-Mem 1 Register Read Register Write D-Mem Read D-Mem Write a. 140pJ 70pJ 60pJ 140pJ 120pJ b. 70pJ 40pJ 40pJ 90pJ 100pJ 4.38.1 [10] <4.3, 4.6, 4.14> How much energy is spent to execute an ADD instruc- tion in a single-cycle design and in the 5-stage pipelined design?
Hennesey_Page_444_Chunk444
4.38.2 [10] <4.6, 4.14> What is the worst-case MIPS instruction in terms of energy consumption, and what is the energy spent to execute it? 4.38.3 [10] <4.6, 4.14> If energy reduction is paramount, how would you change the pipelined design? What is the percentage reduction in the energy spent by an LW instruction after this change? The remaining three problems in this exercise assume that components in the data- path have the following latencies. You can assume that the other components of the datapath have negligible latencies. I-Mem Control Register Read or Write ALU D-Mem Read or Write a. 200ps 150ps 90ps 90ps 250ps b. 750ps 500ps 300ps 250ps 500ps 4.38.4 [10] <4.6, 4.14> What is the performance impact of your changes from 4.38.3? 4.38.5 [10] <4.6, 4.14> We can eliminate the MemRead control signal and have the data memory be read in every cycle, i.e., we can permanently have MemRead=1. Explain why the processor still functions correctly after this change. What is the effect of this change on clock frequency and energy consumption? 4.38.6 [10] <4.6, 4.14> If an idle unit spends 10% of the power it would spend if it were active, what is the energy spent by the instruction memory in each cycle? What percentage of the overall energy spent by the instruction memory does this idle energy represent? Exercise 4.39 Problems in this exercise assume that, during an execution of the program, proces- sor cycles are spent in the following way. A cycle is “spent” on an instruction if the processor completes that type of instruction in that cycle; a cycle is “spent” on a stall if the processor could not complete an instruction in that cycle because of a stall. ADD BEQ LW SW Control Stalls Data Stalls a. 25% 20% 20% 10% 10% 15% b. 25% 10% 25% 20% 10% 10% Problems in this exercise also assume that individual pipeline stages have the ­following latency and energy consumption. The stage expends this energy in order 4.16 Exercises 447
Hennesey_Page_445_Chunk445
448 Chapter 4 The Processor to do its work within the given latency. Note that no energy is spent in the MEM stage during a cycle in which there is no memory access. Similarly, no energy is spent in the WB stage in a cycle in which there is no register write. In several of the following problems, we make assumptions about how energy consumption changes if a stage performs its work slower or faster than this. IF ID EX MEM WB a. 250ps/100pJ 350ps/45pJ 150ps/50pJ 300ps/150pJ 200ps/50pJ b. 200ps/75pJ 170ps/45pJ 220ps/100pJ 210ps/100pJ 150ps/35pJ 4.39.1 [10] <4.14> What is the performance (in instructions per second)? 4.39.2 [10] <4.14> What is the power dissipated in watts (joules per second)? 4.39.3 [10] <4.6, 4.14> Which pipeline stages can you slow down and by how much, without affecting the clock cycle time? 4.39.4 [20] <4.6, 4.14> It is often possible to sacrifice some speed in a circuit in order to reduce its energy consumption. Assume that we can reduce energy con- sumption by a factor of X (new energy is 1/X times the old energy) when we increase the latency by a factor of X (new latency is X times the old latency). Using this tradeoff, we can adjust latencies of pipeline stages to minimize energy ­consumption without sacrificing any performance. Repeat 4.39.2 for this adjusted processor. 4.39.5 [10] <4.6, 4.14> Repeat 4.39.4, but this time the goal is to minimize energy spent per instruction while increasing the clock cycle time by no more than 10%. 4.39.6 [10] <4.6, 4.14> Repeat 4.39.5, but now assume that energy consumption is reduced by a factor of X2 when latency is made X times longer. What are the power savings compared to what you computed for 4.39.2? §4.1, page 303: 3 of 5: Control, Datapath, Memory. Input and Output are missing. §4.2, page 307: false. Edge-triggered state elements make simultaneous reading and writing both possible and unambiguous. §4.3, page 315: I. A. II. C. §4.4, page 330: Yes, Branch and ALUOp0 are identical. In addition, MemtoReg and RegDst are inverses of one another. You don’t need an inverter; simply use the other signal and flip the order of the inputs to the multiplexor! §4.5, page 343: 1. Stall on the LW result. 2. Bypass the first ADD result written into $t1. 3. No stall or bypass required. §4.6, page 358: Statements 2 and 4 are correct; the rest are incorrect. §4.8, page 383: 1. Predict not taken. 2. Predict taken. 3. Dynamic prediction. §4.9, page 391: The first instruction, since it is logically executed before the others. Answers to Check Yourself
Hennesey_Page_446_Chunk446
§4.10, page 403: 1. Both. 2. Both. 3. Software. 4. Hardware. 5. Hardware. 6. Hardware. 7. Both. 8. Hardware. 9. Both. §4.11, page 404: First two are false and last two are true. §4.12, page 4.12-3: Statements 1 and 3 are both true. §4.12, page 4.12-5: The best answer is 2 (see the Elaboration on page 371) 4.16 Exercises 449
Hennesey_Page_447_Chunk447
5 Ideally one would desire an indefinitely large memory capacity such that any particular . . . word would be im­mediately available. . . . We are . . . forced to recognize the possibility of constructing a hierarchy of memories, each of which has greater capacity than the preceding but which is less quickly accessible. A. W. Burks, H. H. Goldstine, and J. von Neumann Preliminary Discussion of the Logical Design of an Electronic Computing Instrument, 1946 Large and Fast: Exploiting Memory Hierarchy 5.1 Introduction 452 5.2 The Basics of Caches 457 5.3 Measuring and Improving Cache Performance 475 5.4 Virtual Memory 492 5.5 A Common Framework for Memory Hierarchies 518 5.6 Virtual Machines 525 Computer Organization and Design. DOI: 10.1016/B978-0-12-374750-1.00005-0 © 2012 Elsevier, Inc. All rights reserved.
Hennesey_Page_448_Chunk448
5.7 Using a Finite-State Machine to Control a Simple Cache 529 5.8 Parallelism and Memory Hierarchies: Cache Coherence 534 5.9 Advanced Material: Implementing Cache Controllers 538 5.10 Real Stuff: the AMD Opteron X4 (Barcelona) and Intel Nehalem Memory Hierarchies 539 5.11 Fallacies and Pitfalls 543 5.12 Concluding Remarks 547 5.13 Historical Perspective and Further Reading 548 5.14 Exercises 548 The Five Classic Components of a Computer
Hennesey_Page_449_Chunk449
452 Chapter 5 Large and Fast: Exploiting Memory Hierarchy 5.1 Introduction From the earliest days of computing, programmers have wanted unlimited amounts of fast memory. The topics in this chapter aid programmers by creating that illusion. Before we look at creating the illusion, let’s consider a simple analogy that illustrates the key principles and mechanisms that we use. Suppose you were a student writing a term paper on important historical develop­ ments in computer hardware. You are sitting at a desk in a library with a collection of books that you have pulled from the shelves and are examining. You find that several of the important computers that you need to write about are described in the books you have, but there is nothing about the EDSAC. There­fore, you go back to the shelves and look for an additional book. You find a book on early ­British computers that covers the EDSAC. Once you have a good selec­tion of books on the desk in front of you, there is a good probability that many of the topics you need can be found in them, and you may spend most of your time just using the books on the desk without going back to the shelves. Having several books on the desk in front of you saves time compared to having only one book there and constantly having to go back to the shelves to return it and take out another. The same principle allows us to create the illusion of a large memory that we can access as fast as a very small memory. Just as you did not need to access all the books in the library at once with equal probability, a program does not access all of its code or data at once with equal probability. Otherwise, it would be impossi­ble to make most memory accesses fast and still have large memory in computers, just as it would be impossible for you to fit all the ­library books on your desk and still find what you wanted quickly. This principle of locality underlies both the way in which you did your work in the library and the way that programs operate. The principle of locality states that programs access a relatively small portion of their address space at any instant of time, just as you accessed a very small portion of the library’s collection. There are two different types of locality: ■ Temporal locality (locality in time): if an item is referenced, it will tend to be referenced again soon. If you recently brought a book to your desk to look at, you will probably need to look at it again soon. ■ ■Spatial locality (locality in space): if an item is referenced, items whose addresses are close by will tend to be referenced soon. For example, when temporal locality The princi­ple stating that if a data ­location is referenced then it will tend to be referenced again soon. spatial locality The locality principle stating that if a data location is referenced, data loca­tions with nearby addresses will tend to be referenced soon.
Hennesey_Page_450_Chunk450
you brought out the book on early English computers to find out about the EDSAC, you also noticed that there was another book shelved next to it about early mechanical computers, so you also brought back that book and, later on, found something useful in that book. Libraries put books on the same topic together on the same shelves to increase spatial locality. We’ll see how memory hierarchies use spatial locality in a little later in this chap­ter. Just as accesses to books on the desk naturally exhibit locality, locality in pro­ grams arises from simple and natural program structures. For example, most pro­grams contain loops, so instructions and data are likely to be accessed repeat­ edly, showing high amounts of temporal locality. Since instructions are normally accessed sequentially, programs also show high spatial locality. Accesses to data also exhibit a natural spatial locality. For example, sequential accesses to elements of an array or a record will naturally have high degrees of spatial locality. We take advantage of the principle of locality by implementing the memory of a computer as a memory hierarchy. A memory hierarchy consists of multiple lev­els of memory with different speeds and sizes. The faster memories are more expensive per bit than the slower memories and thus are smaller. Today, there are three primary technologies used in building memory hierar­ chies. Main memory is implemented from DRAM (dynamic random access memory), while levels closer to the processor (caches) use SRAM (static random access memory). DRAM is less costly per bit than SRAM, although it is substan­ tially slower. The price difference arises because DRAM uses significantly less area per bit of memory, and DRAMs thus have larger capacity for the same amount of silicon; the speed difference arises from several factors described in Section C.9 of Appendix C. The third technology, used to implement the largest and slowest level in the hierarchy, is usually magnetic disk. (Flash mem­ory is used instead of disks in many embedded devices; see Section 6.4.) The access time and price per bit vary widely among these technologies, as the table below shows, using typical values for 2008: Memory technology Typical access time $ per GB in 2008 SRAM 0.5–2.5 ns $2000–$5000 DRAM 50–70 ns $20–$75 Magnetic disk 5,000,000–20,000,000 ns $0.20–$2 Because of these differences in cost and access time, it is advantageous to build memory as a hierarchy of levels. Figure 5.1 shows the faster memory is close to the processor and the slower, less expensive memory is below it. The goal is to present the user with as much memory as is available in the cheapest technology, while providing access at the speed offered by the fastest memory. memory hierarchy A struc­ture that uses multiple levels of memories; as the distance from the processor increases, the size of the memories and the access time both ­increase. 5.1 Introduction 453
Hennesey_Page_451_Chunk451
454 Chapter 5 Large and Fast: Exploiting Memory Hierarchy The data is similarly hierarchical: a level closer to the processor is generally a subset of any level further away, and all the data is stored at the lowest level. By analogy, the books on your desk form a subset of the library you are working in, which is in turn a subset of all the libraries on campus. Furthermore, as we move away from the processor, the levels take progressively longer to access, just as we might encounter in a hierarchy of campus libraries. A memory hierarchy can consist of multiple levels, but data is copied between only two adjacent levels at a time, so we can focus our attention on just two levels. The upper level—the one closer to the processor—is smaller and faster than the lower level, since the upper level uses technology that is more expensive. Figure 5.2 shows that the minimum unit of infor­mation that can be either present or not present in the two-level hierarchy is called a block or a line; in our library analogy, a block of information is one book. If the data requested by the processor appears in some block in the upper level, this is called a hit (analogous to your finding the information in one of the books on your desk). If the data is not found in the upper level, the request is called a miss. The lower level in the hierarchy is then accessed to retrieve the block con­taining the requested data. (Continuing our analogy, you go from your desk to the shelves to find the desired book.) The hit rate, or hit ratio, is the fraction of mem­ory ac­cesses found in the upper level; it is often used as a measure of the perfor­mance of the memory hierarchy. The miss rate (1 - hit rate) is the fraction of memory accesses not found in the ­upper level. block (or line) The minimum unit of information that can be­ either present or not present in a cache. hit rate The fraction of memory accesses found in a level of the memory hierarchy. miss rate The fraction of mem­ory accesses not found in a level of the memory hierarchy. FIGURE 5.1 The basic structure of a memory hierarchy. By implementing the memory system as a hierarchy, the user has the illusion of a memory that is as large as the largest level of the hierarchy, but can be accessed as if it were all built from the fastest memory. Flash memory has replaced disks in many embedded devices, and may lead to a new level in the storage hierarchy for desktop and server computers; see Section 6.4. Speed Fastest Slowest Smallest Biggest Size Cost ($/bit) Current technology Highest Lowest SRAM DRAM Magnetic disk Processor Memory Memory Memory
Hennesey_Page_452_Chunk452
Since performance is the major reason for having a memory hierarchy, the time to service hits and misses is important. Hit time is the time to access the upper level of the memory hierarchy, which includes the time needed to determine whether the access is a hit or a miss (that is, the time needed to look through the books on the desk). The miss penalty is the time to replace a block in the upper level with the corresponding block from the lower level, plus the time to deliver this block to the processor (or the time to get another book from the shelves and place it on the desk). Because the upper level is smaller and built using faster memory parts, the hit time will be much smaller than the time to access the next level in the hierarchy, which is the major component of the miss penalty. (The time to examine the books on the desk is much smaller than the time to get up and get a new book from the shelves.) As we will see in this chapter, the concepts used to build memory systems affect many other aspects of a computer, including how the operating system manages memory and I/O, how compilers generate code, and even how appli­cations use the computer. Of course, because all programs spend much of their time accessing memory, the memory system is necessarily a major factor in determining performance. The reliance on memory hierarchies to achieve performance has meant that programmers, who used to be able to think of memory as a flat, random access storage device, now need to understand that memory is a hierarchy to get good performance. We show how important this understanding is in later examples, such as Figure 5.18 on page 490. Since memory systems are critical to performance, computer designers devote a great deal of attention to these systems and develop sophisticated mechanisms for improving the performance of the memory system. In this chapter, we discuss the major conceptual ideas, although we use many simplifications and abstractions to keep the material manageable in length and complexity. hit time The time required to access a level of the ­memory hierarchy, including the time needed to ­determine whether the access is a hit or a miss. miss penalty The time required to fetch a block into a level of the memory hierarchy from the lower level, including the time to access the block, transmit it from one level to the other, insert it in the level that experienced the miss, and then pass the block to the requestor. FIGURE 5.2 Every pair of levels in the memory hierarchy can be thought of as having an upper and lower level. Within each level, the unit of information that is present or not is called a block or a line. Usually we transfer an entire block when we copy something between levels. Processor Data is transferred 5.1 Introduction 455
Hennesey_Page_453_Chunk453
456 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Programs exhibit both temporal locality, the tendency to reuse recently accessed data items, and spatial locality, the tendency to reference data items that are close to other recently accessed items. Memory hierarchies take advantage of temporal locality by keeping more recently accessed data items closer to the processor. Memory hierarchies take advantage of spatial locality by moving blocks consisting of multiple contiguous words in memory to upper levels of the hierarchy. Figure 5.3 shows that a memory hierarchy uses smaller and faster memory technologies close to the processor. Thus, accesses that hit in the highest level of the hierarchy can be processed quickly. Accesses that miss go to lower levels of the hierarchy, which are larger but slower. If the hit rate is high enough, the memory hierarchy has an effective access time close to that of the highest (and fastest) level and a size equal to that of the lowest (and largest) level. In most systems, the memory is a true hierarchy, meaning that data cannot be present in level i unless it is also present in level i + 1. The BIG Picture FIGURE 5.3 This diagram shows the structure of a memory hierarchy: as the distance from the processor increases, so does the size. This structure, with the appropriate operating mechanisms, allows the processor to have an access time that is determined primarily by level 1 of the hier­ archy and yet have a memory as large as level n. Maintaining this illusion is the subject of this chapter. Although the local disk is normally the bottom of the hierarchy, some systems use tape or a file server over a local area network as the next levels of the hierarchy. CPU Level 1 Level 2 Level n Increasing distance from the CPU in access time Levels in the memory hierarchy Size of the memory at each level
Hennesey_Page_454_Chunk454
Which of the following statements are generally true? 1. Caches take advantage of temporal locality. 2. On a read, the value returned depends on which blocks are in the cache. 3. Most of the cost of the memory hierarchy is at the highest level. 4. Most of the capacity of the memory hierarchy is at the lowest level. 5.2 The Basics of Caches In our library example, the desk acted as a cache—a safe place to store things (books) that we needed to examine. Cache was the name chosen to represent the level of the memory hierarchy between the processor and main memory in the first commercial computer to have this extra level. The memories in the datapath in Chapter 4 are simply replaced by caches. Today, although this remains the dominant use of the word cache, the term is also used to refer to any storage managed to take advantage of locality of access. Caches first appeared in research computers in the early 1960s and in production computers later in that same decade; every general- purpose computer built today, from servers to low-power embedded pro­cessors, includes caches. In this section, we begin by looking at a very simple cache in which the processor requests are each one word and the blocks also consist of a single word. (Readers already familiar with cache basics may want to skip to Section 5.3.) Figure 5.4 shows such a simple cache, before and after requesting a data item that is not initially in the cache. Before the request, the cache contains a collection of recent references X1, X2, . . . , Xn - 1, and the processor requests a word Xn that is not in the cache. This request results in a miss, and the word Xn is brought from memory into the cache. In looking at the scenario in Figure 5.4, there are two questions to answer: How do we know if a data item is in the cache? Moreover, if it is, how do we find it? The answers are related. If each word can go in exactly one place in the cache, then it is straightforward to find the word if it is in the cache. The simplest way to assign a location in the cache for each word in memory is to assign the cache location based on the address of the word in memory. This cache structure is called direct mapped, since each memory location is mapped directly to exactly one location in the cache. The typical mapping between addresses and cache loca­tions for a direct-mapped cache is usually simple. For example, almost all direct-mapped caches use this mapping to find a block: (Block address) modulo (Number of blocks in the cache) Check Yourself Cache: a safe place for hid­ing or storing things. Webster’s New World Diction­ary of the American Language, Third College Edition, 1988 direct-mapped cache A cache structure in which each memory location is mapped to exactly one location in the cache. 5.2 The Basics of Caches 457
Hennesey_Page_455_Chunk455
458 Chapter 5 Large and Fast: Exploiting Memory Hierarchy If the number of entries in the cache is a power of 2, then modulo can be com­puted simply by using the low-order log2 (cache size in blocks) bits of the address. Thus, an 8-block cache uses the three lowest bits (8 = 23) of the block address. For example, Figure 5.5 shows how the memory addresses between 1ten (00001two) and 29ten (11101two) map to locations 1ten (001two) and 5ten (101two) in a direct- mapped cache of eight words. Because each cache location can contain the contents of a number of different memory locations, how do we know whether the data in the cache corresponds to a requested word? That is, how do we know whether a requested word is in the cache or not? We answer this question by adding a set of tags to the cache. The tags ­contain the address information required to identify whether a word in the cache corresponds to the requested word. The tag needs only to contain the upper por­ tion of the address, corresponding to the bits that are not used as an index into the cache. For example, in Figure 5.5 we need only have the upper 2 of the 5 address bits in the tag, since the lower 3-bit index field of the address selects the block. Architects omit the index bits because they are redundant, since by defini­tion the index field of any address of a cache block must be that block number. We also need a way to recognize that a cache block does not have valid infor­ mation. For instance, when a processor starts up, the cache does not have good data, and the tag fields will be meaningless. Even after executing many instruc­tions, some of the cache entries may still be empty, as in Figure 5.4. Thus, we need to know that the tag should be ignored for such entries. The most common method is to add a valid bit to indicate whether an entry contains a valid address. If the bit is not set, there cannot be a match for this block. tag A field in a table used for a memory hierarchy that contains the address information required to identify whether the associated block in the hierarchy corre­sponds to a requested word. valid bit A field in the tables of a memory hierarchy that indicates that the associated block in the hierarchy contains valid data. FIGURE 5.4 The cache just before and just after a reference to a word Xn that is not ­initially in the cache. This reference causes a miss that forces the cache to fetch Xn from memory and insert it into the cache. X4 X1 Xn – 2 Xn – 1 X2 X3 a. Before the reference to Xn X4 X1 Xn – 2 Xn – 1 X2 X3 b. After the reference to Xn Xn
Hennesey_Page_456_Chunk456
For the rest of this section, we will focus on explaining how a cache deals with reads. In general, handling reads is a little simpler than handling writes, since reads do not have to change the contents of the cache. After seeing the basics of how reads work and how cache misses can be handled, we’ll examine the cache designs for real computers and detail how these caches handle writes. Accessing a Cache Below is a sequence of nine memory references to an empty eight-block cache, including the action for each reference. Figure 5.6 shows how the contents of the cache change on each miss. Since there are eight blocks in the cache, the low-order three bits of an address give the block number: FIGURE 5.5 A direct-mapped cache with eight entries showing the addresses of memory words between 0 and 31 that map to the same cache locations. Because there are eight words in the cache, an address X maps to the direct-mapped cache word X modulo 8. That is, the low-order log2(8) = 3 bits are used as the cache index. Thus, addresses 00001two, 01001two, 10001two, and 11001two all map to entry 001two of the cache, while addresses 00101two, 01101two, 10101two, and 11101two all map to entry 101two of the cache. Cache Memory 00001 10001 010 100 101 111 110 000 001 011 00101 01001 01101 10101 11001 11101 5.2 The Basics of Caches 459
Hennesey_Page_457_Chunk457
460 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Decimal address of reference Binary address of reference Hit or miss in cache Assigned cache block (where found or placed) 22 10110two miss (5.6b) (10110two mod 8) = 110two 26 11010two miss (5.6c) (11010two mod 8) = 010two 22 10110two hit (10110two mod 8) = 110two 26 11010two hit (11010two mod 8) = 010two 16 10000two miss (5.6d) (10000two mod 8) = 000two 3 00011two miss (5.6e) (00011two mod 8) = 011two 16 10000two hit (10000two mod 8) = 000two 18 10010two miss (5.6f) (10010two mod 8) = 010two 16 10000two hit (10000two mod 8) = 000two Since the cache is empty, several of the first references are misses; the caption of Figure 5.6 describes the actions for each memory reference. On the eighth refer­ ence we have conflicting demands for a block. The word at address 18 (10010two) should be brought into cache block 2 (010two). Hence, it must replace the word at address 26 (11010two), which is already in cache block 2 (010two). This behavior allows a cache to take advantage of temporal locality: recently referenced words ­replace less recently ­referenced words. This situation is directly analogous to needing a book from the shelves and having no more space on your desk—some book already on your desk must be returned to the shelves. In a direct-mapped cache, there is only one place to put the newly requested item and hence only one choice of what to replace. We know where to look in the cache for each possible address: the low-­order bits of an address can be used to find the unique cache entry to which the address could map. Figure 5.7 shows how a referenced address is divided into ■ ■A tag field, which is used to compare with the value of the tag field of the cache ■ ■A cache index, which is used to select the block The index of a cache block, together with the tag contents of that block, uniquely specifies the memory address of the word contained in the cache block. Because the index field is used as an address to reference the cache, and because an n-bit field has 2n values, the total number of entries in a direct-mapped cache must be a power of 2. In the MIPS architecture, since words are aligned to multiples of four bytes, the least significant two bits of every address specify a byte within a word. Hence, the least significant two bits are ignored when selecting a word in the block. The total number of bits needed for a cache is a function of the cache size and the address size, because the cache includes both the storage for the data and the tags. The size of the block above was one word, but normally it is several. For the following situation:
Hennesey_Page_458_Chunk458
Index V Tag Data Index V Tag Data 000 N 000 N 001 N 001 N 010 N 010 N 011 N 011 N 100 N 100 N 101 N 101 N 110 N 110 Y 10two Memory (10110two) 111 N 111 N a. The initial state of the cache after power-on b. After handling a miss of address (10110two) Index V Tag Data Index V Tag Data 000 N 000 Y 10two Memory (10000two) 001 N 001 N 010 Y 11two Memory (11010two) 010 Y 11two Memory (11010two) 011 N 011 N 100 N 100 N 101 N 101 N 110 Y 10two Memory (10110two) 110 Y 10two Memory (10110two) 111 N 111 N c. After handling a miss of address (11010two) d. After handling a miss of address (10000two) Index V Tag Data Index V Tag Data 000 Y 10two Memory (10000two) 000 Y 10two Memory (10000two) 001 N 001 N 010 Y 11two Memory (11010two) 010 Y 10two Memory (10010two) 011 Y 00two Memory (00011two) 011 Y 00two Memory (00011two) 100 N 100 N 101 N 101 N 110 Y 10two Memory (10110two) 110 Y 10two Memory (10110two) 111 N 111 N e. After handling a miss of address (00011two) f. After handling a miss of address (10010two) FIGURE 5.6 The cache contents are shown after each reference request that misses, with the index and tag fields shown in binary for the sequence of addresses on page 460. The cache is initially empty, with all valid bits (V entry in cache) turned off (N). The processor requests the following addresses: 10110two (miss), 11010two (miss), 10110two (hit), 11010two (hit), 10000two (miss), 00011two (miss), 10000two (hit), 10010two (miss), and 10000two (hit). The figures show the cache contents after each miss in the sequence has been handled. When address 10010two (18) is referenced, the entry for address 11010two (26) must be replaced, and a reference to 11010two will cause a subsequent miss. The tag field will contain only the upper portion of the address. The full address of a word contained in cache block i with tag field j for this cache is j × 8 + i, or equivalently the concatenation of the tag field j and the index i. For example, in cache f above, index 010two has tag 10two and corresponds to address 10010two. 5.2 The Basics of Caches 461
Hennesey_Page_459_Chunk459
462 Chapter 5 Large and Fast: Exploiting Memory Hierarchy ■ ■32-bit byte addresses ■ ■A direct-mapped cache ■ ■The cache size is 2n blocks, so n bits are used for the index ■ ■The block size is 2m words (2m+2 bytes), so m bits are used for the word within the block, and two bits are used for the byte part of the address the size of the tag field is 32 - (n + m + 2). FIGURE 5.7 For this cache, the lower portion of the address is used to select a cache entry consisting of a data word and a tag. This cache holds 1024 words or 4 KB. We assume 32-bit addresses in this chapter. The tag from the cache is compared against the upper portion of the address to determine whether the entry in the cache corresponds to the requested address. Because the cache has 210 (or 1024) words and a block size of one word, 10 bits are used to index the cache, leaving 32 - 10 - 2 = 20 bits to be compared against the tag. If the tag and upper 20 bits of the address are equal and the valid bit is on, then the request hits in the cache, and the word is supplied to the processor. Otherwise, a miss occurs. Address (showing bit positions) Data Hit Data Tag Valid Tag 32 20 Index 0 1 2 1023 1022 1021 = Index 20 10 Byte offset 31 30 13 12 11 2 1 0
Hennesey_Page_460_Chunk460
The total number of bits in a direct-mapped cache is 2n × (block size + tag size + valid field size). Since the block size is 2m words (2m+5 bits), and we need 1 bit for the valid field, the number of bits in such a cache is 2n × (2m × 32 + (32 - n - m - 2) + 1) = 2n × (2m × 32 + 31 - n - m). Although this is the actual size in bits, the naming convention is to exclude the size of the tag and valid field and to count only the size of the data. Thus, the cache in Figure 5.7 is called a 4 KB cache. Bits in a Cache How many total bits are required for a direct-mapped cache with 16 KB of data and 4-word blocks, assuming a 32-bit address? We know that 16 KB is 4K (212) words. With a block size of 4 words (22), there are 1024 (210) blocks. Each block has 4 × 32 or 128 bits of data plus a tag, which is 32 – 10 – 2 – 2 bits, plus a valid bit. Thus, the total cache size is 210 × (4 × 32 + (32 - 10 - 2 - 2) + 1) = 210 × 147 = 147 Kbits or 18.4 KB for a 16 KB cache. For this cache, the total number of bits in the cache is about 1.15 times as many as needed just for the storage of the data. Mapping an Address to a Multiword Cache Block Consider a cache with 64 blocks and a block size of 16 bytes. To what block number does byte address 1200 map? We saw the formula on page 457. The block is given by (Block address) modulo (Number of blocks in the cache) EXAMPLE ANSWER EXAMPLE ANSWER 5.2 The Basics of Caches 463
Hennesey_Page_461_Chunk461
464 Chapter 5 Large and Fast: Exploiting Memory Hierarchy where the address of the block is ​ Byte address  Bytes per block ​ Notice that this block address is the block containing all addresses between ​ ​ Byte address  Bytes per block ​ ​ × Bytes per block and ​ ​ Byte address  Bytes per block ​ ​ × Bytes per block + (Bytes per block - 1) Thus, with 16 bytes per block, byte address 1200 is block address ​ ​ 1200 ____ 16 ​ ​ = 75 which maps to cache block number (75 modulo 64) = 11. In fact, this block maps all addresses between 1200 and 1215. Larger blocks exploit spatial locality to lower miss rates. As Figure 5.8 shows, increasing the block size usually decreases the miss rate. The miss rate may go up eventually if the block size becomes a significant fraction of the cache size, because the number of blocks that can be held in the cache will become small, and there will be a great deal of competition for those blocks. As a result, a block will be bumped out of the cache before many of its words are accessed. Stated alterna­tively, spatial locality among the words in a block decreases with a very large block; consequently, the benefits in the miss rate become smaller. A more serious problem associated with just increasing the block size is that the cost of a miss increases. The miss penalty is determined by the time required to fetch the block from the next lower level of the hierarchy and load it into the cache. The time to fetch the block has two parts: the latency to the first word and the transfer time for the rest of the block. Clearly, unless we change the memory system, the transfer time—and hence the miss penalty—will likely increase as the block size increases. Furthermore, the improvement in the miss rate starts to decrease as the blocks become larger. The result is that the increase in the miss penalty overwhelms the decrease in the miss rate for blocks that are too large, and cache performance thus decreases. Of course, if we design the memory to transfer larger blocks more efficiently, we can increase the block size and ­obtain further improvements in cache performance. We discuss this topic in the next section.
Hennesey_Page_462_Chunk462
Elaboration: Although it is hard to do anything about the longer latency component of the miss penalty for large blocks, we may be able to hide some of the transfer time so that the miss penalty is effectively smaller. The simplest method for doing this, called early restart, is sim­ply to resume execution as soon as the requested word of the block is returned, rather than wait for the entire block. Many processors use this technique for instruction access, where it works best. Instruction accesses are largely sequential, so if the memory system can deliver a word every clock cycle, the processor may be able to restart operation when the requested word is returned, with the memory system delivering new instruction words just in time. This technique is usually less effective for data caches because it is likely that the words will be requested from the block in a less predictable way, and the probability that the processor will need another word from a different cache block before the transfer completes is high. If the processor cannot access the data cache because a transfer is ongoing, then it must stall. An even more sophisticated scheme is to organize the memory so that the requested word is transferred from the memory to the cache first. The remainder of the block is then transferred, starting with the address after the requested word and wrapping around to the beginning of the block. This technique, called requested word first or critical word first, can be slightly faster than early restart, but it is limited by the same properties that limit early restart. Handling Cache Misses Before we look at the cache of a real system, let’s see how the control unit deals with cache misses. (We describe a cache controller in detail in Section 5.7). The control unit must detect a miss and process the miss by fetching the requested data cache miss A request for data from the cache that cannot be filled because the data is not present in the cache. FIGURE 5.8 Miss rate versus block size. Note that the miss rate actually goes up if the block size is too large relative to the cache size. Each line represents a cache of different size. (This figure is independent of associativity, discussed soon.) Unfortunately, SPEC CPU2000 traces would take too long if block size were included, so this data is based on SPEC92. 4K 16 10% 16K 64K 256K 5% 0% 32 64 128 256 Miss rate Block size 5.2 The Basics of Caches 465
Hennesey_Page_463_Chunk463
466 Chapter 5 Large and Fast: Exploiting Memory Hierarchy from memory (or, as we shall see, a lower-level cache). If the cache reports a hit, the computer continues using the data as if nothing happened. Modifying the control of a processor to handle a hit is trivial; ­misses, however, require some extra work. The cache miss handling is done in collaboration with the processor con­trol unit and with a separate controller that initiates the memory access and refills the cache. The processing of a cache miss creates a pipeline stall (Chapter 4) as opposed to an interrupt, which would require saving the state of all registers. For a cache miss, we can stall the entire processor, essentially freezing the contents of the temporary and programmer-visible registers, while we wait for memory. More sophisticated out-of-order processors can allow execution of instructions while waiting for a cache miss, but we’ll assume in-order processors that stall on cache misses in this section. Let’s look a little more closely at how instruction misses are handled; the same approach can be easily extended to handle data misses. If an instruction access results in a miss, then the content of the Instruction register is invalid. To get the proper instruction into the cache, we must be able to instruct the lower level in the memory hierarchy to perform a read. Since the program counter is incre­ mented in the first clock cycle of execution, the address of the instruction that generates an instruction cache miss is equal to the value of the program counter minus 4. Once we have the address, we need to instruct the main memory to per­ form a read. We wait for the memory to respond (since the access will take multi­ ple clock cycles), and then write the words containing the desired instruction into the cache. We can now define the steps to be taken on an instruction cache miss: 1. Send the original PC value (current PC – 4) to the memory. 2. Instruct main memory to perform a read and wait for the memory to com­ plete its access. 3. Write the cache entry, putting the data from memory in the data portion of the entry, writing the upper bits of the address (from the ALU) into the tag field, and turning the valid bit on. 4. Restart the instruction execution at the first step, which will refetch the instruction, this time finding it in the cache. The control of the cache on a data access is essentially identical: on a miss, we simply stall the processor until the memory responds with the data. Handling Writes Writes work somewhat differently. Suppose on a store instruction, we wrote the data into only the data cache (without changing main memory); then, after the write into the cache, memory would have a different value from that in the cache. In such a case, the cache and memory are said to be inconsistent. The simplest way
Hennesey_Page_464_Chunk464
to keep the main memory and the cache consistent is always to write the data into both the memory and the cache. This scheme is called write-through. The other key aspect of writes is what occurs on a write miss. We first fetch the words of the block from memory. After the block is fetched and placed into the cache, we can overwrite the word that caused the miss into the cache block. We also write the word to main memory using the full address. Although this design handles writes very simply, it would not provide very good performance. With a write-through scheme, every write causes the data to be written to main memory. These writes will take a long time, likely at least 100 processor clock cycles, and could slow down the processor considerably. For example, suppose 10% of the instructions are stores. If the CPI without cache misses was 1.0, spending 100 extra cycles on every write would lead to a CPI of 1.0 + 100 × 10% = 11, reducing performance by more than a factor of 10. One solution to this problem is to use a write buffer. A write buffer stores the data while it is waiting to be written to memory. After writing the data into the cache and into the write buffer, the processor can continue execution. When a write to main memory completes, the entry in the write buffer is freed. If the write buffer is full when the processor reaches a write, the processor must stall until there is an empty position in the write buffer. Of course, if the rate at which the memory can complete writes is less than the rate at which the processor is gener­ating writes, no amount of buffering can help, because writes are being generated faster than the memory system can accept them. The rate at which writes are generated may also be less than the rate at which the memory can accept them, and yet stalls may still occur. This can ­happen when the writes occur in bursts. To reduce the occurrence of such stalls, processors usu­ally increase the depth of the write buffer beyond a single entry. The alternative to a write-through scheme is a scheme called write-back or copy back. In a write-back scheme, when a write occurs, the new value is written only to the block in the cache. The modi­fied block is written to the lower level of the hierarchy when it is re­placed. Write-back schemes can improve performance, especially when processors can generate writes as fast or faster than the writes can be handled by main memory; a write-back scheme is, however, more complex to implement than write-through. In the rest of this section, we describe caches from real processors, and we examine how they handle both reads and writes. In Section 5.5, we will describe the handling of writes in more detail. Elaboration: Writes introduce several complications into caches that are not present for reads. Here we discuss two of them: the policy on write misses and efficient implementation of writes in write-back caches. Consider a miss in a write-through cache. The most common strategy is to allocate a block in the cache, called write allocate. The block is fetched from memory and then the appropriate portion of the block is overwritten. An alternative strategy is to update the portion of the block in memory but not put it in the cache, called no write allocate. The motiva­tion is write-through A scheme in which writes always update both the cache and the next lower level of the memory hierarchy, ensuring that data is always con­sistent between the two. write buffer A queue that holds data while the data is waiting to be written to memory. write-back A scheme that han­dles writes by updating values only to the block in the cache, then writing the modified block to the lower level of the hierar­chy when the block is replaced. 5.2 The Basics of Caches 467
Hennesey_Page_465_Chunk465
468 Chapter 5 Large and Fast: Exploiting Memory Hierarchy that some­times programs write entire blocks of data, such as when the operating system zeros a page of memory. In such cases, the fetch associated with the initial write miss may be unnecessary. Some computers allow the write allocation policy to be changed on a per page basis. Actually implementing stores efficiently in a cache that uses a write-back strategy is more complex than in a write-through cache. A write-through cache can write the data into the cache and read the tag; if the tag mismatches, then a miss occurs. Because the cache is write-through, the overwriting of the block in the cache is not catastrophic, since memory has the correct value. In a write-back cache, we must first write the block back to memory if the data in the cache is modified and we have a cache miss. If we simply overwrote the block on a store instruction before we knew whether the store had hit in the cache (as we could for a write-through cache), we would destroy the contents of the block, which is not backed up in the next lower level of the mem­ory hierarchy. In a write-back cache, because we cannot overwrite the block, stores either require two cycles (a cycle to check for a hit followed by a cycle to actually perform the write) or require a write buffer to hold that data—effectively allowing the store to take only one cycle by pipelining it. When a store buffer is used, the processor does the cache lookup and places the data in the store buffer during the normal cache access cycle. Assuming a cache hit, the new data is written from the store buffer into the cache on the next unused cache access cycle. By comparison, in a write-through cache, writes can always be done in one cycle. We read the tag and write the data portion of the selected block. If the tag matches the address of the block being written, the processor can continue normally, since the correct block has been updated. If the tag does not match, the processor generates a write miss to fetch the rest of the block corresponding to that address. Many write-back caches also include write buffers that are used to reduce the miss penalty when a miss replaces a modified block. In such a case, the modified block is moved to a write-back buffer associated with the cache while the requested block is read from memory. The write-back buffer is later written back to mem­ory. Assuming another miss does not occur immedi­ately, this technique halves the miss penalty when a dirty block must be replaced. An Example Cache: The Intrinsity FastMATH Processor The Intrinsity FastMATH is a fast embedded microprocessor that uses the MIPS architecture and a simple cache implementation. Near the end of the chapter, we will examine the more complex cache design of the AMD Opteron X4 (Barcelona), but we start with this simple, yet real, example for pedagogical reasons. Figure 5.9 shows the organization of the Intrinsity FastMATH data cache. This processor has a 12-stage pipeline, similar to that discussed late in Chapter 4. When operating at peak speed, the processor can request both an instruction word and a data word on every clock. To satisfy the demands of the pipeline with­out stalling, separate instruction and data caches are used. Each cache is 16 KB, or 4K words, with 16-word blocks. Read requests for the cache are straightforward. Because there are separate data and instruction caches, we need separate control signals to read and write
Hennesey_Page_466_Chunk466
each cache. (Remember that we need to update the instruction cache when a miss occurs.) Thus, the steps for a read request to either cache are as follows: 1. Send the address to the appropriate cache. The address comes either from the PC (for an instruction) or from the ALU (for data). 2. If the cache signals hit, the requested word is available on the data lines. Since there are 16 words in the desired block, we need to select the right one. A block index field is used to control the multiplexor (shown at the bottom of the figure), which selects the requested word from the 16 words in the indexed block. FIGURE 5.9 The 16 KB caches in the Intrinsity FastMATH each contain 256 blocks with 16 words per block. The tag field is 18 bits wide and the index field is 8 bits wide, while a 4-bit field (bits 5–2) is used to index the block and select the word from the block using a 16‑to‑1 multi­plexor. In practice, to eliminate the multiplexor, caches use a separate large RAM for the data and a smaller RAM for the tags, with the block offset supply­ing the extra address bits for the large data RAM. In this case, the large RAM is 32 bits wide and must have 16 times as many words as blocks in the cache. Address (showing bit positions) Data Hit Data Tag V Tag 32 18 = Index 18 8 Byte offset 31 14 13 2 1 0 6 5 4 Block offset 256 entries 512 bits 18 bits Mux 32 32 32 5.2 The Basics of Caches 469
Hennesey_Page_467_Chunk467
470 Chapter 5 Large and Fast: Exploiting Memory Hierarchy 3. If the cache signals miss, we send the address to the main memory. When the memory returns with the data, we write it into the cache and then read it to fulfill the request. For writes, the Intrinsity FastMATH offers both write-through and write-back, leaving it up to the operating system to decide which strategy to use for an appli­ cation. It has a one-entry write buffer. Instruction miss rate Data miss rate Effective combined miss rate 0.4% 11.4% 3.2% FIGURE 5.10 Approximate instruction and data miss rates for the Intrinsity FastMATH processor for SPEC CPU2000 benchmarks. The combined miss rate is the effective miss rate seen for the combination of the 16 KB instruction cache and 16 KB data cache. It is obtained by weighting the instruc­ tion and data individual miss rates by the frequency of instruction and data references. What cache miss rates are attained with a cache structure like that used by the Intrinsity FastMATH? Figure 5.10 shows the miss rates for the instruction and data caches. The combined miss rate is the effective miss rate per reference for each program after accounting for the differing frequency of instruction and data accesses. Although miss rate is an important characteristic of cache designs, the ultimate measure will be the effect of the memory system on program execution time; we’ll see how miss rate and execution time are related shortly. Elaboration: A combined cache with a total size equal to the sum of the two split caches will usually have a better hit rate. This higher rate occurs because the combined cache does not rigidly divide the number of entries that may be used by instructions from those that may be used by data. Nonetheless, many processors use a split instruction and data cache to increase cache bandwidth. (There may also be fewer conflict misses; see Section 5.5.) Here are miss rates for caches the size of those found in the Intrinsity FastMATH processor, and for a combined cache whose size is equal to the sum of the two caches: ■ ■Total cache size: 32 KB ■ ■Split cache effective miss rate: 3.24% ■ ■Combined cache miss rate: 3.18% The miss rate of the split cache is only slightly worse. The advantage of doubling the cache bandwidth, by supporting both an instruction and data access simultaneously, easily overcomes the disadvantage of a slightly increased miss rate. This observation cautions us that we cannot use miss rate as the sole measure of cache per­formance, as Section 5.3 shows. split cache A scheme in which a level of the memory ­hierarchy is composed of two independent caches that operate in parallel with each other, with one ­handling instructions and one handling data.
Hennesey_Page_468_Chunk468
Designing the Memory System to Support Caches Cache misses are satisfied from main memory, which is constructed from DRAMs. In Section 5.1, we saw that the primary emphasis with DRAMs is on cost and density. Although it is difficult to reduce the latency to fetch the first word from memory, we can reduce the miss penalty if we increase the bandwidth from the memory to the cache. This reduction allows larger block sizes to be used while still maintaining a low miss penalty, similar to that for a smaller block. The processor is traditionally connected to memory over a bus. (As we’ll see in Chapter 6, that tradition is changing, but the actual interconnect technology doesn’t matter in this chapter, so we’ll use the term bus.) The clock rate of the bus is usually much slower than the processor. The speed of this bus affects the miss penalty. To understand the impact of different organizations of memory, let’s define a set of hypothetical memory access times. Assume ■ ■1 memory bus clock cycle to send the address ■ ■15 memory bus clock cycles for each DRAM access initiated ■ ■1 memory bus clock cycle to send a word of data If we have a cache block of four words and a one-word-wide bank of DRAMs, the miss penalty would be 1 + 4 × 15 + 4 × 1 = 65 memory bus clock cycles. Thus, the number of bytes transferred per bus clock cycle for a single miss would be ​ 4 × 4  65 ​ = 0.25 Figure 5.11 shows three options for designing the memory system. The first option follows what we have been assuming: memory is one word wide, and all accesses are made sequentially. The second option increases the bandwidth to memory by widening the memory and the buses between the processor and mem­ ory; this allows parallel access to multiple words of the block. The third option increases the bandwidth by widening the memory but not the interconnection bus. Thus, we still pay a cost to transmit each word, but we can avoid paying the cost of the access latency more than once. Let’s look at how much these other two options improve the 65-cycle miss penalty that we would see for the first option in Figure 5.11(a). Increasing the width of the memory and the bus will increase the memory bandwidth proportionally, decreasing both the access time and transfer time portions of the miss penalty. With a main memory width of two words, the miss pen­alty drops from 65 memory bus clock cycles to 1 + (2 × 15) + 2 × 1 = 33 memory bus clock cycles. The bandwidth for a ­single miss is then 0.48 (almost twice as high) bytes per bus clock cycle for a memory that is two words wide. The major costs of this enhancement are the wider bus and the potential increase in cache access time due to the multiplexor and control logic between the processor and cache. 5.2 The Basics of Caches 471
Hennesey_Page_469_Chunk469
472 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Instead of making the entire path between the memory and cache wider, the memory chips can be organized in banks to read or write multiple words in one access time rather than reading or writing a single word each time. Each bank could be one word wide so that the width of the bus and the cache need not change, but sending an address to several banks permits them all to read simulta­neously. This scheme, which is called interleaving, retains the advantage of incur­ring the full memory latency only once. For example, with four banks, the time to get a four-word block would consist of 1 cycle to transmit the address and read request to the banks, 15 cycles for all four banks to access memory, and 4 cycles to send the four words back to the cache. This yields a miss penalty of 1 + (1 × 15) + 4 × 1 = 20 memory bus clock cycles. This is an effective bandwidth per miss of 0.80 bytes per clock, or about three times the bandwidth for the one-word-wide ­memory and bus. FIGURE 5.11 The primary method of achieving higher memory bandwidth is to increase the physical or logical width of the memory system. In this figure, memory bandwidth is improved two ways. The simplest design, (a), uses a memory where all components are one word wide; (b) shows a wider memory, bus, and cache; while (c) shows a narrow bus and cache with an interleaved memory. In (b), the logic between the cache and processor consists of a multiplexor used on reads and control logic to update the appropriate words of the cache on writes. Processor Cache Memory Bus One-word-wide memory organization a. b. Wider memory organization Processor Cache Memory Bus Multiplexor Processor Cache Bus Memory bank 0 Memory bank 1 Memory bank 2 Memory bank 3 c. Interleaved memory organization
Hennesey_Page_470_Chunk470
Banks are also valuable on writes. Each bank can write indepen­dently, quadrupling the write bandwidth and leading to fewer stalls in a write-through cache. As we will see, an alternative strategy for writes makes interleaving even more attractive. Because of the ubiquity of caches and the desire for larger block sizes, DRAM manufacturers provide for a burst access to data from a series of sequential loca­ tions in the DRAM. The newest development is Double Data Rate (DDR) DRAMs. The name means data transfers on both the leading and falling edge of the clock, thereby getting twice as much bandwidth as you might expect based on the clock rate and the data width. To deliver such high bandwidth, the internal DRAM is organized as interleaved memory banks. The advantage of such optimizations is that they use the circuitry already largely on the DRAMs, adding little cost to the system while achieving a signifi­cant improvement in bandwidth. Section C.9 of Appendix C describes the internal architecture of DRAMs and how these optimizations are implemented. Elaboration: Memory chips are organized to produce a number of output bits, usually 4 to 32, with 16 being the most popular in 2008. We describe the organization of a RAM as d × w, where d is the number of addressable locations (the depth) and w is the output (or width of each location). DRAMs are logically organized as rectangular arrays, and access time is divided into row access and column ac­cess. DRAMs buffer a row. Burst transfers allow repeated accesses to the buffer without a row access time. The buffer acts like an SRAM; by changing column address, random bits can be accessed in the buffer until the next row access. This capability changes the access time significantly, since the access time to bits in the row is much lower. Figure 5.12 shows how the density, cost, and access time of DRAMs have changed over the years. To improve the interface to processors, DRAMs added clocks and are properly called Syn­chronous DRAMs or SDRAMs. The advantage of SDRAMs is that the use of a clock elimi­nates the time for the memory and processor to synchronize. Elaboration: One way to measure the performance of the memory system behind the caches is the Stream benchmark [McCalpin, 1995]. It measures the performance of long vector operations. They have no temporal locality and they access arrays that are larger than the cache of the computer being tested. Elaboration: The burst mode for DDR memory is also found on memory buses, such as the Intel Duo Core Front Side Bus. 5.2 The Basics of Caches 473
Hennesey_Page_471_Chunk471
474 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Year introduced Chip size $ per GB Total access time to a new row/column Column access time to existing row 1980 64 Kbit $1,500,000 250 ns 150 ns 1983 256 Kbit $500,000 185 ns 100 ns 1985 1 Mbit $200,000 135 ns 40 ns 1989 4 Mbit $50,000 110 ns 40 ns 1992 16 Mbit $15,000 90 ns 30 ns 1996 64 Mbit $10,000 60 ns 12 ns 1998 128 Mbit $4,000 60 ns 10 ns 2000 256 Mbit $1,000 55 ns 7 ns 2004 512 Mbit $250 50 ns 5 ns 2007 1 Gbit $50 40 ns 1.25 ns FIGURE 5.12 DRAM size increased by multiples of four approximately once every three years until 1996, and thereafter considerably slower. The improvements in access time have been slower but continuous, and cost roughly tracks density improvements, although cost is often affected by other issues, such as availability and demand. The cost per gigabyte is not adjusted for inflation. Summary We began the previous section by examining the simplest of caches: a direct-mapped cache with a one-word block. In such a cache, both hits and misses are simple, since a word can go in exactly one location and there is a separate tag for every word. To keep the cache and memory consistent, a write-through scheme can be used, so that every write into the cache also causes memory to be updated. The alternative to write-through is a write-back scheme that copies a block back to memory when it is replaced; we’ll discuss this scheme further in upcoming sections. To take advantage of spatial locality, a cache must have a block size larger than one word. The use of a larger block decreases the miss rate and improves the effi­ ciency of the cache by reducing the amount of tag storage relative to the amount of data storage in the cache. Although a larger block size decreases the miss rate, it can also increase the miss penalty. If the miss penalty increased linearly with the block size, larger blocks could easily lead to lower performance. To avoid performance loss, the bandwidth of main memory is increased to transfer cache blocks more efficiently. Common methods for increasing bandwidth external to the DRAM are making the memory wider and interleaving. DRAM designers have steadily improved the interface between the processor and memory to increase the bandwidth of burst mode transfers to reduce the cost of larger cache block sizes.
Hennesey_Page_472_Chunk472
The speed of the memory system affects the designer’s decision on the size of the cache block. Which of the following cache designer guidelines are generally valid? 1. The shorter the memory latency, the smaller the cache block 2. The shorter the memory latency, the larger the cache block 3. The higher the memory bandwidth, the smaller the cache block 4. The higher the memory bandwidth, the larger the cache block 5.3  Measuring and Improving Cache Performance In this section, we begin by examining ways to measure and analyze cache perfor­ mance. We then explore two different techniques for improving cache ­performance. One focuses on reducing the miss rate by reducing the probability that two differ­ ent memory blocks will contend for the same cache location. The sec­ond tech­ nique reduces the miss penalty by adding an additional level to the hier­archy. This technique, called multilevel caching, first appeared in high-end computers selling for more than $100,000 in 1990; since then it has become common on desktop computers selling for less than $500! CPU time can be divided into the clock cycles that the CPU spends executing the program and the clock cycles that the CPU spends waiting for the memory system. Normally, we assume that the costs of cache accesses that are hits are part of the normal CPU execution cycles. Thus, CPU time = (CPU execution clock cycles + Memory-stall clock cycles) × Clock cycle time The memory-stall clock cycles come primarily from cache misses, and we make that assumption here. We also restrict the discussion to a simplified model of the memory system. In real processors, the stalls generated by reads and writes can be quite complex, and accurate performance prediction usually requires very detailed simulations of the processor and memory system. Memory-stall clock cycles can be defined as the sum of the stall cycles coming from reads plus those coming from writes: Memory-stall clock cycles = Read-stall cycles + Write-stall cycles Check Yourself 5.3 Measuring and Improving Cache Performance 475
Hennesey_Page_473_Chunk473
476 Chapter 5 Large and Fast: Exploiting Memory Hierarchy The read-stall cycles can be defined in terms of the number of read accesses per program, the miss penalty in clock cycles for a read, and the read miss rate: Read-stall cycles = ​ Reads  Program ​ × Read miss rate × Read miss penalty Writes are more complicated. For a write-through scheme, we have two sources of stalls: write misses, which usually require that we fetch the block before continu­ ing the write (see the Elaboration on page 467 for more details on dealing with writes), and write buffer stalls, which occur when the write buffer is full when a write occurs. Thus, the cycles stalled for writes equals the sum of these two: Write-stall cycles = ​( ​ Writes  Program ​ × Write miss rate × Write miss penalty )​ + Write buffer stalls Because the write buffer stalls depend on the proximity of writes, and not just the frequency, it is not possible to give a simple equation to compute such stalls. For­tunately, in systems with a reasonable write buffer depth (e.g., four or more words) and a memory capable of accepting writes at a rate that significantly exceeds the average write frequency in programs (e.g., by a factor of 2), the write buffer stalls will be small, and we can safely ignore them. If a system did not meet these criteria, it would not be well designed; instead, the designer should have used either a deeper write buffer or a write-back organization. Write-back schemes also have potential additional stalls arising from the need to write a cache block back to memory when the block is replaced. We will discuss this more in Section 5.5. In most write-through cache organizations, the read and write miss penalties are the same (the time to fetch the block from memory). If we assume that the write buffer stalls are negligible, we can combine the reads and writes by using a single miss rate and the miss penalty: Memory-stall clock cycles = ​ Memory accesses  Program ​ × Miss rate × Miss penalty We can also factor this as Memory-stall clock cycles = ​ Instructions  Program ​ × ​ Misses  Instruction ​ × Miss penalty Let’s consider a simple example to help us understand the impact of cache perfor­ mance on processor performance.
Hennesey_Page_474_Chunk474
Calculating Cache Performance Assume the miss rate of an instruction cache is 2% and the miss rate of the data cache is 4%. If a processor has a CPI of 2 without any memory stalls and the miss penalty is 100 cycles for all misses, determine how much faster a pro­ cessor would run with a perfect cache that never missed. Assume the frequen­cy of all loads and stores is 36%. The number of memory miss cycles for instructions in terms of the Instruc­ tion count (I) is Instruction miss cycles = I × 2% × 100 = 2.00 × I As the frequency of all loads and stores is 36%, we can find the number of memory miss cycles for data references: Data miss cycles = I × 36% × 4% × 100 = 1.44 × I The total number of memory-stall cycles is 2.00 I + 1.44 I = 3.44 I. This is more than three cycles of memory stall per instruction. Accordingly, the total CPI including memory stalls is 2 + 3.44 = 5.44. Since there is no change in instruction count or clock rate, the ratio of the CPU execution times is ​ CPU time with stalls  CPU time with perfect cache ​ = ​ I × CPIstall × Clock cycle  I × CPIperfect × Clock cycle ​ = ​ CPIstall  CPIperfect ​ = ​ 5.44  2 ​ The performance with the perfect cache is better by ​ 5.44  2 ​ = 2.72. What happens if the processor is made faster, but the memory system is not? The amount of time spent on memory stalls will take up an increasing fraction of the execution time; Amdahl’s law, which we examined in Chapter 1, reminds us of this fact. A few simple examples show how serious this problem can be. Suppose we speed-up the computer in the previous example by reducing its CPI from 2 to 1 without changing the clock rate, which might be done with an improved pipeline. The system with cache misses would then have a CPI of 1 + 3.44 = 4.44, and the system with the perfect cache would be EXAMPLE ANSWER 5.3 Measuring and Improving Cache Performance 477
Hennesey_Page_475_Chunk475
478 Chapter 5 Large and Fast: Exploiting Memory Hierarchy ​ 4.44  1 ​ = 4.44 times faster. The amount of execution time spent on memory stalls would have risen from ​ 3.44  5.44 ​ = 63% to ​ 3.44  4.44 ​ = 77%. Similarly, increasing the clock rate without changing the memory system also increases the performance lost due to cache misses. The previous examples and equations assume that the hit time is not a fac­tor in determining cache performance. Clearly, if the hit time increases, the total time to access a word from the memory system will increase, possibly causing an increase in the processor cycle time. Although we will see addi­tional examples of what can increase hit time shortly, one example is increas­ing the cache size. A larger cache could clearly have a longer access time, just as, if your desk in the library was very large (say, 3 square meters), it would take longer to locate a book on the desk. An increase in hit time likely adds another stage to the pipeline, since it may take multiple cycles for a cache hit. Although it is more complex to calculate the performance impact of a deeper pipeline, at some point the increase in hit time for a larger cache could domi­nate the improvement in hit rate, leading to a decrease in processor performance. To capture the fact that the time to access data for both hits and misses affects performance, designers sometime use average memory access time (AMAT) as a way to examine alternative cache designs. Average memory access time is the average time to access memory considering both hits and misses and the frequency of different accesses; it is equal to the following: AMAT = Time for a hit + Miss rate × Miss penalty Calculating Average Memory Access Time Find the AMAT for a processor with a 1 ns clock cycle time, a miss penalty of 20 clock cycles, a miss rate of 0.05 misses per instruction, and a cache access time (in­cluding hit detection) of 1 clock cycle. Assume that the read and write miss penalties are the same and ignore other write stalls. EXAMPLE
Hennesey_Page_476_Chunk476
The average memory access time per instruction is AMAT = Time for a hit + Miss rate × Miss penalty = 1 + 0.05 × 20 = 2 clock cycles or 2 ns. The next subsection discusses alternative cache organizations that decrease miss rate but may sometimes increase hit time; additional examples appear in Section 5.11, Fallacies and Pitfalls. Reducing Cache Misses by More Flexible Placement of Blocks So far, when we place a block in the cache, we have used a simple placement scheme: A block can go in exactly one place in the cache. As mentioned earlier, it is called direct mapped because there is a direct mapping from any block address in memory to a single location in the upper level of the hierarchy. However, there is actually a whole range of schemes for placing blocks. Direct mapped, where a block can be placed in exactly one location, is at one extreme. At the other extreme is a scheme where a block can be placed in any location in the cache. Such a scheme is called fully associative, because a block in memory may be associated with any entry in the cache. To find a given block in a fully asso­ ciative cache, all the entries in the cache must be searched because a block can be placed in any one. To make the search practical, it is done in parallel with a com­ parator associated with each cache entry. These comparators significantly increase the hardware cost, effectively making fully associative placement practical only for caches with small numbers of blocks. The middle range of designs between direct mapped and fully associative is called set associative. In a set-associative cache, there are a fixed number of ­locations where each block can be placed. A set-associative cache with n loca­tions for a block is called an n-way set-associative cache. An n-way set-associa­tive cache consists of a number of sets, each of which consists of n blocks. Each block in the memory maps to a unique set in the cache given by the index field, and a block can be placed in any element of that set. Thus, a set-associative placement combines direct-mapped ANSWER fully associative cache A cache structure in which a block can be placed in any location in the cache. set-associative cache A cache that has a fixed number of loca­tions (at least two) where each block can be placed. 5.3 Measuring and Improving Cache Performance 479
Hennesey_Page_477_Chunk477
480 Chapter 5 Large and Fast: Exploiting Memory Hierarchy placement and fully associative placement: a block is directly mapped into a set, and then all the blocks in the set are searched for a match. For example, Figure 5.13 shows where block 12 may be placed in a cache with eight blocks total, accord­ing to the three block place­ment policies. Remember that in a direct-mapped cache, the position of a memory block is given by (Block number) modulo (Number of blocks in the cache) In a set-associative cache, the set containing a memory block is given by (Block number) modulo (Number of sets in the cache) Since the block may be placed in any element of the set, all the tags of all the elements of the set must be searched. In a fully associative cache, the block can go anywhere, and all tags of all the blocks in the cache must be searched. FIGURE 5.13 The location of a memory block whose address is 12 in a cache with eight blocks varies for direct- mapped, set-associative, and fully associative placement. In direct-mapped placement, there is only one cache block where memory block 12 can be found, and that block is given by (12 modulo 8) = 4. In a two-way set-associative cache, there would be four sets, and memory block 12 must be in set (12 mod 4) = 0; the memory block could be in either element of the set. In a fully associative placement, the memory block for block address 12 can appear in any of the eight cache blocks. Direct mapped 2 4 5 7 6 0 1 3 Block # Data Tag Search 1 2 Set associative 2 0 1 3 Set # Data Tag Search 1 2 Fully associative Data Tag Search 1 2
Hennesey_Page_478_Chunk478
We can also think of all block placement strategies as a variation on set associativity. Figure 5.14 shows the possible associativity structures for an eight- block cache. A direct-mapped cache is simply a one-way set-associative cache: each cache entry holds one block and each set has one element. A fully associative cache with m entries is simply an m-way set-associative cache; it has one set with m blocks, and an entry can reside in any block within that set. FIGURE 5.14 An eight-block cache configured as direct mapped, two-way set associa­tive, four-way set associative, and fully associative. The total size of the cache in blocks is equal to the number of sets times the associativity. Thus, for a fixed cache size, increasing the associativity decreases the number of sets while increasing the number of elements per set. With eight blocks, an eight-way set‑associative cache is the same as a fully associative cache. Eight-way set associative (fully associative) Tag Tag Data Data Tag Tag Data Data Tag Tag Data Data Tag Tag Data Data Tag Tag Data Data Tag Tag Data Data Set Four-way set associative Tag Tag Data Data Set 0 1 0 1 2 3 0 1 2 3 4 5 6 7 Two-way set associative Tag Data Block One-way set associative (direct mapped) The advantage of increasing the degree of associativity is that it usually decreases the miss rate, as the next example shows. The main disadvantage, which we discuss in more detail shortly, is a potential increase in the hit time. 5.3 Measuring and Improving Cache Performance 481
Hennesey_Page_479_Chunk479
482 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Misses and Associativity in Caches Assume there are three small caches, each consisting of four one-word blocks. One cache is fully associative, a second is two-way set-associative, and the third is direct-mapped. Find the number of misses for each cache organiza­tion given the following sequence of block addresses: 0, 8, 0, 6, and 8. The direct-mapped case is easiest. First, let’s determine to which cache block each block address maps: Block address Cache block 0 (0 modulo 4) = 0 6 (6 modulo 4) = 2 8 (8 modulo 4) = 0 Now we can fill in the cache contents after each reference, using a blank ­entry to mean that the block is invalid, colored text to show a new entry added to the cache for the associated reference, and plain text to show an old entry in the cache: Address of memory block accessed Hit or miss Contents of cache blocks after reference 0 1 2 3 0 miss Memory[0] 8 miss Memory[8] 0 miss Memory[0] 6 miss Memory[0] Memory[6] 8 miss Memory[8] Memory[6] The direct-mapped cache generates five misses for the five accesses. The set-associative cache has two sets (with indices 0 and 1) with two elements per set. Let’s first determine to which set each block address maps: Block address Cache set 0 (0 modulo 2) = 0 6 (6 modulo 2) = 0 8 (8 modulo 2) = 0 EXAMPLE ANSWER
Hennesey_Page_480_Chunk480
Because we have a choice of which entry in a set to replace on a miss, we need a replacement rule. Set-associative caches usually replace the least recently used block within a set; that is, the block that was used furthest in the past is replaced. (We will discuss other replacement rules in more detail shortly.) Using this replacement rule, the contents of the set-associative cache after each reference looks like this: Address of memory block accessed Hit or miss Contents of cache blocks after reference Set 0 Set 0 Set 1 Set 1 0 miss Memory[0] 8 miss Memory[0] Memory[8] 0 hit Memory[0] Memory[8] 6 miss Memory[0] Memory[6] 8 miss Memory[8] Memory[6] Notice that when block 6 is referenced, it replaces block 8, since block 8 has been less recently referenced than block 0. The two-way set-associative cache has four misses, one less than the direct-mapped cache. The fully associative cache has four cache blocks (in a single set); any memory block can be stored in any cache block. The fully associative cache has the best performance, with only three misses: Address of memory block accessed Hit or miss Contents of cache blocks after reference Block 0 Block 1 Block 2 Block 3 0 miss Memory[0] 8 miss Memory[0] Memory[8] 0 hit Memory[0] Memory[8] 6 miss Memory[0] Memory[8] Memory[6] 8 hit Memory[0] Memory[8] Memory[6] For this series of references, three misses is the best we can do, because three unique block addresses are accessed. Notice that if we had eight blocks in the cache, there would be no replacements in the two-way set-associative cache (check this for yourself), and it would have the same number of misses as the fully associative cache. Similarly, if we had 16 blocks, all 3 caches would have the same number of misses. Even this trivial example shows that cache size and associativity are not independent in determining cache perfor­mance. 5.3 Measuring and Improving Cache Performance 483
Hennesey_Page_481_Chunk481
484 Chapter 5 Large and Fast: Exploiting Memory Hierarchy How much of a reduction in the miss rate is achieved by associativity? Figure 5.15 shows the improvement for a 64 KB data cache with a 16-word block, and associa­ tivity ranging from direct mapped to eight-way. Going from one-way to two- way associativity decreases the miss rate by about 15%, but there is little further improvement in going to higher associativity. Associativity Data miss rate 1 10.3% 2 8.6% 4 8.3% 8 8.1% FIGURE 5.15 The data cache miss rates for an organization like the Intrinsity FastMATH processor for SPEC CPU2000 benchmarks with associativity varying from one-way to eight-way. These results for 10 SPEC CPU2000 programs are from Hennessy and Patterson [2003]. Locating a Block in the Cache Now, let’s consider the task of finding a block in a cache that is set associative. Just as in a direct-mapped cache, each block in a set-associative cache includes an address tag that gives the block address. The tag of every cache block within the appropriate set is checked to see if it matches the block address from the proces­ sor. Figure 5.16 decomposes the address. The index value is used to select the set containing the address of interest, and the tags of all the blocks in the set must be searched. Because speed is of the essence, all the tags in the selected set are searched in parallel. As in a fully associative cache, a sequential search would make the hit time of a set-associative cache too slow. Block offset Tag Index FIGURE 5.16 The three portions of an address in a set-associative or direct-mapped cache. The index is used to select the set, then the tag is used to choose the block by comparison with the blocks in the selected set. The block offset is the address of the desired data within the block. If the total cache size is kept the same, increasing the associativity increases the number of blocks per set, which is the number of simultaneous compares needed to perform the search in parallel: each increase by a factor of 2 in asso­ciativity doubles the number of blocks per set and halves the number of sets. Accordingly, each factor-of-2 increase in associativity decreases the size of the index by 1 bit and increases the size of the tag by 1 bit. In a fully associative cache, there is effectively only one set, and all the blocks must be checked in par­allel. Thus, there is no index, and the entire address, excluding the block offset, is compared against the tag of every block. In other words, we search the entire cache without any indexing.
Hennesey_Page_482_Chunk482
In a direct-mapped cache, only a single comparator is needed, because the entry can be in only one block, and we access the cache simply by indexing. Figure 5.17 shows that in a four-way set-associative cache, four comparators are needed, together with a 4‑to-1 multiplexor to choose among the four potential members of the selected set. The cache access consists of indexing the appropriate set and then searching the tags of the set. The costs of an associative cache are the extra comparators and any delay imposed by having to do the compare and select from among the elements of the set. 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. Elaboration: A Content Addressable Memory (CAM) is a circuit that combines compari­ son and storage in a single device. Instead of supplying an address and reading a word like a RAM, you supply the data and the CAM looks to see if it has a copy and returns the index of the matching row. CAMs mean that cache designers can afford to implement much higher set asso­ciativity than if they needed to build the hardware out of SRAMs and comparators. In 2008, the greater size and power of CAM generally leads to 2-way and 4-way set associativity being built from standard SRAMs and comparators, with 8-way and above built using CAMs. Choosing Which Block to Replace When a miss occurs in a direct-mapped cache, the requested block can go in exactly one position, and the block occupying that position must be replaced. In an associative cache, we have a choice of where to place the requested block, and hence a choice of which block to replace. In a fully associative cache, all blocks are candidates for replacement. In a set-associative cache, we must choose among the blocks in the selected set. The most commonly used scheme is least recently used (LRU), which we used in the previous example. In an LRU scheme, the block replaced is the one that has been unused for the longest time. The set associative example on page 482 uses LRU, which is why we replaced Memory(0) instead of Memory(6). LRU replacement is implemented by keeping track of when each element in a set was used relative to the other elements in the set. For a two-way set-associative cache, tracking when the two elements were used can be implemented by keeping a single bit in each set and setting the bit to indicate an element whenever that element is referenced. As associativity increases, implementing LRU gets harder; in Section 5.5, we will see an alternative scheme for replacement. least recently used (LRU) A replacement scheme in which the block replaced is the one that has been ­unused for the longest time. 5.3 Measuring and Improving Cache Performance 485
Hennesey_Page_483_Chunk483
486 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Size of Tags versus Set Associativity Increasing associativity requires more comparators and more tag bits per cache block. Assuming a cache of 4K blocks, a 4-word block size, and a 32‑bit address, find the total number of sets and the total number of tag bits for caches that are direct mapped, two-way and four-way set associative, and fully associative. EXAMPLE FIGURE 5.17 The implementation of a four-way set-associative cache requires four comparators and a 4‑to‑1 multi­plexor. The comparators determine which element of the selected set (if any) matches the tag. The output of the comparators is used to select the data from one of the four blocks of the indexed set, using a multiplexor with a decoded select signal. In some implementations, the Output enable signals on the data portions of the cache RAMs can be used to select the entry in the set that drives the output. The Output enable signal comes from the compara­tors, causing the element that matches to drive the data outputs. This organization eliminates the need for the multiplexor. Address Data Tag V Tag = Index 22 8 31 30 12 11 10 9 8 3 2 1 0 4-to-1 multiplexor Index 0 1 2 253 254 255 Data V Tag = Data V Tag = Data V Tag 22 = 32 Data Hit
Hennesey_Page_484_Chunk484
Since there are 16 (= 24) bytes per block, a 32-bit address yields 32 - 4 = 28 bits to be used for index and tag. The direct-mapped cache has the same number of sets as blocks, and hence 12 bits of index, since log2(4K) = 12; hence, the total number is (28 - 12) × 4K = 16 × 4K = 64 K tag bits. Each degree of associativity decreases the number of sets by a factor of 2 and thus decreases the number of bits used to index the cache by 1 and increases the number of bits in the tag by 1. Thus, for a two-way set-associative cache, there are 2K sets, and the total number of tag bits is (28 -11) × 2 × 2K = 34 × 2K = 68 Kbits. For a four-way set-associative cache, the total number of sets is 1K, and the total number is (28 - 10) × 4 × 1K = 72 × 1K = 72 K tag bits. For a fully associative cache, there is only one set with 4K blocks, and the tag is 28 bits, leading to 28 × 4K × 1 = 112K tag bits. Reducing the Miss Penalty Using Multilevel Caches All modern computers make use of caches. To close the gap further between the fast clock rates of modern processors and the increasingly long time required to access DRAMs, most microprocessors support an additional level of caching. This second-level cache is usually on the same chip and is accessed whenever a miss occurs in the primary cache. If the second-level cache contains the desired data, the miss penalty for the first-level cache will be essentially the access time of the second-level cache, which will be much less than the access time of main memory. If ­neither the primary nor the secondary cache contains the data, a main memory access is required, and a larger miss penalty is incurred. How significant is the performance improvement from the use of a secondary cache? The next example shows us. Performance of Multilevel Caches Suppose we have a processor with a base CPI of 1.0, assuming all references hit in the primary cache, and a clock rate of 4 GHz. Assume a main memory access time of 100 ns, including all the miss handling. Suppose the miss rate per instruction at the primary cache is 2%. How much faster will the proces­ sor be if we add a secondary cache that has a 5 ns access time for either a hit or a miss and is large enough to reduce the miss rate to main memory to 0.5%? The miss penalty to main memory is ​ 100 ns  0.25 ​ ns  clock cycle ​ ​ = 400 clock cycles ANSWER EXAMPLE ANSWER 5.3 Measuring and Improving Cache Performance 487
Hennesey_Page_485_Chunk485
488 Chapter 5 Large and Fast: Exploiting Memory Hierarchy The effective CPI with one level of caching is given by Total CPI = Base CPI + Memory-stall cycles per instruction For the processor with one level of caching, Total CPI = 1.0 + Memory-stall cycles per instruction = 1.0 + 2% × 400 = 9 With two levels of caching, a miss in the primary (or first-level) cache can be satisfied ­either by the secondary cache or by main memory. The miss ­penalty for an access to the second-level cache is ​ 5 ns  0.25 ​ ns  clock cycle ​ ​ = 20 clock cycles If the miss is satisfied in the secondary cache, then this is the entire miss penalty. If the miss needs to go to main memory, then the total miss penalty is the sum of the secondary cache access time and the main memory access time. Thus, for a two-level cache, total CPI is the sum of the stall cycles from both levels of cache and the base CPI: Total CPI = 1 + Primary stalls per instruction + Secondary stalls per instruction = 1 + 2% × 20 + 0.5% × 400 = 1 + 0.4 + 2.0 = 3.4 Thus, the processor with the secondary cache is faster by ​ 9.0  3.4 ​ = 2.6 Alternatively, we could have computed the stall cycles by summing the stall cycles of those references that hit in the secondary cache ((2% - 0.5%) × 20 = 0.3). Those references that go to main memory, which must include the cost to access the secondary cache as well as the main memory access time, is (0.5% × (20 + 400) = 2.1). The sum, 1.0 + 0.3 + 2.1, is again 3.4. The design considerations for a primary and secondary cache are significantly different, because the presence of the other cache changes the best choice versus a single-level cache. In particular, a two-level cache structure allows the primary cache to focus on minimizing hit time to yield a shorter clock cycle or fewer pipeline stages, while allow­ing the secondary cache to focus on miss rate to reduce the penalty of long mem­ory access times.
Hennesey_Page_486_Chunk486
The effect of these changes on the two caches can be seen by comparing each cache to the optimal design for a single level of cache. In comparison to a ­single- level cache, the primary cache of a multilevel cache is often smaller. Furthermore, the primary cache may use a smaller block size, to go with the smaller cache size and also to reduce the miss penalty. In comparison, the secondary cache will be much larger than in a single-level cache, since the access time of the secondary cache is less critical. With a larger total size, the secondary cache may use a larger block size than appropriate with a single-level cache. It often uses higher associativity than the primary cache given the focus of reducing miss rates. Sorting has been exhaustively analyzed to find better algorithms: Bubble Sort, Quicksort, Radix Sort, and so on. Figure 5.18(a) shows instructions executed by item searched for Radix Sort versus Quicksort. As expected, for large arrays, Radix Sort has an algorithmic advantage over Quicksort in terms of number of operations. Figure 5.18(b) shows time per key instead of instructions executed. We see that the lines start on the same trajectory as Figure 5.18(a), but then the Radix Sort line diverges as the data to sort increases. What is going on? Figure 5.18(c) answers by looking at the cache misses per item sorted: Quicksort consistently has many fewer misses per item to be sorted. Alas, standard algorithmic analysis often ignores the impact of the memory hierarchy. As faster clock rates and Moore’s law allow architects to squeeze all of the performance out of a stream of instructions, using the memory hierarchy well is critical to high performance. As we said in the introduction, understanding the behavior of the memory hierarchy is critical to understanding the performance of programs on today’s computers. Elaboration: Multilevel caches create several complications. First, there are now several different types of misses and corresponding miss rates. In the example on pages 487–488. we saw the primary cache miss rate and the global miss rate—the fraction of references that missed in all cache levels. There is also a miss rate for the secondary cache, which is the ratio of all misses in the secondary cache divided by the number of accesses to it. This miss rate is called the local miss rate of the secondary cache. Because the primary cache filters accesses, especially those with good spatial and temporal locality, the local miss rate of the secondary cache is much higher than the global miss rate. For the example on pages 487–488. we can compute the local miss rate of the secondary cache as 0.5%/2% = 25%! Luckily, the global miss rate dictates how often we must access the main memory. Elaboration: With out-of-order processors (see Chapter 4), performance is more complex, since they execute instructions during the miss penalty. Instead of instruction miss rates and data miss rates, we use misses per instruction, and this formula: ​ Memory-stall cycles  Instruction ​ = ​ Misses  Instruction ​ × (Total miss latency – Overlapped miss latency) multilevel cache A memory hierarchy with multiple levels of caches, rather than just a cache and main memory. Understanding Program Performance global miss rate The fraction of references that miss in all lev­els of a multilevel cache. local miss rate The fraction of references to one level of a cache that miss; used in multilevel hierarchies. 5.3 Measuring and Improving Cache Performance 489
Hennesey_Page_487_Chunk487
490 Chapter 5 Large and Fast: Exploiting Memory Hierarchy FIGURE 5.18 Comparing Quicksort and Radix Sort by (a) instructions executed per item sorted, (b) time per item sorted, and (c) cache misses per item sorted. This data is from a paper by LaMarca and Ladner [1996]. Although the numbers would change for newer computers, the idea still holds. Due to such results, new versions of Radix Sort have been invented that take memory hierarchy into account, to regain its algorithmic advantages (see Section 5.11). The basic idea of cache optimizations is to use all the data in a block repeatedly before it is replaced on a miss. Radix Sort Quicksort Size (K items to sort) Instructions/item 0 4 8 16 32 200 400 600 800 1000 1200 64 128 256 512 1024 2048 4096 a. Radix Sort Quicksort Size (K items to sort) Clock cycles/item 0 4 8 16 32 400 800 1200 1600 2000 64 128 256 512 1024 2048 4096 b. Radix Sort Quicksort Size (K items to sort) Cache misses/item 0 4 8 16 32 1 2 3 4 5 64 128 256 512 1024 2048 4096 c.
Hennesey_Page_488_Chunk488
There is no general way to calculate overlapped miss latency, so evaluations of memory hierarchies for out-of-order processors inevitably require simulation of the processor and mem­ory hierarchy. Only by seeing the execution of the processor during each miss can we see if the processor stalls waiting for data or simply finds other work to do. A guideline is that the proces­sor often hides the miss penalty for an L1 cache miss that hits in the L2 cache, but it rarely hides a miss to the L2 cache. Elaboration: The performance challenge for algorithms is that the memory hierarchy varies between different implementations of the same architecture in cache size, associa­tivity, block size, and number of caches. To cope with such variability, some recent numeri­cal libraries parameterize their algorithms and then search the parameter space at runtime to find the best combination for a particular computer. This approach is called autotuning. Which of the following is generally true about a design with multiple levels of caches? 1. First-level caches are more concerned about hit time, and second-level caches are more concerned about miss rate. 2. First-level caches are more concerned about miss rate, and second-level caches are more concerned about hit time. Summary In this section, we focused on three topics: cache performance, using associativity to reduce miss rates, and the use of multilevel cache hierarchies to reduce miss penalties. The memory system has a significant effect on program execution time. The number of memory-stall cycles depends on both the miss rate and the miss penalty. The challenge, as we will see in Section 5.5, is to reduce one of these factors without significantly affecting ­other critical factors in the memory hierarchy. To reduce the miss rate, we examined the use of associative placement schemes. Such schemes can reduce the miss rate of a cache by allowing more flexible place­ ment of blocks within the cache. Fully associative schemes allow blocks to be placed anywhere, but also require that every block in the cache be searched to sat­isfy a request. The higher costs make large fully associative caches impractical. Set-associative caches are a practical alternative, since we need only search among the elements of a unique set that is chosen by indexing. Set-associative caches have higher miss rates but are faster to access. The amount of associativity that yields the best performance depends on both the technology and the details of the implementation. Finally, we looked at multilevel caches as a technique to reduce the miss penalty by allowing a larger secondary cache to handle misses to the primary cache. Second‑level caches have become commonplace as designers find that limited silicon and the goals of high clock rates prevent primary caches from becoming Check Yourself 5.3 Measuring and Improving Cache Performance 491
Hennesey_Page_489_Chunk489
492 Chapter 5 Large and Fast: Exploiting Memory Hierarchy large. The secondary cache, which is often ten or more times larger than the pri­mary cache, handles many accesses that miss in the primary cache. In such cases, the miss penalty is that of the access time to the secondary cache (typically < 10 processor cycles) versus the access time to memory (typically > 100 proces­sor cycles). As with associativity, the design tradeoffs between the size of the secondary cache and its access time depend on a number of aspects of the implementation. 5.4 Virtual Memory In the previous section, we saw how caches provided fast access to recently used portions of a program’s code and data. Similarly, the main memory can act as a “cache” for the secondary storage, usually implemented with magnetic disks. This technique is called virtual memory. Historically, there were two major motiva­tions for virtual memory: to allow efficient and safe sharing of memory among multiple programs, and to remove the programming burdens of a small, limited amount of main memory. Four decades after its invention, it’s the former reason that reigns today. Consider a collection of programs running all at once on a computer. Of course, to allow multiple programs to share the same memory, we must be able to protect the programs from each other, ensuring that a program can only read and write the portions of main memory that have been assigned to it. Main memory need contain only the active portions of the many programs, just as a cache contains only the active portion of one program. Thus, the principle of locality enables vir­ tual memory as well as caches, and virtual memory allows us to efficiently share the processor as well as the main memory. We cannot know which programs will share the memory with ­other pro­ grams when we compile them. In fact, the programs sharing the memory change dynamically while the programs are running. Because of this dynamic interaction, we would like to compile each program into its own address space—a separate range of memory locations accessible only to this program. Virtual memory implements the translation of a program’s address space to physical addresses. This translation process enforces protection of a program’s address space from other programs. The second motivation for virtual memory is to allow a single user program to exceed the size of primary memory. Formerly, if a program became too large for memory, it was up to the programmer to make it fit. Programmers di­vided pro­ grams into pieces and then identified the pieces that were mutually exclusive. These overlays were loaded or unloaded under user program control during exe­cution, with the programmer ensuring that the program never tried to access an overlay that was not loaded and that the overlays loaded never exceeded the total size of the memory. Overlays were traditionally organized as modules, each con­taining . . . a system has been devised to make the core drum combina- tion appear to the programmer as a single level store, the requisite transfers taking place auto­matically. Kilburn et al., One-level storage system, 1962 virtual memory A technique that uses main memory as a “cache” for secondary storage. physical address An address in main memory. protection A set of mecha­nisms for ensuring that multiple processes sharing the processor, memory, or I/O devices cannot interfere, intentionally or unin­tentionally, with one another by reading or writing each other’s data. These mechanisms also isolate the operating system from a user process.
Hennesey_Page_490_Chunk490
both code and data. Calls between procedures in different modules would lead to overlaying of one module with another. As you can well imagine, this responsibility was a substantial burden on pro­ grammers. Virtual memory, which was invented to relieve programmers of this difficulty, automatically manages the two levels of the memory hierarchy repre­ sented by main memory (sometimes called physical memory to distinguish it from virtual memory) and secondary storage. Although the concepts at work in virtual memory and in caches are the same, their differing historical roots have led to the use of different term­inology. A virtual memory block is called a page, and a virtual memory miss is called a page fault. With virtual memory, the processor produces a virtual address, which is translated by a combina­tion of hardware and software to a physical ­address, which in turn can be used to access main memory. Figure 5.19 shows the virtually addressed memory with pages mapped to main memory. This process is called address mapping or address translation. Today, the two mem­ory hierarchy levels controlled by virtual memory are usually DRAMs and magnetic disks (see Chapter 1, pages 22–23). If we return to our library analogy, we can think of a virtual address as the title of a book and a physical address as the location of that book in the library, such as might be given by the Library of Congress call number. page fault An event that occurs when an accessed page is not present in main memory. virtual address An address that corresponds to a ­location in virtual space and is translated by address mapping to a physical address when memory is ­accessed. address translation Also called address mapping. The process by which a virtual address is mapped to an address used to access memory. FIGURE 5.19 In virtual memory, blocks of memory (called pages) are mapped from one set of addresses (called virtual addresses) to another set (called physical addresses). The processor generates virtual addresses while the memory is accessed using physical addresses. Both the virtual memory and the physical memory are broken into pages, so that a virtual page is mapped to a phys­ical page. Of course, it is also possible for a virtual page to be absent from main memory and not be mapped to a physical address; in that case, the page resides on disk. Physical pages can be shared by having two vir­tual addresses point to the same physical address. This capability is used to allow two different programs to share data or code. Virtual addresses Physical addresses Address translation Disk addresses 5.4 Virtual Memory 493
Hennesey_Page_491_Chunk491
494 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Virtual memory also simplifies loading the program for execution by provid­ing relocation. Relocation maps the virtual addresses used by a program to dif­ferent physical addresses before the addresses are used to access memory. This relocation allows us to load the program anywhere in main memory. Further­more, all virtual memory systems in use today relocate the program as a set of fixed-size blocks (pages), thereby eliminating the need to find a contiguous block of memory to allocate to a program; instead, the operating system need only find a sufficient number of pages in main memory. In virtual memory, the address is broken into a virtual page number and a page offset. Figure 5.20 shows the translation of the virtual page number to a physical page number. The physical page number constitutes the upper portion of the physical address, while the page offset, which is not changed, constitutes the lower ­portion. The number of bits in the page offset field determines the page size. The number of pages addressable with the virtual address need not match the number of pages addressable with the physical address. Having a larger number of virtual pages than physical pages is the basis for the illusion of an essentially unbounded amount of virtual memory. FIGURE 5.20 Mapping from a virtual to a physical address. The page size is 212 = 4 KB. The number of physical pages allowed in memory is 218, since the physical page number has 18 bits in it. Thus, main memory can have at most 1 GB, while the virtual address space is 4 GB. Virtual page number Page offset 31 30 29 28 27 3 2 1 0 15 14 13 12 11 10 9 8 Physical page number Page offset 29 28 27 3 2 1 0 15 14 13 12 11 10 9 8 Virtual address Physical address Translation Many design choices in virtual memory systems are motivated by the high cost of a miss, which in virtual memory is traditionally called a page fault. A page fault will take millions of clock cycles to process. (The table on page 453 shows that main memory latency is about 100,000 times quicker than disk.) This enormous miss
Hennesey_Page_492_Chunk492
penalty, dominated by the time to get the first word for typical page sizes, leads to several key decisions in designing virtual memory systems: ■ ■Pages should be large enough to try to amortize the high access time. Sizes from 4 KB to 16 KB are typical today. New desktop and server systems are being developed to support 32 KB and 64 KB pages, but new embedded sys­ tems are going in the other direction, to 1 KB pages. ■ ■Organizations that reduce the page fault rate are attractive. The primary tech­ nique used here is to allow fully associative placement of pages in memory. ■ ■Page faults can be handled in software because the overhead will be small compared to the disk access time. In addition, software can afford to use clever algorithms for choosing how to place pages because even small reduc­ tions in the miss rate will pay for the cost of such algorithms. ■ ■Write-through will not work for virtual memory, since writes take too long. Instead, virtual memory systems use write-back. The next few subsections address these factors in virtual memory design. Elaboration: Although we normally think of virtual addresses as much larger than physical addresses, the opposite can occur when the processor address size is small relative to the state of the memory technology. No single program can benefit, but a collection of programs running at the same time can benefit from not having to be swapped to memory or by running on parallel processors. For servers and desktop computers, 32-bit address processors are problematic. Elaboration: The discussion of virtual memory in this book focuses on paging, which uses fixed-size blocks. There is also a variable-size block scheme called segmentation. In segmenta­tion, an address consists of two parts: a segment number and a segment offset. The segment register is mapped to a physical address, and the offset is added to find the actual physical address. Because the segment can vary in size, a bounds check is also needed to make sure that the offset is within the segment. The major use of segmentation is to support more powerful methods of protection and sharing in an address space. Most operating system textbooks con­tain extensive discussions of segmentation compared to paging and of the use of segmentation to logically share the address space. The major disadvantage of segmentation is that it splits the address space into logically separate pieces that must be manipulated as a two-part address: the segment number and the offset. Paging, in contrast, makes the boundary between page number and offset invisible to programmers and compilers. Segments have also been used as a method to extend the address space without changing the word size of the computer. Such attempts have been unsuccessful because of the awkwardness and performance penalties inherent in a two-part address, of which programmers and compilers must be aware. Many architectures divide the address space into large fixed-size blocks that simplify pro­tection between the operating system and user programs and increase the efficiency of imple­menting paging. Although these divisions are often called “segments,” this mechanism is much simpler than variable block size segmentation and is not visible to user programs; we discuss it in more detail shortly. segmentation A variable-size address mapping scheme in which an address consists of two parts: a segment number, which is mapped to a physical address, and a segment offset. 5.4 Virtual Memory 495
Hennesey_Page_493_Chunk493
496 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Placing a Page and Finding It Again Because of the incredibly high penalty for a page fault, designers reduce page fault frequency by optimizing page placement. If we allow a virtual page to be mapped to any physical page, the operating system can then choose to replace any page it wants when a page fault occurs. For example, the operating system can use a sophisticated algorithm and complex data structures that track page usage to try to choose a page that will not be needed for a long time. The ability to use a clever and flexible replacement scheme reduces the page fault rate and simplifies the use of fully associative placement of pages. As mentioned in Section 5.3, the difficulty in using fully associative place­ment is in locating an entry, since it can be anywhere in the upper level of the hierarchy. A full search is impractical. In virtual memory systems, we locate pages by using a table that indexes the memory; this structure is called a page table, and it resides in memory. A page table is indexed with the page number from the virtual address to discover the corresponding physical page number. Each program has its own page table, which maps the virtual address space of that program to main memory. In our library analogy, the page table corre­sponds to a mapping between book titles and library locations. Just as the card catalog may contain entries for books in another library on campus rather than the ­local branch library, we will see that the page table may contain entries for ­pages not present in memory. To indicate the location of the page table in mem­ory, the hardware includes a register that points to the start of the page table; we call this the page table register. Assume for now that the page table is in a fixed and contiguous area of memory. The page table, together with the program counter and the registers, specifies the state of a program. If we want to allow another program to use the processor, we must save this state. Later, after restoring this state, the program can continue exe­ cution. We often refer to this state as a process. The process is considered active when it is in possession of the processor; other­wise, it is considered inactive. The operating system can make a process active by loading the process’s state, includ­ ing the program counter, which will initiate execution at the value of the saved program counter. The process’s address space, and hence all the data it can access in memory, is defined by its page table, which resides in memory. Rather than save the entire page table, the operating system simply loads the page table register to point to the page table of the process it wants to make active. Each process has its own page table, since different processes use the same virtual addresses. The operating sys­tem is responsible for allocating the physical memory and updating the page tables, so that the virtual address spaces of different processes do not collide. As we will see shortly, the use of separate page tables also provides protection of one process from another. page table The table contain­ing the virtual to physical address translations in a virtual memory system. The table, which is stored in memory, is typically indexed by the virtual page number; each entry in the table contains the physical page number for that virtual page if the page is currently in memory. Hardware/ Software Interface
Hennesey_Page_494_Chunk494
Figure 5.21 uses the page table register, the virtual address, and the indicated page table to show how the hardware can form a physical address. A valid bit is used in each page table entry, just as we did in a cache. If the bit is off, the page is not present in main memory and a page fault occurs. If the bit is on, the page is in memory and the entry contains the physical page number. FIGURE 5.21 The page table is indexed with the virtual page number to obtain the corresponding portion of the physical address. We assume a 32-bit address. The starting address of the page table is given by the page table pointer. In this figure, the page size is 212 bytes, or 4 KB. The virtual address space is 232 bytes, or 4 GB, and the physical address space is 230 bytes, which allows main memory of up to 1 GB. The number of entries in the page table is 220, or 1 million entries. The valid bit for each entry indicates whether the mapping is legal. If it is off, then the page is not present in memory. Although the page table entry shown here need only be 19 bits wide, it would typically be rounded up to 32 bits for ease of index­ing. The extra bits would be used to store additional information that needs to be kept on a per-page basis, such as protection. Virtual page number Page offset 3 1 3 0 2 9 2 8 2 7 3 2 1 0 1 5 1 4 1 3 1 2 1 1 1 0 9 8 Physical page number Page offset 2 9 2 8 2 7 3 2 1 0 1 5 1 4 1 3 1 2 1 1 1 0 9 8 Virtual address Physical address Page table register Physical page number Valid Page table If 0 then page is not present in memory 20 12 18 5.4 Virtual Memory 497
Hennesey_Page_495_Chunk495
498 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Because the page table contains a mapping for every possible virtual page, no tags are ­required. In cache terminology, the index that is used to access the page table consists of the full block address, which is the virtual page ­number. Page Faults If the valid bit for a virtual page is off, a page fault occurs. The operating system must be given control. This transfer is done with the exception mechanism, which we discuss later in this section. Once the operating system gets control, it must find the page in the next level of the hierarchy (usually magnetic disk) and decide where to place the requested page in main memory. The virtual address alone does not immediately tell us where the page is on disk. Returning to our library analogy, we cannot find the location of a library book on the shelves just by knowing its title. Instead, we go to the catalog and look up the book, obtaining an address for the location on the shelves, such as the Library of Congress call number. Likewise, in a virtual memory system, we must keep track of the location on disk of each page in virtual address space. Because we do not know ahead of time when a page in memory will be replaced, the operating system usually creates the space on disk for all the pages of a process when it creates the process. This disk space is called the swap space. At that time, it also creates a data structure to record where each virtual page is stored on disk. This data structure may be part of the page table or may be an aux­ iliary data structure indexed in the same way as the page table. Figure 5.22 shows the organization when a single table holds either the physical page number or the disk address. The operating system also creates a data structure that tracks which ­processes and which virtual addresses use each physical page. When a page fault occurs, if all the pages in main memory are in use, the operating system must choose a page to replace. Because we want to minimize the number of page faults, most operating systems try to choose a page that they hypothesize will not be needed in the near future. Using the past to predict the future, ­operating systems follow the least recently used (LRU) replacement scheme, which we mentioned in Section 5.3. The operating system searches for the least recently used page, assuming that a page that has not been used in a long time is less likely to be needed than a more recently accessed page. The replaced pages are written to swap space on the disk. In case you are wondering, the operating system is just another process, and these tables controlling memory are in memory; the details of this seeming contradic­tion will be explained shortly. swap space The space on the disk reserved for the full virtual memory space of a process.
Hennesey_Page_496_Chunk496
Implementing a completely accurate LRU scheme is too expensive, since it requires updating a data structure on every memory reference. Instead, most operating systems approximate LRU by keeping track of which pages have and which pages have not been recently used. To help the operating system estimate the LRU pages, some computers provide a reference bit or use bit, which is set whenever a page is accessed. The operating system periodi­cally clears the refer­ence bits and later records them so it can determine which pages were touched during a particular time period. With this usage information, the operating sys­tem can select a page that is among the least recently referenced (detected by hav­ing its reference bit off). If this bit is not provided by the hardware, the operating system must find another way to estimate which pages have been accessed. Hardware/ Software Interface reference bit Also called use bit. A field that is set whenever a page is accessed and that is used to implement LRU or other replacement schemes. FIGURE 5.22 The page table maps each page in virtual memory to either a page in main memory or a page stored on disk, which is the next level in the hierarchy. The vir­tual page number is used to index the page table. If the valid bit is on, the page table supplies the physical page number (i.e., the starting address of the page in memory) corresponding to the virtual page. If the valid bit is off, the page currently resides only on disk, at a specified disk address. In many systems, the table of physical page addresses and disk page addresses, while logically one table, is stored in two sepa­rate data structures. Dual tables are justified in part because we must keep the disk addresses of all the pages, even if they are currently in main memory. Remember that the pages in main memory and the pages on disk are the same size. Page table Physical page or disk address Physical memory Virtual page number Disk storage 1 1 1 1 0 1 1 1 1 1 0 0 Valid 5.4 Virtual Memory 499
Hennesey_Page_497_Chunk497
500 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Elaboration: With a 32-bit virtual address, 4 KB pages, and 4 bytes per page table entry, we can compute the total page table size: Number of page table entries = ​ 232  212 ​ = 220 Size of page table = 220 page table entries × 22 ​ bytes  page table entry ​ = 4 MB That is, we would need to use 4 MB of memory for each program in execution at any time. This amount is not so bad for a single program. What if there are hundreds of programs running, each with their own page table? And how should we handle 64-bit addresses, which by this cal­culation would need 252 words? A range of techniques is used to reduce the amount of storage required for the page table. The five techniques below aim at reducing the total maximum storage required as well as mini­mizing the main memory dedicated to page tables: 1. The simplest technique is to keep a limit register that restricts the size of the page table for a given process. If the virtual page number becomes larger than the con- tents of the limit reg­ister, entries must be added to the page table. This technique allows the page table to grow as a process consumes more space. Thus, the page table will only be large if the process is using many pages of virtual address space. This technique requires that the address space expand in only one direction. 2. Allowing growth in only one direction is not sufficient, since most languages require two areas whose size is expandable: one area holds the stack and the other area holds the heap. Because of this duality, it is convenient to divide the page table and let it grow from the highest address down, as well as from the lowest address up. This means that there will be two separate page tables and two separate limits. The use of two page tables breaks the address space into two segments. The high-order bit of an address usually determines which segment and thus which page table to use for that address. Since the segment is specified by the ­high-order address bit, each segment can be as large as one-half of the address space. A limit register for each segment specifies the current size of the segment, which grows in units of pages. This type of segmentation is used by many architectures, including MIPS. Unlike the type of segmentation discussed in the second elaboration on page 495, this form of segmentation is invisible to the application program, although not to the operating system. The major disadvantage of this scheme is that it does not work well when the address space is used in a sparse fashion rather than as a contiguous set of virtual addresses. 3. Another approach to reducing the page table size is to apply a hashing function to the vir­tual address so that the page table need be only the size of the number of physical pages in main memory. Such a structure is called an ­inverted page table. Of course, the lookup process is slightly more complex with an inverted page table, because we can no longer just index the page table. 4. Multiple levels of page tables can also be used to reduce the total amount of page table storage. The first level maps large fixed-size blocks of virtual address space, perhaps 64 to 256 pages in total. These large blocks are sometimes called ­segments, and this first-level mapping table is sometimes called a segment table, though the
Hennesey_Page_498_Chunk498
segments are again invisible to the user. Each entry in the segment table indicates whether any pages in that segment are allocated and, if so, points to a page table for that segment. Address transla­tion happens by first looking in the ­segment table, using the highest-order bits of the ad­dress. If the segment address is valid, the next set of high-order bits is used to index the page table indicated by the segment table entry. This scheme allows the address space to be used in a sparse fashion (multiple noncontiguous segments can be active) without hav­ing to allocate the entire page table. Such schemes are particularly useful with very large address spaces and in software systems that require noncontiguous allocation. The prima­ry disadvantage of this two-level mapping is the more complex process for address trans­lation. 5. To reduce the actual main memory tied up in page tables, most modern systems also allow the page tables to be paged. Although this sounds tricky, it works by using the same basic ideas of virtual memory and simply allowing the page tables to ­reside in the virtual ad­dress space. In addition, there are some small but ­critical problems, such as a never-end­ing series of page faults, which must be avoided. How these problems are overcome is both very detailed and typically highly processor specific. In brief, these problems are avoided by placing all the page tables in the address space of the operating system and placing at least some of the page tables for the operating system in a portion of main mem­ory that is physically addressed and is always present and thus never on disk. What about Writes? The difference between the access time to the cache and main memory is tens to hundreds of cycles, and write-through schemes can be used, although we need a write buffer to hide the latency of the write from the processor. In a virtual mem­ory system, writes to the next level of the hierarchy (disk) take millions of proces­sor clock cycles; therefore, building a write buffer to allow the system to write-through to disk would be completely impractical. Instead, virtual memory sys­tems must use write-back, performing the individual writes into the page in memory, and copying the page back to disk when it is replaced in the memory. A write-back scheme has another major advantage in a virtual memory system. Because the disk transfer time is small compared with its access time, copying back an entire page is much more efficient than writing individual words back to the disk. A write-back operation, although more efficient than transferring indi­vidual words, is still costly. Thus, we would like to know whether a page needs to be copied back when we choose to replace it. To track whether a page has been written since it was read into the memory, a dirty bit is added to the page table. The dirty bit is set when any word in a page is written. If the operating system chooses to replace the page, the dirty bit indicates whether the page needs to be written out before its location in memory can be given to another page. Hence, a modified page is often called a dirty page. Hardware/ Software Interface 5.4 Virtual Memory 501
Hennesey_Page_499_Chunk499
502 Chapter 5 Large and Fast: Exploiting Memory Hierarchy Making Address Translation Fast: the TLB Since the page tables are stored in main memory, every memory access by a program can take at least twice as long: one memory access to obtain the physical address and a second access to get the data. The key to improving access performance is to rely on locality of reference to the page table. When a translation for a virtual page number is used, it will probably be needed again in the near future, because the references to the words on that page have both temporal and spatial locality. Accordingly, modern processors include a special cache that keeps track of recently used translations. This special address translation cache is ­tradition­ally referred to as a translation-lookaside buffer (TLB), although it would be more accurate to call it a translation cache. The TLB corresponds to that little piece of paper we typically use to record the location of a set of books we look up in the card catalog; rather than continually searching the entire catalog, we record the location of several books and use the scrap of paper as a cache of Library of Con­gress call numbers. Figure 5.23 shows that each tag entry in the TLB holds a portion of the virtual page number, and each data entry of the TLB holds a physical page number. Because translation-lookaside buffer (TLB) A cache that keeps track of recently used address mappings to try to avoid an access to the page table. FIGURE 5.23 The TLB acts as a cache of the page table for the entries that map to physical pages only. The TLB contains a sub­set of the virtual-to-physical page mappings that are in the page table. The TLB mappings are shown in color. Because the TLB is a cache, it must have a tag field. If there is no matching entry in the TLB for a page, the page table must be examined. The page table either supplies a physical page number for the page (which can then be used to build a TLB entry) or indicates that the page resides on disk, in which case a page fault occurs. Since the page table has an entry for every virtual page, no tag field is needed; in other words, unlike a TLB, a page table is not a cache. 1 1 1 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 0 0 1 0 1 1 1 1 1 0 0 Physical page or disk address ValidDirty Ref Page table Physical memory Virtual page number Disk storage 1 1 1 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 Physical page address ValidDirty Ref TLB Tag
Hennesey_Page_500_Chunk500