A apresentação está carregando. Por favor, espere

A apresentação está carregando. Por favor, espere

MO401 Arquitetura de Computadores I

Apresentações semelhantes


Apresentação em tema: "MO401 Arquitetura de Computadores I"— Transcrição da apresentação:

1 MO401 Arquitetura de Computadores I
Review today, not so fast in future 2006/2007 Prof. Paulo Cesar Centoducatte

2 MO401 Livro Texto: “Computer Architecture: A Quantitative Approach” - 4rd edition Hennessy & Patterson Revisão: “Computer Organization and Design the hardware / software interface” Patterson & Hennessy Revisão em sala: Pipelining, Desempenho, Hierarquia de Memórias (cache)

3 Sumário Revisão Fundamentos Conjunto de Instruções
Paralelismo no nível de instruções (ILP) Exploração dinâmica (Superescalar) ILP por software (VLIW) Hierarquia de Memórias Multiprocessadores Sistemas de Armazenamento Redes e Clusters

4 MO401 Arquitetura de Computadores I Revisão: Pipeline, Desempenho e Hierarquia de Memórias (Caches)
“Computer Organization and Design the hardware / software interface” “Computer Architecture: A Quantitative Approach” - (Apêndice A) Review today, not so fast in future

5 Revisão: Pipeline Review today, not so fast in future

6 Pipelining - Conceito Exemplo: Lavanderia 4 trouxas para serem lavadas
Lavar: 30 minutos Secar: 40 minutos Passar: 20 minutos A B C D

7 Lavanderia Seqüencial
6 7 8 9 10 11 Horas Tempo O r d e m T a f s 30 40 20 30 40 20 30 40 20 30 40 20 A B C D Lavanderia seqüencial: 6 horas para lavar 4 trouxas Se for usado pipelining, quanto tempo?

8 Lavanderia Pipelined 6 7 8 9 10 11 Horas 30 40 20 A B C D
Tempo O r d e m T a f s 30 40 20 A B C D Lavanderia Pipelined: 3.5 horas para 4 trouxas

9 Pipelining O Pipelining não ajuda na latência de uma tarefa, ajuda no throughput de toda a carga de trabalho O período do Pipeline é limitado pelo estágio mais lento Múltiplas tarefas simultâneas Speedup potencial = Número de estágios Estágios não balanceados reduzem o speedup O Tempo de “preenchimento” e de “esvaziamento“ reduzem o speedup 6 7 8 9 Time T a s k O r d e 30 40 20 A B C D

10 CPU Pipelines Executam bilhões de instruções: throughput
Características desejáveis em um conjunto de instruções (ISA) para pipelining? Instruções de tamanho variável vs. Todas instruções do mesmo tamanho? Operandos em memória em qq operações vs. operandos em memória somente para loads e stores? Formato das instruções irregular vs. formato regular das instruções (ié. Operandos nos mesmos lugares)?

11 Um RISC Típico Formato de instruções de 32-bit (3 formatos)
Acesso à memória somente via instruções load/store 32 GPR de 32-bits (R0 contém zero) Instruções aritméticas: 3-address, reg-reg, registradores no mesmo lugar Modo de endereçamento simples para load/store (base + displacement) Sem indireção Condições simples para o branch Delayed branch SPARC, MIPS, HP PA-Risc, DEC Alpha, IBM PowerPC, CDC 6600, CDC 7600, Cray-1, Cray-2, Cray-3

12 Exemplo: MIPS (Localização dos regs)
Register-Register 31 26 25 21 20 16 15 11 10 6 5 Op Rs1 Rs2 Rd Opx Register-Immediate 31 26 25 21 20 16 15 immediate Op Rs1 Rd Branch 31 26 25 21 20 16 15 immediate Op Rs1 Rs2 Jump / Call 31 26 25 target Op

13 MIPS Datapath - 5 estágios
Instruction Fetch Instr. Decode Reg. Fetch Execute Addr. Calc Memory Access Write Back Next PC MUX 4 Adder Next SEQ PC Zero? RS1 Reg File Address MUX Memory RS2 ALU Inst Memory Data L M D RD MUX MUX Sign Extend Imm WB Data

14 MIPS Datapath - 5 estágios
Instruction Fetch Instr. Decode Reg. Fetch Execute Addr. Calc Memory Access Write Back Next PC IF/ID ID/EX MEM/WB EX/MEM MUX Next SEQ PC Next SEQ PC 4 Adder Zero? RS1 Reg File Address Memory MUX RS2 ALU Memory Data MUX MUX Sign Extend Imm WB Data RD RD RD

15 Pipelining Time (clock cycles) I n s t r. O r d e Cycle 1 Cycle 2
Reg ALU DMem Ifetch Cycle 1 Cycle 2 Cycle 3 Cycle 4 Cycle 6 Cycle 7 Cycle 5 I n s t r. O r d e

16 Limites de Pipelining Hazards: impedem que a próxima instrução seja executada no ciclo de clock “previsto” para ela Structural hazards: O HW não suporta uma dada combinação de instruções Data hazards: Uma Instrução depende do resultado da instrução anterior que ainda está no pipeline Control hazards: Causado pelo delay entre o fetching de uma instrução e a decisão sobre a mudança do fluxo de execução (branches e jumps).

17 Memória Única (D/I) - Structural Hazards
Time (clock cycles) Cycle 1 Cycle 2 Cycle 3 Cycle 4 Cycle 5 Cycle 6 Cycle 7 ALU I n s t r. O r d e Load Ifetch Reg DMem Reg Reg ALU DMem Ifetch Instr 1 Reg ALU DMem Ifetch Instr 2 ALU Instr 3 Ifetch Reg DMem Reg Reg ALU DMem Ifetch Instr 4

18 Memória Única (D/I) - Structural Hazards
Time (clock cycles) Cycle 1 Cycle 2 Cycle 3 Cycle 4 Cycle 5 Cycle 6 Cycle 7 ALU I n s t r. O r d e Load Ifetch Reg DMem Reg Reg ALU DMem Ifetch Instr 1 Reg ALU DMem Ifetch Instr 2 Bubble Stall Reg ALU DMem Ifetch Instr 3

19 Data Hazards Read After Write (RAW)
InstrJ lê o operando antes da InstrI escreve-lo Causada por uma “Dependência” (nomenclatura de compiladores). I: add r1,r2,r3 J: sub r4,r1,r3

20 Data Hazard em R1 add r1,r2,r3 sub r4,r1,r3 and r6,r1,r7 or r8,r1,r9
Time (clock cycles) IF ID/RF EX MEM WB I n s t r. O r d e add r1,r2,r3 sub r4,r1,r3 and r6,r1,r7 or r8,r1,r9 xor r10,r1,r11 Reg ALU DMem Ifetch

21 Data Hazards Write After Read (WAR) InstrJ escreve o operando antes que a InstrI o leia Chamada “anti-dependência” (nomenclatura de compiladores). Devido ao reuso do nome “r1”. Não ocorre no pipeline do MIPS: Todas instruções usam 5 estágios, e Leituras são no estágio 2, e Escritas são no estágio 5 I: sub r4,r1,r3 J: add r1,r2,r3 K: mul r6,r1,r7

22 Data Hazards Write After Write (WAW) InstrJ escreve o operando antes que a InstrI o escreva. Chamada “dependência de saída” (nomenclatura de compiladores). Devido ao reuso do nome “r1”. Não ocorre no pipeline do MIPS: Todas Instruções são de 5 estágios, e Escritas são sempre no 5 estágio (WAR e WAW ocorrem em pipelines mais sofisticados) I: sub r1,r4,r3 J: add r1,r2,r3 K: mul r6,r1,r7

23 Data Hazards – Solução por SW
Compilador reconhece o data hazard e troca a ordem das instruções (quando possível) Compilador reconhece o data hazard e adiciona nops Exemplo: sub R2, R1, R3 ; reg R2 escrito por sub nop ; no operation nop and R12, R2, R5 ; resultado do sub disponível or R13, R6, R2 add R14, R2, R2 sw 100 (R2), R15

24 Data Hazard Control: Stalls
Hazard ocorre quando a instr. Lê (no estágio ID) um reg que será escrito, por uma instr. anterior (no estágio EX, MEM, WB) Solução: Detectar o hazard e parar a instrução no pipeline até o hazard ser resolvido Detectar o hazard pela comparação do campo read no IF/ID pipeline register com o campo write dos outros pipeline registers (ID/EX, EX/MEM, MEM/WB) Adicionar bubble no pipeline – Preservar o PC e o IF/ID pipeline register

25 MIPS Datapath - 5 estágios
Instruction Fetch Instr. Decode Reg. Fetch Execute Addr. Calc Memory Access Write Back Next PC IF/ID ID/EX MEM/WB EX/MEM MUX Next SEQ PC Next SEQ PC 4 Adder Zero? RS1 Reg File Address Memory MUX RS2 ALU Memory Data MUX MUX Sign Extend Imm WB Data RD RD RD

26 Redução do Data Hazard - Forwarding
Time (clock cycles) I n s t r. O r d e add r1,r2,r3 sub r4,r1,r3 and r6,r1,r7 or r8,r1,r9 xor r10,r1,r11 Reg ALU DMem Ifetch

27 HW para Forwarding ID/EX EX/MEM MEM/WR mux Registers Data Memory mux
NextPC mux Registers ALU Data Memory mux mux Immediate

28 Data Hazard com Forwarding
Time (clock cycles) Reg ALU DMem Ifetch I n s t r. O r d e lw r1, 0(r2) sub r4,r1,r6 and r6,r1,r7 or r8,r1,r9 MIPS actutally didn’t interlecok: MPU without Interlocked Pipelined Stages

29 Data Hazard com Forwarding
Time (clock cycles) I n s t r. O r d e Reg ALU DMem Ifetch lw r1, 0(r2) Reg Ifetch ALU DMem Bubble sub r4,r1,r6 Ifetch ALU DMem Reg Bubble and r6,r1,r7 Bubble Ifetch Reg ALU DMem or r8,r1,r9

30 Load Hazards - Software Scheduling
Código para (a, b, c, d ,e, f na memória). a = b + c; d = e – f; Slow code: LW Rb,b LW Rc,c ADD Ra,Rb,Rc SW a,Ra LW Re,e LW Rf,f SUB Rd,Re,Rf SW d,Rd Fast code: LW Rb,b LW Rc,c LW Re,e ADD Ra,Rb,Rc LW Rf,f SW a,Ra SUB Rd,Re,Rf SW d,Rd

31 Control Hazard - Branches (3 estágios de Stall)
Reg ALU DMem Ifetch 10: beq r1,r3,36 14: and r2,r3,r5 18: or r6,r1,r7 22: add r8,r1,r9 36: xor r10,r1,r11 Reg ALU DMem Ifetch Reg ALU DMem Ifetch ALU Ifetch Reg DMem Reg Reg ALU DMem Ifetch

32 MIPS Datapath - 5 estágios
Instruction Fetch Instr. Decode Reg. Fetch Execute Addr. Calc Memory Access Write Back Next PC IF/ID ID/EX MEM/WB EX/MEM MUX Next SEQ PC Next SEQ PC 4 Adder Zero? RS1 Reg File Address Memory MUX RS2 ALU Memory Data MUX MUX Sign Extend Imm WB Data RD RD RD

33 Exemplo: Impacto do Branch Stall
Se CPI = 1, 30% branches, 3-cycle stall  CPI = 1.9! Solução para minimizar os efeitos: Determinar branch taken ou não o mais cedo, e Calcular o endereço alvo do branch logo MIPS branch: testa se reg = 0 ou  0 Solução MIPS: Zero test no estágio ID/RF Adder para calcular o novo PC no estágio ID/RF 1 clock cycle penalty por branch versus 3

34 Pipelined MIPS Datapath
Instruction Fetch Instr. Decode Reg. Fetch Execute Addr. Calc Memory Access Write Back Next PC Next SEQ PC ID/EX EX/MEM MEM/WB MUX 4 Adder IF/ID Adder Zero? RS1 Address Reg File Memory RS2 ALU Memory Data MUX MUX Sign Extend Imm WB Data RD RD RD

35 Alternativas para Branch Hazard
#1: Stall até a decisão se o branch será tomado ou não #2: Predict Branch Not Taken Executar a próxima instrução “Invalidar” as instruções no pipeline se branch é tamado Vantagem: retarda a atualização do pipeline 47% dos branches no MIPS não são tomados, em média PC+4 já está computado, use-o para pegar a próxima instrução #3: Predict Branch Taken 53% dos branches do MIPS são tomados, em média “branch target address” no MIPS ainda não foi calculado 1 cycle branch penalty Em outras máquinas esse penalty pode não ocorrer

36 Alternativas para Branch Hazard
#4: Delayed Branch Define-se que o branch será tamado APÓS a uma dada quantidade de instruções branch instruction sequential successor1 sequential successor sequential successorn branch target if taken 1 slot delay permite a decisão e o calculo do “branch target address” no pipeline de 5 estágios MIPS usa está solução Branch delay de tamanho n (n slots delay)

37 Delayed Branch Qual instrução usar para preencher o branch delay slot?
Antes do branch Do target address ( avaliada somente se branch taken) Após ao branch (somente avaliada se branch not taken)

38 Delayed Branch

39 Delayed Branch Compilador: single branch delay slot:
Preenche +/- 60% dos branch delay slots +/- 80% das instruções executadas no branch delay slots são utéis à computação +/- 50% (60% x 80%) dos slots preenchidos são utéis

40 Revisão: Desempenho Review today, not so fast in future

41 Qual o mais rápido? Time to run the task (ExTime)
Plane DC to Paris 6.5 hours 3 hours Speed 610 mph 1350 mph Passengers 470 132 Throughput (pmph) 286,700 178,200 Boeing 747 BAD/Sud Concorde Time to run the task (ExTime) Execution time, response time, latency Tasks per day, hour, week, sec, ns … (Desempenho) Throughput, bandwidth Fastest for 1 person? Which takes less time to transport 470 passengers?

42 Definições Desempenho (performance) é em unidades por segundo
Quanto maior melhor performance(x) = execution_time(x) " X é n vezes mais rápido que Y" significa que: Performance(X) Execution_time(Y) n = = Performance(Y) Execution_time(X)

43 Aspectos sobre Desempenho de CPU (CPU Law)
CPU time = Seconds = Instructions x Cycles x Seconds Program Program Instruction Cycle Inst Count CPI Clock Rate Program X Compiler X (X) Inst. Set X X Organization X X Technology X

44 Instruções por Ciclo (Throughput)
“Cycles per Instruction” médio CPI = (CPU Time * Clock Rate) / Instruction Count = Cycles / Instruction Count “Freqüência das Instruções”

45 Exemplo: Calculando CPI
Base Machine (Reg / Reg) Op Freq Cycles CPI(i) (% Time) ALU 50% (33%) Load 20% (27%) Store 10% (13%) Branch 20% (27%) 1.5 Mix típico de instruções em programas

46 Exemplo: Impacto de Branch Stall
Assuma: CPI = 1.0 (ignorando branches stall por 3 ciclos) Se 30% são branch, Stall 3 ciclos Op Freq Cycles CPI(i) (% Time) Other 70% (37%) Branch 30% (63%) => novo CPI = 1.9, ou aproximadamente 2 vezes mais lento

47 Exemplo 2: SpeedUp para Pipelining
For simple RISC pipeline, CPI = 1:

48 Exemplo 3: Branch Alternativas
Scheduling Branch CPI speedup v. scheme penalty stall Stall pipeline Predict taken Predict not taken Delayed branch

49 Exemplo 4: Dual-port vs. Single-port
Máquina A: Dual ported memory (“Harvard Architecture”) Máquina B: Single ported memory, porém seu pipelined é 1.05 vezes mais rápido (clock rate) CPI Ideal = 1 para ambas Loads: 40% das instruções executadas SpeedUpA = Pipeline Depth/(1 + 0) x (clockunpipe/clockpipe) = Pipeline Depth SpeedUpB = Pipeline Depth/( x 1) x (clockunpipe/(clockunpipe / 1.05) = (Pipeline Depth/1.4) x 1.05 = 0.75 x Pipeline Depth SpeedUpA / SpeedUpB = Pipeline Depth/(0.75 x Pipeline Depth) = 1.33 Máquina A é 1.33 mais rápida que a B

50 Revisão: Hierarquia de Memórias

51 Time 1000 100 Performance 10 1 Processor-DRAM Memory Gap (latency)
60%/yr. (2X/1.5yr) 1000 CPU “Moore’s Law” 100 Processor-Memory Performance Gap: (grows 50% / year) Performance 10 DRAM 9%/yr. (2X/10yrs) Y-axis is performance X-axis is time Latency Cliché: Not e that x86 didn’t have cache on chip until 1989 DRAM 1 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 Time

52 Níveis em uma Hierarquia de Memórias
CPU Upper Level Capacidade Access Time Custo Staging Xfer Unit faster CPU Registers 100s Bytes <1s ns Registers Instr. Operands prog./compiler 1-8 bytes Cache 10s-100s K Bytes 1-10 ns $10/ MByte Cache cache cntl 8-128 bytes Blocks Main Memory M Bytes 50ns- 70ns $1/ MByte Memory OS 512-4K bytes Pages Disk 10s G Bytes, 10 ms (10,000,000 ns) $0.002/ MByte Disk user/operator Mbytes Files Larger Tape “infinito” sec-min $0.0014/ MByte Tape Lower Level

53 Princípio da Localidadde
Princípio da Localidade: Programas acessam relativamente uma pequena porção do espaço de endereçamento em um dado instante de tempo. Dois tipos de Localidade: Localidadde Temporal (Localidade no Tempo): Se um item é referenciado, ele tende a ser referenciado outra vez em um curto espaço de tempo (loops) Localidade Espacial (Localidade no Espaço): Se um item é referenciado, itens próximos também tendem a serem referenciados em um curto espaço de tempo (acesso a array) The principle of locality states that programs access a relatively small portion of the address space at any instant of time. This is kind of like in real life, we all have a lot of friends. But at any given time most of us can only keep in touch with a small group of them. There are two different types of locality: Temporal and Spatial. Temporal locality is the locality in time which says if an item is referenced, it will tend to be referenced again soon. This is like saying if you just talk to one of your friends, it is likely that you will talk to him or her again soon. This makes sense. For example, if you just have lunch with a friend, you may say, let’s go to the ball game this Sunday. So you will talk to him again soon. Spatial locality is the locality in space. It says if an item is referenced, items whose addresses are close by tend to be referenced soon. Once again, using our analogy. We can usually divide our friends into groups. Like friends from high school, friends from work, friends from home. Let’s say you just talk to one of your friends from high school and she may say something like: “So did you hear so and so just won the lottery.” You probably will say NO, I better give him a call and find out more. So this is an example of spatial locality. You just talked to a friend from your high school days. As a result, you end up talking to another high school friend. Or at least in this case, you hope he still remember you are his friend. +3 = 10 min. (X:50)

54 Hierarquia de Memórias: Terminologia
Hit: o dado está no upper level (examplo: Block X) Hit Rate: taxa de hit no upper level no acesso à memória Hit Time: Tempo para o acesso no upper level, consiste em: RAM access time + Time to determine hit/miss Miss: o dado precisa ser buscado em um bloco no lower level (Block Y) Miss Rate = 1 - (Hit Rate) Miss Penalty: Tempo para colocar um bloco no upper level + Tempo para disponibilizar o dado para o processador Hit Time << Miss Penalty (500 instruções no 21264!) A HIT is when the data the processor wants to access is found in the upper level (Blk X). The fraction of the memory access that are HIT is defined as HIT rate. HIT Time is the time to access the Upper Level where the data is found (X). It consists of: (a) Time to access this level. (b) AND the time to determine if this is a Hit or Miss. If the data the processor wants cannot be found in the Upper level. Then we have a miss and we need to retrieve the data (Blk Y) from the lower level. By definition (definition of Hit: Fraction), the miss rate is just 1 minus the hit rate. This miss penalty also consists of two parts: (a) The time it takes to replace a block (Blk Y to BlkX) in the upper level. (b) And then the time it takes to deliver this new block to the processor. It is very important that your Hit Time to be much much smaller than your miss penalty. Otherwise, there will be no reason to build a memory hierarchy. +2 = 14 min. (X:54) Lower Level Memory Upper Level To Processor From Processor Blk X Blk Y

55 Cache: Direct Mapped Memory Address Memory 4 Byte Direct Mapped Cache 1 Cache Index 2 3 1 4 2 5 3 6 7 Posição 0 pode ser ocupada por dados dos endereços em memória: 0, 4, 8, ... etc. Em geral: qq endereço cujos 2 LSBs são 0s Address<1:0> => cache index Qual dado deve ser colocado na cache? Como definir o local, na cache, para cada dado? 8 9 A B Let’s look at the simplest cache one can build. A direct mapped cache that only has 4 bytes. In this direct mapped cache with only 4 bytes, location 0 of the cache can be occupied by data form memory location 0, 4, 8, C, ... and so on. While location 1 of the cache can be occupied by data from memory location 1, 5, 9, ... etc. So in general, the cache location where a memory location can map to is uniquely determined by the 2 least significant bits of the address (Cache Index). For example here, any memory location whose two least significant bits of the address are 0s can go to cache location zero. With so many memory locations to chose from, which one should we place in the cache? Of course, the one we have read or write most recently because by the principle of temporal locality, the one we just touch is most likely to be the one we will need again soon. Of all the possible memory locations that can be placed in cache Location 0, how can we tell which one is in the cache? +2 = 22 min. (Y:02) C D E F

56 1 KB Direct Mapped Cache, 32B blocks
Para uma cache de 2 ** N byte: Os (32 - N) bits de mais alta ordem são “Cache Tag” Os M bits de mais baixa ordem são “Byte Select” (Block Size = 2 ** M) 31 9 4 Cache Tag Example: 0x50 Cache Index Byte Select Ex: 0x01 Ex: 0x00 Stored as part of the cache “state” Valid Bit Cache Tag Cache Data : Byte 31 Byte 1 Byte 0 Let’s use a specific example with realistic numbers: assume we have a 1 KB direct mapped cache with block size equals to 32 bytes. In other words, each block associated with the cache tag will have 32 bytes in it (Row 1). With Block Size equals to 32 bytes, the 5 least significant bits of the address will be used as byte select within the cache block. Since the cache size is 1K byte, the upper 32 minus 10 bits, or 22 bits of the address will be stored as cache tag. The rest of the address bits in the middle, that is bit 5 through 9, will be used as Cache Index to select the proper cache entry. +2 = 30 min. (Y:10) : 0x50 Byte 63 Byte 33 Byte 32 1 2 3 : : : : Byte 1023 Byte 992 31

57 Two-way Set Associative Cache
N-way set associative: N entradas para cada Cache Index N direct mapped caches opera em paralelo (N típico: 2 a 4) Examplo: Two-way set associative cache Cache Index: seleciona um “set” na cache As duas tags no set são comparadas em paralelo O Dado é selecionado basedo no resultado da comparação das tag Cache Index Valid Cache Tag Cache Data Cache Data Cache Block 0 Cache Tag Valid : Cache Block 0 : : : This is called a 2-way set associative cache because there are two cache entries for each cache index. Essentially, you have two direct mapped cache works in parallel. This is how it works: the cache index selects a set from the cache. The two tags in the set are compared in parallel with the upper bits of the memory address. If neither tag matches the incoming address tag, we have a cache miss. Otherwise, we have a cache hit and we will select the data on the side where the tag matches occur. This is simple enough. What is its disadvantages? +1 = 36 min. (Y:16) Compare Adr Tag Compare 1 Sel1 Mux Sel0 OR Cache Block Hit

58 Desvantagem de Set Associative Cache
N-way Set Associative Cache v. Direct Mapped Cache: N comparadores vs. 1 MUX extra, atrasa o acesso ao dado Dado disponível APÓS Hit/Miss Direct mapped cache: Cache Block disponível ANTES do Hit/Miss: É possível assumir um hite e continuar. Se miss, Recover. Cache Data Cache Block 0 Cache Tag Valid : Cache Index Mux 1 Sel1 Sel0 Cache Block Compare Adr Tag OR Hit First of all, a N-way set associative cache will need N comparators instead of just one comparator (use the right side of the diagram for direct mapped cache). A N-way set associative cache will also be slower than a direct mapped cache because of this extra multiplexer delay. Finally, for a N-way set associative cache, the data will be available AFTER the hit/miss signal becomes valid because the hit/mis is needed to control the data MUX. For a direct mapped cache, that is everything before the MUX on the right or left side, the cache block will be available BEFORE the hit/miss signal (AND gate output) because the data does not have to go through the comparator. This can be an important consideration because the processor can now go ahead and use the data without knowing if it is a Hit or Miss. Just assume it is a hit. Since cache hit rate is in the upper 90% range, you will be ahead of the game 90% of the time and for those 10% of the time that you are wrong, just make sure you can recover. You cannot play this speculation game with a N-way set-associatvie cache because as I said earlier, the data will not be available to you until the hit/miss signal is valid. +2 = 38 min. (Y:18)

59 Hierarquia de Memória: 4 Questões
Q1: Em que lugar colocar um bloco no upper level? (Block placement) Q2: Como localizar o bloco se ele está no upper level? (Block identification) Q3: Qual bloco deve ser trocado em um miss? (Block replacement) Q4: O que ocorre em um write? (Write strategy)

60 Q1: Em que lugar colocar um bloco no upper level?
Colocar o Bloco 12 em uma cache de 8 blocos : Fully associative, direct mapped, 2-way set associative S.A. Mapping = Block Number Modulo Number Sets Direct Mapped (12 mod 8) = 4 2-Way Assoc (12 mod 4) = 0 Full Mapped Cache Memory

61 Q2: Como localizar o bloco se ele está no upper level?
Tag em cada bloco Não é necessário testar o index ou block offset O aumento da associatividade reduz o index e aumenta a tag Block Offset Block Address Index Tag

62 Q3: Qual bloco deve ser trocado em um miss?
Fácil para Direct Mapped Set Associative or Fully Associative: Random LRU (Least Recently Used) FIFO Assoc: way way way Size LRU Ran LRU Ran LRU Ran 16 KB 5.2% 5.7% 4.7% % % % 64 KB 1.9% 2.0% % % % % 256 KB 1.15% 1.17% % 1.13% % 1.12% Taxa de misses na cache: blocos de 16 bytes na arquitetura Vax; acessos de usuários e do sistema operacional

63 Q4: O que ocorre em um write?
Write through — A informação é escrita tanto no bloco da cache quanto no bloco do lower-level memory. Write back — A informação é escrita somente no bloco da cache. O bloco da cache modificado é escrito na memória principal somente quando ele é trocaddo. block clean or dirty? Prós e Contras? WT: read misses não pode resultar em writes WB: não há repetição de writes na mesma posição WT, em geral, é combinado com write buffers, assim não há espera pelo lower level memory

64 Write Buffer para Write Through
Processor Cache Write Buffer DRAM Um Write Buffer colocado entre a Cache e a Memory Processador: escreve o dado na cache e no write buffer Memory controller: escreve o conteúdo do buffer na memória Write buffer é uma FIFO: Número típico de entradas: 4 Trabalha bem se: freqüência de escrita (w.r.t. time) << 1 / DRAM write cycle Memory system é um pesadelo para o projetista : freqüência de escrita (w.r.t. time) -> 1 / DRAM write cycle Saturação do Write buffer You are right, memory is too slow. We really didn't writ e to the memory directly. We are writing to a write buffer. Once the data is written into the write buffer and assuming a cache hit, the CPU is done with the write. The memory controller will then move the write buffer’s contents to the real memory behind the scene. The write buffer works as long as the frequency of store is not too high. Notice here, I am referring to the frequency with respect to time, not with respect to number of instructions. Remember the DRAM cycle time we talked about last time. It sets the upper limit on how frequent you can write to the main memory. If the store are too close together or the CPU time is so much faster than the DRAM cycle time, you can end up overflowing the write buffer and the CPU must stop and wait. +2 = 60 min. (Y:40)

65 Hierarquia de Memória Moderna
Tirando vantagens do príncipio da localidade: Provê ao usuário o máximo de memória disponibilizada pela tecnologia mais barata. Provê acesso na velocidade oferecida pela tecnologia mais rápida. Control Datapath Secondary Storage (Disk) Processor Registers Main Memory (DRAM) Second Level Cache (SRAM) On-Chip 1s 10,000,000s (10s ms) Speed (ns): 10s 100s Gs Size (bytes): Ks Ms Tertiary (Disk/Tape) 10,000,000,000s (10s sec) Ts The design goal is to present the user with as much memory as is available in the cheapest technology (points to the disk). While by taking advantage of the principle of locality, we like to provide the user an average access speed that is very close to the speed that is offered by the fastest technology. (We will go over this slide in details in the next lecture on caches). +1 = 16 min. (X:56)

66 Resumo #1/3: Pipelining & Desempenho
Sobreposição de tarefas; fácil se as tarefas são independentes Speed Up  Pipeline Depth; Se CPI ideal for 1, então: Hazards limita o desempenho nos computadores: Estrutural: é necessário mais recursos de HW Dados (RAW,WAR,WAW): forwarding, compiler scheduling Controle: delayed branch, prediction Tempo é a medida de desempenho: latência ou throughput CPI Law: CPU time = Seconds = Instructions x Cycles x Seconds Program Program Instruction Cycle

67 Resumo #2/3: Caches Princípio da Localidade:
Programas acessam relativamente uma pequena porção do espaço de endereçamento em um dado instante de tempo. Localidadde Temporal :Localidade no Tempo Localidade Espacial : Localidade no Espaço Cache Misses: 3 categorias Compulsory Misses Capacity Misses Conflict Misses Políticas de Escrita: Write Through: (write buffer) Write Back

68 Resumo #3/3: Cache Design
Várias Dimensões interagindo cache size block size associativity replacement policy write-through vs write-back Solução ótima é um compromiso Depende da característica dos acessos workload I-cache, D-cache, TLB Depende da razão tecnologia / custo Cache Size Associativity Block Size No fancy replacement policy is needed for the direct mapped cache. As a matter of fact, that is what cause direct mapped trouble to begin with: only one place to go in the cache--causes conflict misses. Besides working at Sun, I also teach people how to fly whenever I have time. Statistic have shown that if a pilot crashed after an engine failure, he or she is more likely to get killed in a multi-engine light airplane than a single engine airplane. The joke among us flight instructors is that: sure, when the engine quit in a single engine stops, you have one option: sooner or later, you land. Probably sooner. But in a multi-engine airplane with one engine stops, you have a lot of options. It is the need to make a decision that kills those people. Bad Good Factor A Factor B Less More


Carregar ppt "MO401 Arquitetura de Computadores I"

Apresentações semelhantes


Anúncios Google