Download clase-computadoras-mc

Document related concepts
no text concepts found
Transcript
Electrónica Digital
Computadoras
de la Arena al Lenguaje C
Ing. Jose Luis Hamkalo
Construyendo una
Computadora
Paso 1: La CPU
• EL camino de datos
Registros
Register file
ALU
Bus
• Señales disponibles
• El ciclo de instrucción
Búsqueda (Fetch)
Decodificación
Ejecución
• Secuenciamiento de instrucciones
Microoperaciones
Ejemplos
Registro con Salida de Alta
Impedancia
D_in_31
D
R_in
R_out
…
D_in_30
Ck
Q
D
Ck
D_out_31
Q
D_in_0
…
D_out_30
D
Q
Ck
…
D_out_0
Transferencias entre Registros
por un BUS
Din
Ain
A
Aout
Dout
Din
Bin
B
Bout
Dout
BUS
Para Copiar el contenido de A en B: Poner Aout y Bin en 1 (las otras en 0)
Transferencias entre Registros
por un BUS (continuación)
Din
B
Din
Ain
Bout
Dout
A
Aout
Bin
Dout
Din
Cin
C
Cout
Dout
BUS
Para Copiar el contenido de A en B y C al mismo tiempo!!!:
Poner Aout , Bin y Cin en 1 (las otras en 0)
Decodificador Binario
Pone en 1 la salida correspondiente al número
binario que se pone en las entradas .
El resto de las salidas en 0.
Se usa en todas la memorias (RAM)
La Unidad Aritmético Lógica
(ALU)
Solo hace cálculos (ni más ni menos!):
aritméticos, lógicos, comparaciones, etc.
Un ejemplo simple: opera sobre 2 bits (a y b)
solo hace OR y AND:
Ahora hacela de 32 bits y que además sume,
reste, multiplique, divida, etc.!!!
La Unidad Aritmético Lógica
(ALU)
Solo hace cálculos (ni más ni
menos!)
Pueder haber especializadas
y más de una!
A
Sumar
Restar
Dividir
B
1
ALU
...
A+B
La Unidad de Control
Es un circuito secuencial (Máquina de estado
Finito).
Recibe un código de operación como entrada y
genera una secuencia de señales de control en
tiempo en forma.
Entrada
(código de
Operación, i.e
sumar, copiar,
etc)
Lógica
Combinacional
Estado
Unidad de Control
Salida
(Señales de
Control, i.e. Aout,
Bin, SUMAR,
etc.)
Memoria
Celdas con información.
Se pueden leer o escribir.
Se acceden por su dirección (posición en
un arreglo).
Tipos
RAM
ROM (solo lectura)
FLASH
Memoria
Ejemplo RAM de 4 x 2 bits (que chiquita!, quiero
una de 4Gbytes!)
El Camino de Datos (Data
Path)
Poniéndolo todo junto
Qué es cada cosa?
Tenemos estas Señales
REGISTER control signal
Effect
ALUadd
Configures the ALU to add its inputs
ALUand
ALUxor
ALUor
ALUsll
ALUslt
ALUsrl
ALUsub
CONST(value)
Configures the ALU to bitwise AND its
inputs
Configures the ALU to bitwise eXclusive
OR its inputs
Configures the ALU to bitwise OR its
inputs
Configures the ALU to shift left logical;
the result is (bus << Y)
Configures the ALU to compare its
inputs; the result is (Y < bus)
Configures the ALU to shift right logical;
the result is (bus >> Y)
Configures the ALU to subtract the buss
input from Y
Places the constant value onto the bus
Y estas otras (quiero más!)
IRaddrout
Tri-state enables the portion of the Instruction Register that contains the
(26 bit, MIPS "J" format) address, along with the top 6 bits of the Program
Counter, to be driven onto the bus
IRimmedout
Tri-state enables the portion of the Instruction Register that contains the
(16 bit, MIPS "I" format) 2's complement immediate value to be signextended to 32 bits and driven onto the bus
IRin
Latches the bus data into the Instruction Register at the trailing edge of
the clock cycle
IRoffsetout
Tri-state enables the Instruction Register's shifted and sign extended
value from the offset field to be driven onto the bus (used for branches)
JUMP(label)
Microcode jump to label
JUMPonop
Microcode jump to label named like the opcode; e.g., if an "Addi" is in the
IR, jumps to the microcode label Addi
MARin
MARout
Latches the bus data into the Memory Address Register at the trailing
edge of the clock cycle
Tri-state enables the Memory Address Register's output to be driven onto
the bus
y las últimas
MDRin
MDRout
MEMread
MEMwrite
PCin
PCinif0
PCout
REGin
REGout
SELrs
SELrt
SELrd
UNTILmfc
Yin
Yout
Zin
Zout
Latches the bus data into the Memory Data Register at the trailing edge of the clock cycle
Tri-state enables the Memory Data Register's output to be driven onto the bus
Initiate a memory read from the address in the MAR; here, you may assume that the memory will take 2
clock cycles to respond
Initiate a memory write using the data in the MDR and the address in the MAR; in this simple design,
you may assume that a memory write takes precisely 1 clock cycle
Latches the bus data into the Program Counter at the trailing edge of the clock cycle
Only if the value in Z is zero, latch the bus data into the Program Counter at the trailing edge of the
clock cycle
Tri-state enables the Program Counter's output to be driven onto the bus
Latches the bus data into whichever register is selected by SELrs, SELrt, or SELrd; the value is latched
at the trailing edge of the clock cycle
Tri-state enables the output of whichever register is selected by SELrs, SELrt, or SELrd; the selected
value is driven onto the bus
Selects the rs field of the IR to be used to control the register file's decoder
Selects the rt field of the IR to be used to control the register file's decoder
Selects the rd field of the IR to be used to control the register file's decoder
Repeat this state until the memory has issued a memory fetch complete signal, indicating that the
fetched value will be valid to read from the MDR in the next clock cycle
Latches the bus data into the Y register at the trailing edge of the clock cycle; this register is needed
because, with only one bus, one of the two operands for a binary operation (e.g., Add) must come from
somewhere other than the bus
Tri-state enables the Y register's output to be driven onto the bus
The ALU is always producing a result, but we only make note of that result if we latch the ALU's output
into the Z register at the trailing edge of the clock cycle
Tri-state enables the Z Register's output to be driven onto the bus
Como hago una suma?: Paso a Paso
(Secuenciamiento de Instrucciones)
Start:
PCout, MARin, MEMread, Yin
CONST(4), ALUadd, Zin
Zout, PCin, UNTILmfc
MDRout, Irin, JUMPonop
...
Add: SELrs, REGout, Yin
SELrt, REGout, ALUadd, Zin
Zout, SELrd, REGin, JUMP(Start)
-Cada renglón se hace en un ciclo
-Las señales dentro de un renglón se hacen al mismo tiempo (en paralelo)
-En 7 ciclos logro sumar 2 registros! (El resultado lo guardo en un tercero)
Que tipos de instrucciones hay?
Aritmético-Lógicas
Acceso a Memoria (Load y Store)
Saltos
Condicionales
Incondicionales
Aritméticas de Punto Flotante (FP)
Sistema
Como vamos por ahora?
Una CPU que obtiene sus instrucciones y
datos de la memoria.
Y es capaz de ejecutarlas!
Que Clase de Computadora
Queremos?
• Computadoras de escritorio
 PCs y workstations
 Precio-desempeño óptimo
• Servidores
 Web
 Disponibilad
 Escalabilidad
• Procesadores embarcados
 Desempeño a precio mínimo
 Mínimo conumo de potencia
Un Mouse es un Sistema de
Cómputo!
-Mouse Óptico
LED ilumina el escritorio
Cámara de baja resol.
Procesador básico de
Imágenes detecta mov.
Botones y rueda.
-Supera al mouse
mecánico de bolita.
Quiero una computadora de alto
desempeño: La Arquitectura
MIPS 32
Conjunto de instrucciones simple,
Load/Store o tipo RISC (pocas
instrucciones).
Diseñada para eficiencia del pipeline
(procesamiento en línea de montaje)
Eficiencia para el compilador
La Arquitectura MIPS 32
• Registros
 32 registros de 32 bits: $0, $1, $2, $31 (int)
 32 registros de 32 bits: $f0, $f1, $f2, $f31 (fp)
• Tipos de datos
 Bytes (8 bits), Half Word (16 bits), Words (32 bits)
 Double words (fp)
• Modos de direccionamiento (Qué?)
 Inmediato
 Desplazamiento
CPU y FPU
de MIPS 32
Para el Sistema
(Windows, linux ...)
Convención de Uso de
Registros
Registers
Name
Number
Use
Callee must preserve?
$zero
$0
constant 0
N/A
$at
$1
assembler temporary
No
$v0–$v1
$2–$3
values for function
returns and expression
evaluation
No
$a0–$a3
$4–$7
function arguments
No
$t0–$t7
$8–$15
temporaries
No
$s0–$s7
$16–$23
saved temporaries
Yes
$t8–$t9
$24–$25
temporaries
No
$k0–$k1
$26–$27
reserved for OS kernel
No
$gp
$28
global pointer
Yes
$sp
$29
stack pointer
Yes
$fp
$30
frame pointer
Yes
$ra
$31
return address
N/A
Formatos de Instrucciones
MIPS
Instrucción del Tipo I addi
regs[rt] ← regs[rs] + imm
addi rt, rs, imm
31
0
8
rs
rt
Op Code
(6 bits)
fuente
(5 bits)
destino
(5 bits)
imm
inmediato
(16 bits)
Ejemplo Instrucción del Tipo I
addi
regs[1] ← regs[2] + 15
(Hardware)
001000
Op Code
00010
fuente
00001
destino
0000000000001111
inmediato
Suma el contenido del registro fuente (rs) a una constante y lo guarda
en el registro destino (rd)
Programando a Nivel de la
Máquina
Programa en MIPS 32 que calcula
la suma de los cuadrados de los
numeros de 0 a 100.
Programando en Lenguaje
Ensamblador
Da una sintaxis con mnemónicos
para las instrucciones, registros y
modos de direccionamiento.
Instrucción del Tipo I addi
regs[rt] ← regs[rs] + imm
addi rt, rs, imm
(Texto)
Ensamblado
31
(Hardware)
0
8
rs
rt
Op Code
(6 bits)
fuente
(5 bits)
destino
(5 bits)
imm
inmediato
(16 bits)
Ejemplo de addi
regs[1] ← regs[2] + 15
addi $1, $2, 15
(Texto)
Ensamblado
(Hardware)
001000
Op Code
00010
fuente
00001
destino
0000000000001111
inmediato
Instrucción del Tipo I: lw
(Texto)
Regs[rt] ← Mem[Regs[rs] + imm]
lw rt, offset(rs)
Ensamblado
31
(Hardware)
0
0x23
rs
rt
Op Code
(6 bits)
fuente
(5 bits)
destino
(5 bits)
Offset
inmediato
(16 bits)
Ejemplo de lw
(Texto)
lw $3, 33($4)
Regs[3] ← Mem[Regs[4] + 33]
Ensamblado
31
(Hardware)
0
010111
00100
00011
Op Code
(6 bits)
fuente
(5 bits)
destino
(5 bits)
0000000000100001
inmediato
(16 bits)
Instrucción del Tipo I: bne
(Texto)
if (Regs[rs] ≠ Regs[rt]) then PC ← PC+4+(Offsetx
bne rs, rt, label
else PC ← PC+4
Ensamblado
31
(Hardware)
0
5
rs
rt
Op Code
(6 bits)
fuente
(5 bits)
destino
(5 bits)
Offset
inmediato
(16 bits)
Ejemplo de bne
bne $5, $6, loop
if (Regs[5] ≠ Regs[6]) then PC ← PC+4+(-5x
Loop:
else PC ← PC+4
bne $5, $6,-16
31
0
000101
000101
000110
Op Code
(6 bits)
fuente
(5 bits)
destino
(5 bits)
1111111111111011
inmediato
(16 bits)
Instrucción del Tipo R: add
Regs[rd] ← Regs[rs] + Regs[rt]
add rd, rs, rt
(Texto)
Ensamblado
31
(Hardware)
0
0
rs
rt
rd
Op Code fuente 1 fuente 2 destino
(6 bits)
(5 bits)
(5 bits) (5 bits)
0
0x20
función
(6 bits)
Ejemplo de add:
(Texto)
Regs[rd] ← Regs[rs] + Regs[rt]
add $7, $8, $9
Ensamblado
31
(Hardware)
0
0
01000
01001
00111
Op Code fuente 1 fuente 2 destino
(6 bits)
(5 bits)
(5 bits) (5 bits)
0
0x20
función
(6 bits)
Instrucción del Tipo R: sll
(Texto)
Regs[rd] ← Regs[rt] << shamt
sll rd, rt, shamt
Ensamblado
31
(Hardware)
0
Op Code
(6 bits)
0
rt
fuente
(5 bits)
rd
shamt
0
destino
(5 bits)
despl.
(5 bits)
función
(6 bits)
Instrucción del Tipo J: j
pc ← target*
j target
(Texto)
Ensamblado
31
(Hardware)
2
Op Code
(6 bits)
0
target
destino
(26 bits)
Instrucción del Tipo J: jal
(Texto)
Regs[31] ← pc
pc ← target*
jal target
Ensamblado
31
(Hardware)
3
Op Code
(6 bits)
0
target
destino
(26 bits)
Instrucciones Aritmético Lógicas
en MIPS 32
•
•
•
•
•
•
•
•
add, addu, addi, addiu, sub
and, andi, xor, xori, nor, or, ori
clo, clz
div (cociente en lo, resto en hi), divu
mult, multu (resultado en hi lo)
mul (especifica rdest)
madd, maddu, msub, msubu (resultado en hi lo)
sll, sllv, sra, srav, srl, srlv
Instrucciones que Manipulan
Constantes y de Comparación
• lui
• slt, sltu, slti, sltiu,
Instrucciones de Branch
•
•
•
•
•
•
beq
bgez, bgezal
bgtz
blez
bltz, bltzal
bne
Instrucciones de Jump
• j, jal
• jr, jalr
Instrucciones de cargaalmacenamiento
• lb, lbu, lh, lhu, lw
• sb, sh, sw
Instrucciones de Movimiento de
Datos
•
•
•
•
mfhi, mflo
mthi, mtlo
movn
movz
Instrucciones de Llamada al
Sistema
• eret
• syscall
• break
Instrucción que no Hace Nada
• nop
Pseudoinstrucciones
(Facilidades del Assembler)
Name
instruction syntax
Real instruction
translation
meaning
Move
move $rt,$rs
addi $rt,$rs,0
R[rt]=R[rs]
Clear
clear $rt
add $rt,$zero,$zero
R[rt]=0
Load Address
la $at, LabelAddr
lui $at,
LabelAddr[31:16]; ori
$at,$at, LabelAddr[15:0]
$at = Label Address
Load Immediate
li $at, IMMED[31:0]
lui $at, IMMED[31:16];
ori $at,$at, IMMED[15:0]
$at = 32 bit Immediate
value
Branch if greater than
bgt $rs,$rt,Label
slt $at,$rt,$rs; bne
$at,$zero,Label
if(R[rs]>R[rt]) PC=Label
Branch if less than
blt $rs,$rt,Label
slt $at,$rs,$rt; bne
$at,$zero,Label
if(R[rs]<R[rt]) PC=Label
Branch if greater than or
equal
bge $rs,$rt,Label
slt $at,$rs,$rt; beq
$at,$zero,Label
if(R[rs]>=R[rt])
PC=Label
Branch if less than or
equal
ble $rs,$rt,Label
slt $at,$rt,$rs; beq
$at,$zero,Label
if(R[rs]<=R[rt])
PC=Label
Branch if greater than
unsigned
bgtu $rs,$rt,Label
if(R[rs]=>R[rt])
PC=Label
Branch if greater than
zero
bgtz $rs,$rt,Label
if(R[rs]>0) PC=Label
Multiplies and returns
only first 32 bits
mul $1, $2, $3
mult $2, $3; mflo $1
$1 = $2 * $3
Programando en Lenguaje
Ensamblador (con
abstracciones)
Agrega: directivas, labels,
pseudoinstrucciones, modos de
direccionamiento no soportados
por el procesador.
Proceso de producir un
ejecutable
Ensamblador
• Programa que traduce el código
assembly a binario.
• Genera como salida un archivo objeto.
Archivo objeto generado por un assembler en Unix
Modelo de memoria
Llamados a Funciones
Necesidad de Mayores Abstracciones:
Lenguajes de Alto Nivel
#include <stdio.h>
int main()
{
int i, sum = 0;
for(i=0;i<=100;i++)
sum = sum + i*i;
printf("La suma de 0 ... 100 es \n%10d",sum);
return 0;
}
El Compilador
Generación de un Ejecutable
Linker
• Enlaza los archivos objeto y genera el ejecutable.
• Resuelve las referencias a bibliotecas externas.
• Asigna las posiciones finales en memoria.
Construyendo una Computadora
Paso 2: Los Dispositivos de Entrada
Salida
Sistemas basados en MIPS
•
•
•
•
•
•
•
•
•
Routers
Cablemodem
ADSL
Smart Cards
Impresoras laser
Decodificadores
PlaySation 2
Robots
Celulares
Arquitectura MIPS presente en los
siguientes procesadores
• IDT RC32438; ATI Xilleon; Alchemy Au1000, 1100,
1200; Broadcom Sentry5; RMI XLR7xx, Cavium
Octeon CN30xx, CN31xx, CN36xx, CN38xx and
CN5xxx; Infineon Technologies EasyPort, Amazon,
Danube, ADM5120, WildPass, INCA-IP, INCA-IP2;
Microchip Technology PIC32; NEC EMMA and
EMMA2, NEC VR4181A, VR4121, VR4122,
VR4181A, VR5432, VR5500; Oak Technologies
Generation; PMC-Sierra RM11200; QuickLogic
QuickMIPS ESP; Toshiba Donau, Toshiba
TMPR492x, TX4925, TX9956, TX7901.
Supercomputadoras basadas
en MIPS.
Estaciónes
de Trabajo
gráficas
Servidores
1990
Supercomputadoras
1996
Evolución SGI
2005
Supercomputadoras basadas
en MIPS.
SGI Origin 2000
Supercomputadoras basadas
en MIPS. Sircortex startup
(2007)
Sircortex SC5832
CHIP (nodo): multinucleo 6 MIPS 64
Topologia Kautz graph
Controlador de memoria crossbar
interconnect DMA engine,
Gigabit Ethernet y PCI Express
en un chip que consume 10 watts
Desempeño pico de 6 Gigaflops.
Configuración tope (un solo gabinete):
972 nodos, total de 5832 nucleos
MIPS64 y 8.2 teraFLOPS de desempeño
pico.
Que Micros estamos Usando?
Todos se basan en los principios del que
acabamos de estudiar
Que Micros estamos Usando?
Múltiples Núcleos
Cada Núcleo ejecuta varias instrucciones
en un ciclo
Memorias Cache
Y a una altísima velocidad!!! (3.000
millones de ciclos por segundo)
Plataforma Intel 975
Ejemplo chipset intel 975
FIN
• El intel 4004, primer microprocesador
(1971)