Docsity

Understanding Memory Hierarchies: The Role of Caches in Program Performance, Study Guides, Projects, Research of Technology

Partial preview of the text

Download Understanding Memory Hierarchies: The Role of Caches in Program Performance and more Study Guides, Projects, Research Technology in PDF only on Docsity!

C H A P T E R

The Memory Hierarchy

6.1 Storage Technologies 561 6.2 Locality 586

6.3 The Memory Hierarchy 591

6.4 Cache Memories 596

6.5 Writing Cache-friendly Code 615

6.6 Putting It Together: The Impact of Caches on Program Performance 620 6.7 Summary 629

Bibliographic Notes 630

Homework Problems 631

Solutions to Practice Problems 642

559

560 Chapter 6 The Memory Hierarchy

To this point in our study of systems, we have relied on a simple model of a computer system as a CPU that executes instructions and a memory system that holds instructions and data for the CPU. In our simple model, the memory system is a linear array of bytes, and the CPU can access each memory location in a constant amount of time. While this is an effective model as far as it goes, it does not reflect the way that modern systems really work. In practice, a memory system is a hierarchy of storage devices with different capacities, costs, and access times. CPU registers hold the most frequently used data. Small, fast cache memories nearby the CPU act as staging areas for a subset of the data and instructions stored in the relatively slow main memory. The main memory stages data stored on large, slow disks, which in turn often serve as staging areas for data stored on the disks or tapes of other machines connected by networks. Memory hierarchies work because well-written programs tend to access the storage at any particular level more frequently than they access the storage at the next lower level. So the storage at the next level can be slower, and thus larger and cheaper per bit. The overall effect is a large pool of memory that costs as much as the cheap storage near the bottom of the hierarchy, but that serves data to programs at the rate of the fast storage near the top of the hierarchy. As a programmer, you need to understand the memory hierarchy because it has a big impact on the performance of your applications. If the data your program needs are stored in a CPU register, then they can be accessed in zero cycles during the execution of the instruction. If stored in a cache, 1 to 30 cycles. If stored in main memory, 50 to 200 cycles. And if stored in disk tens of millions of cycles! Here, then, is a fundamental and enduring idea in computer systems: if you understand how the system moves data up and down the memory hierarchy, then you can write your application programs so that their data items are stored higher in the hierarchy, where the CPU can access them more quickly. This idea centers around a fundamental property of computer programs known as locality. Programs with good locality tend to access the same set of data items over and over again, or they tend to access sets of nearby data items. Programs with good locality tend to access more data items from the upper levels of the memory hierarchy than programs with poor locality, and thus run faster. For example, the running times of different matrix multiplication kernels that perform the same number of arithmetic operations, but have different degrees of locality, can vary by a factor of 20! In this chapter, we will look at the basic storage technologies—SRAM mem- ory, DRAM memory, ROM memory, and rotating and solid state disks—and describe how they are organized into hierarchies. In particular, we focus on the cache memories that act as staging areas between the CPU and main memory, be- cause they have the most impact on application program performance. We show you how to analyze your C programs for locality and we introduce techniques for improving the locality in your programs. You will also learn an interesting way to characterize the performance of the memory hierarchy on a particular machine as a “memory mountain” that shows read access times as a function of locality.

562 Chapter 6 The Memory Hierarchy

Transistors Relative Relative per bit access time Persistent? Sensitive? cost Applications SRAM 6 1 × Yes No 100 × Cache memory DRAM 1 10 × No Yes 1 × Main mem, frame buffers

Figure 6.2 Characteristics of DRAM and SRAM memory.

Dynamic RAM

DRAM stores each bit as charge on a capacitor. This capacitor is very small— typically around 30 femtofarads, that is, 30 × 10 −^15 farads. Recall, however, that a farad is a very large unit of measure. DRAM storage can be made very dense— each cell consists of a capacitor and a single access transistor. Unlike SRAM, however, a DRAM memory cell is very sensitive to any disturbance. When the capacitor voltage is disturbed, it will never recover. Exposure to light rays will cause the capacitor voltages to change. In fact, the sensors in digital cameras and camcorders are essentially arrays of DRAM cells. Various sources of leakage current cause a DRAM cell to lose its charge within a time period of around 10 to 100 milliseconds. Fortunately, for computers operating with clock cycle times measured in nanoseconds, this retention time is quite long. The memory system must periodically refresh every bit of memory by reading it out and then rewriting it. Some systems also use error-correcting codes, where the computer words are encoded a few more bits (e.g., a 32-bit word might be encoded using 38 bits), such that circuitry can detect and correct any single erroneous bit within a word. Figure 6.2 summarizes the characteristics of SRAM and DRAM memory. SRAM is persistent as long as power is applied. Unlike DRAM, no refresh is necessary. SRAM can be accessed faster than DRAM. SRAM is not sensitive to disturbances such as light and electrical noise. The trade-off is that SRAM cells use more transistors than DRAM cells, and thus have lower densities, are more expensive, and consume more power.

Conventional DRAMs

The cells (bits) in a DRAM chip are partitioned into d supercells , each consisting of w DRAM cells. A d × w DRAM stores a total of dw bits of information. The supercells are organized as a rectangular array with r rows and c columns, where rc = d. Each supercell has an address of the form (i, j ), where i denotes the row, and j denotes the column. For example, Figure 6.3 shows the organization of a 16 × 8 DRAM chip with d = 16 supercells, w = 8 bits per supercell, r = 4 rows, and c = 4 columns. The shaded box denotes the supercell at address ( 2 , 1 ). Information flows in and out of the chip via external connectors called pins. Each pin carries a 1-bit signal. Figure 6.3 shows two of these sets of pins: eight data pins that can transfer 1 byte

Section 6.1 Storage Technologies 567

Nonvolatile Memory

DRAMs and SRAMs are volatile in the sense that they lose their information if the supply voltage is turned off. Nonvolatile memories , on the other hand, retain their information even when they are powered off. There are a variety of nonvolatile memories. For historical reasons, they are referred to collectively as read-only memories (ROMs), even though some types of ROMs can be written to as well as read. ROMs are distinguished by the number of times they can be reprogrammed (written to) and by the mechanism for reprogramming them. A programmable ROM (PROM) can be programmed exactly once. PROMs include a sort of fuse with each memory cell that can be blown once by zapping it with a high current. An erasable programmable ROM (EPROM) has a transparent quartz window that permits light to reach the storage cells. The EPROM cells are cleared to zeros by shining ultraviolet light through the window. Programming an EPROM is done by using a special device to write ones into the EPROM. An EPROM can be erased and reprogrammed on the order of 1000 times. An electrically erasable PROM (EEPROM) is akin to an EPROM, but does not require a physically separate programming device, and thus can be reprogrammed in-place on printed circuit cards. An EEPROM can be reprogrammed on the order of 10^5 times before it wears out. Flash memory is a type of nonvolatile memory, based on EEPROMs, that has become an important storage technology. Flash memories are everywhere, providing fast and durable nonvolatile storage for a slew of electronic devices, including digital cameras, cell phones, music players, PDAs, and laptop, desktop, and server computer systems. In Section 6.1.3, we will look in detail at a new form of flash-based disk drive, known as a solid state disk (SSD), that provides a faster, sturdier, and less power-hungry alternative to conventional rotating disks. Programs stored in ROM devices are often referred to as firmware. When a computer system is powered up, it runs firmware stored in a ROM. Some systems provide a small set of primitive input and output functions in firmware, for example, a PC’s BIOS (basic input/output system) routines. Complicated devices such as graphics cards and disk drive controllers also rely on firmware to translate I/O (input/output) requests from the CPU.

Accessing Main Memory

Data flows back and forth between the processor and the DRAM main memory over shared electrical conduits called buses. Each transfer of data between the CPU and memory is accomplished with a series of steps called a bus transaction. A read transaction transfers data from the main memory to the CPU. A write transaction transfers data from the CPU to the main memory. A bus is a collection of parallel wires that carry address, data, and control signals. Depending on the particular bus design, data and address signals can share the same set of wires, or they can use different sets. Also, more than two devices can share the same bus. The control wires carry signals that synchronize the transaction and identify what kind of transaction is currently being performed. For example,

Section 6.1 Storage Technologies 569

(a) CPU places address A on the memory bus.

Main memory

Bus interface

Register file

I/O bridge

ALU

A X

0 A

%eax

(b) Main memory reads A from the bus, retrieves word x, and places it on the bus.

Register file

Main memory

Bus interface

I/O bridge

ALU

x X

0 A

%eax

(c) CPU reads word x from the bus, and copies it into register %eax.

Register file

Main memory

Bus interface

I/O bridge

ALU

X

X

0 A

%eax

Figure 6.7 Memory read transaction for a load operation: movl A,%eax.

bus, reads the address from the memory bus, fetches the data word from the DRAM, and writes the data to the memory bus. The I/O bridge translates the memory bus signal into a system bus signal, and passes it along to the system bus (Figure 6.7(b)). Finally, the CPU senses the data on the system bus, reads it from the bus, and copies it to register %eax (Figure 6.7(c)). Conversely, when the CPU performs a store instruction such as

movl %eax,A

where the contents of register %eax are written to address A, the CPU initiates a write transaction. Again, there are three basic steps. First, the CPU places the address on the system bus. The memory reads the address from the memory bus and waits for the data to arrive (Figure 6.8(a)). Next, the CPU copies the data word in %eax to the system bus (Figure 6.8(b)). Finally, the main memory reads the data word from the memory bus and stores the bits in the DRAM (Figure 6.8(c)).

570 Chapter 6 The Memory Hierarchy

(a) CPU places address A on the memory bus. Main memory reads it and waits for the data word.

Register file

Main memory

Bus interface

I/O bridge

ALU

A

y

0

A

%eax

(b) CPU places data word y on the bus.

Register file

Main memory

Bus interface

I/O bridge

ALU

y

y

0

A

%eax

(c) Main memory reads data word y from the bus and stores it at address A.

Register file

Main memory

Bus interface

I/O bridge

y^ ALU

0 y A

%eax

Figure 6.8 Memory write transaction for a store operation: movl %eax,A.

6.1.2 Disk Storage

Disks are workhorse storage devices that hold enormous amounts of data, on the order of hundreds to thousands of gigabytes, as opposed to the hundreds or thousands of megabytes in a RAM-based memory. However, it takes on the order of milliseconds to read information from a disk, a hundred thousand times longer than from DRAM and a million times longer than from SRAM.

Disk Geometry

Disks are constructed from platters. Each platter consists of two sides, or surfaces , that are coated with magnetic recording material. A rotating spindle in the center of the platter spins the platter at a fixed rotational rate , typically between 5400 and

Section 6.2 Locality 587

Locality is typically described as having two distinct forms: temporal locality and spatial locality. In a program with good temporal locality, a memory location that is referenced once is likely to be referenced again multiple times in the near future. In a program with good spatial locality, if a memory location is referenced once, then the program is likely to reference a nearby memory location in the near future. Programmers should understand the principle of locality because, in general, programs with good locality run faster than programs with poor locality. All levels of modern computer systems, from the hardware, to the operating system, to application programs, are designed to exploit locality. At the hardware level, the principle of locality allows computer designers to speed up main memory accesses by introducing small fast memories known as cache memories that hold blocks of the most recently referenced instructions and data items. At the operating system level, the principle of locality allows the system to use the main memory as a cache of the most recently referenced chunks of the virtual address space. Similarly, the operating system uses main memory to cache the most recently used disk blocks in the disk file system. The principle of locality also plays a crucial role in the design of application programs. For example, Web browsers exploit temporal locality by caching recently referenced documents on a local disk. High-volume Web servers hold recently requested documents in front-end disk caches that satisfy requests for these documents without requiring any intervention from the server.

6.2.1 Locality of References to Program Data

Consider the simple function in Figure 6.19(a) that sums the elements of a vector. Does this function have good locality? To answer this question, we look at the reference pattern for each variable. In this example, the sum variable is referenced once in each loop iteration, and thus there is good temporal locality with respect to sum. On the other hand, since sum is a scalar, there is no spatial locality with respect to sum. As we see in Figure 6.19(b), the elements of vector v are read sequentially, one after the other, in the order they are stored in memory (we assume for convenience that the array starts at address 0). Thus, with respect to variable v, the function has good spatial locality but poor temporal locality since each vector element

1 int sumvec(int v[N]) 2 { 3 int i, sum = 0; 4 5 for (i = 0; i < N; i++) 6 sum += v[i]; 7 return sum; 8 } (a)

Address 0 4 8 12 16 20 24 28 Contents v 0 v 1 v 2 v 3 v 4 v 5 v 6 v 7

Access order 1 2 3 4 5 6 7 8

(b)

Figure 6.19 (a) A function with good locality. (b) Reference pattern for vector v ( N = 8). Notice how the vector elements are accessed in the same order that they are stored in memory.

588 Chapter 6 The Memory Hierarchy

1 int sumarrayrows(int a[M][N]) 2 { 3 int i, j, sum = 0; 4 5 for (i = 0; i < M; i++) 6 for (j = 0; j < N; j++) 7 sum += a[i][j]; 8 return sum; 9 } (a)

Address 0 4 8 12 16 20 Contents a 00 a 01 a 02 a 10 a 11 a 12

Access order 1 2 3 4 5 6

(b)

Figure 6.20 (a) Another function with good locality. (b) Reference pattern for array a ( M = 2, N = 3). There is good spatial locality because the array is accessed in the same row-major order in which it is stored in memory.

is accessed exactly once. Since the function has either good spatial or temporal locality with respect to each variable in the loop body, we can conclude that the sumvec function enjoys good locality. A function such as sumvec that visits each element of a vector sequentially is said to have a stride-1 reference pattern (with respect to the element size). We will sometimes refer to stride-1 reference patterns as sequential reference patterns. Visiting every kth element of a contiguous vector is called a stride- k reference pattern. Stride-1 reference patterns are a common and important source of spatial locality in programs. In general, as the stride increases, the spatial locality decreases. Stride is also an important issue for programs that reference multidimensional arrays. For example, consider the sumarrayrows function in Figure 6.20(a) that sums the elements of a two-dimensional array. The doubly nested loop reads the elements of the array in row-major order. That is, the inner loop reads the elements of the first row, then the second row, and so on. The sumarrayrows function enjoys good spatial locality because it references the array in the same row-major order that the array is stored (Figure 6.20(b)). The result is a nice stride-1 reference pattern with excellent spatial locality. Seemingly trivial changes to a program can have a big impact on its locality. For example, the sumarraycols function in Figure 6.21(a) computes the same result as the sumarrayrows function in Figure 6.20(a). The only difference is that we have interchanged the i and j loops. What impact does interchanging the loops have on its locality? The sumarraycols function suffers from poor spatial locality because it scans the array column-wise instead of row-wise. Since C arrays are laid out in memory row-wise, the result is a stride-N reference pattern, as shown in Figure 6.21(b).

6.2.2 Locality of Instruction Fetches

Since program instructions are stored in memory and must be fetched (read) by the CPU, we can also evaluate the locality of a program with respect to its instruction fetches. For example, in Figure 6.19 the instructions in the body of the

590 Chapter 6 The Memory Hierarchy

glance at a source code and getting a high-level feel for the locality in the program is a useful and important skill for a programmer to master.

Practice Problem 6.

Permute the loops in the following function so that it scans the three-dimensional array a with a stride-1 reference pattern.

1 int sumarray3d(int a[N][N][N]) 2 { 3 int i, j, k, sum = 0; 4 5 for (i = 0; i < N; i++) { 6 for (j = 0; j < N; j++) { 7 for (k = 0; k < N; k++) { 8 sum += a[k][i][j]; 9 } 10 } 11 } 12 return sum; 13 }

Practice Problem 6.

The three functions in Figure 6.22 perform the same operation with varying de- grees of spatial locality. Rank-order the functions with respect to the spatial local- ity enjoyed by each. Explain how you arrived at your ranking.

(a) An array of structs 1 #define N 1000 2 3 typedef struct { 4 int vel[3]; 5 int acc[3]; 6 } point; 7 8 point p[N];

(b) The clear1 function 1 void clear1(point *p, int n) 2 { 3 int i, j; 4 5 for (i = 0; i < n; i++) { 6 for (j = 0; j < 3; j++) 7 p[i].vel[j] = 0; 8 for (j = 0; j < 3; j++) 9 p[i].acc[j] = 0; 10 } 11 } Figure 6.22 Code examples for Practice Problem 6.9.

Section 6.3 The Memory Hierarchy 591

(c) The clear2 function

1 void clear2(point *p, int n) 2 { 3 int i, j; 4 5 for (i = 0; i < n; i++) { 6 for (j = 0; j < 3; j++) { 7 p[i].vel[j] = 0; 8 p[i].acc[j] = 0; 9 } 10 } 11 }

(d) The clear3 function 1 void clear3(point *p, int n) 2 { 3 int i, j; 4 5 for (j = 0; j < 3; j++) { 6 for (i = 0; i < n; i++) 7 p[i].vel[j] = 0; 8 for (i = 0; i < n; i++) 9 p[i].acc[j] = 0; 10 } 11 }

Figure 6.22 (continued) Code examples for Practice Problem 6.9.

6.3 The Memory Hierarchy

Sections 6.1 and 6.2 described some fundamental and enduring properties of storage technology and computer software:

. (^) Storage technology: Different storage technologies have widely different ac- cess times. Faster technologies cost more per byte than slower ones and have less capacity. The gap between CPU and main memory speed is widening. . (^) Computer software: Well-written programs tend to exhibit good locality.

In one of the happier coincidences of computing, these fundamental properties of hardware and software complement each other beautifully. Their complemen- tary nature suggests an approach for organizing memory systems, known as the memory hierarchy , that is used in all modern computer systems. Figure 6.23 shows a typical memory hierarchy. In general, the storage devices get slower, cheaper, and larger as we move from higher to lower levels. At the highest level (L0) are a small number of fast CPU registers that the CPU can access in a single clock cycle. Next are one or more small to moderate-sized SRAM-based cache memories that can be accessed in a few CPU clock cycles. These are followed by a large DRAM- based main memory that can be accessed in tens to hundreds of clock cycles. Next are slow but enormous local disks. Finally, some systems even include an addi- tional level of disks on remote servers that can be accessed over a network. For example, distributed file systems such as the Andrew File System (AFS) or the Network File System (NFS) allow a program to access files that are stored on re- mote network-connected servers. Similarly, the World Wide Web allows programs to access remote files stored on Web servers anywhere in the world.

Section 6.3 The Memory Hierarchy 593

4 9 14 3

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Level k :

Level k 1:

Smaller, faster, more expensive device at level k caches a subset of the blocks from level k 1.

Larger, slower, cheaper storage device at level k 1 is partitioned into blocks.

Data is copied between levels in block-sized transfer units.

Figure 6.24 The basic principle of caching in a memory hierarchy.

Figure 6.24 shows the general concept of caching in a memory hierarchy. The storage at level k + 1 is partitioned into contiguous chunks of data objects called blocks. Each block has a unique address or name that distinguishes it from other blocks. Blocks can be either fixed-sized (the usual case) or variable-sized (e.g., the remote HTML files stored on Web servers). For example, the level k + 1 storage in Figure 6.24 is partitioned into 16 fixed-sized blocks, numbered 0 to 15. Similarly, the storage at level k is partitioned into a smaller set of blocks that are the same size as the blocks at level k + 1. At any point in time, the cache at level k contains copies of a subset of the blocks from level k + 1. For example, in Figure 6.24, the cache at level k has room for four blocks and currently contains copies of blocks 4, 9, 14, and 3. Data is always copied back and forth between level k and level k + 1 in block- sized transfer units. It is important to realize that while the block size is fixed between any particular pair of adjacent levels in the hierarchy, other pairs of levels can have different block sizes. For example, in Figure 6.23, transfers between L and L0 typically use one-word blocks. Transfers between L2 and L1 (and L3 and L2, and L4 and L3) typically use blocks of 8 to 16 words. And transfers between L5 and L4 use blocks with hundreds or thousands of bytes. In general, devices lower in the hierarchy (further from the CPU) have longer access times, and thus tend to use larger block sizes in order to amortize these longer access times.

Cache Hits

When a program needs a particular data object d from level k + 1, it first looks for d in one of the blocks currently stored at level k. If d happens to be cached at level k, then we have what is called a cache hit. The program reads d directly from level k, which by the nature of the memory hierarchy is faster than reading d from level k + 1. For example, a program with good temporal locality might read a data object from block 14, resulting in a cache hit from level k.

594 Chapter 6 The Memory Hierarchy

Cache Misses

If, on the other hand, the data object d is not cached at level k, then we have what is called a cache miss. When there is a miss, the cache at level k fetches the block containing d from the cache at level k + 1, possibly overwriting an existing block if the level k cache is already full. This process of overwriting an existing block is known as replacing or evicting the block. The block that is evicted is sometimes referred to as a victim block. The decision about which block to replace is governed by the cache’s replacement policy. For example, a cache with a random replacement policy would choose a random victim block. A cache with a least-recently used (LRU) replacement policy would choose the block that was last accessed the furthest in the past. After the cache at level k has fetched the block from level k + 1, the program can read d from level k as before. For example, in Figure 6.24, reading a data object from block 12 in the level k cache would result in a cache miss because block 12 is not currently stored in the level k cache. Once it has been copied from level k + 1 to level k, block 12 will remain there in expectation of later accesses.

Kinds of Cache Misses

It is sometimes helpful to distinguish between different kinds of cache misses. If the cache at level k is empty, then any access of any data object will miss. An empty cache is sometimes referred to as a cold cache , and misses of this kind are called compulsory misses or cold misses. Cold misses are important because they are often transient events that might not occur in steady state, after the cache has been warmed up by repeated memory accesses. Whenever there is a miss, the cache at level k must implement some placement policy that determines where to place the block it has retrieved from level k + 1. The most flexible placement policy is to allow any block from level k + 1 to be stored in any block at level k. For caches high in the memory hierarchy (close to the CPU) that are implemented in hardware and where speed is at a premium, this policy is usually too expensive to implement because randomly placed blocks are expensive to locate. Thus, hardware caches typically implement a more restricted placement policy that restricts a particular block at level k + 1 to a small subset (sometimes a singleton) of the blocks at level k. For example, in Figure 6.24, we might decide that a block i at level k + 1 must be placed in block (i mod 4) at level k. For example, blocks 0, 4, 8, and 12 at level k + 1 would map to block 0 at level k; blocks 1, 5, 9, and 13 would map to block 1; and so on. Notice that our example cache in Figure 6.24 uses this policy. Restrictive placement policies of this kind lead to a type of miss known as a conflict miss , in which the cache is large enough to hold the referenced data objects, but because they map to the same cache block, the cache keeps missing. For example, in Figure 6.24, if the program requests block 0, then block 8, then block 0, then block 8, and so on, each of the references to these two blocks would miss in the cache at level k, even though this cache can hold a total of four blocks.