La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

Lectura 7: Manejo de interrupciones y excepciones

Presentaciones similares


Presentación del tema: "Lectura 7: Manejo de interrupciones y excepciones"— Transcripción de la presentación:

1 Lectura 7: Manejo de interrupciones y excepciones
Adapted from: Mary Jane Irwin ( ) [Original from Computer Organization and Design, Patterson & Hennessy, © 2005, UCB] This set needs more work !!

2 Componentes fundamentales de un computador
Procesador Dispositivos Control Output Memoria Flujo de datos Input Métricas importantes para una sistema entrada/salida (I/O) Desempeño Compatibilidad Escalabilidad y diversidad Formalidad (protocolo) Costo, tamaño, peso

3 Dispositivos de entrada/salida
Los dispositivos de entrada son muy diversos en: Comportamiento– Entrada, salida o almacenamiento Partner – Humano o máquina Velocidad de datos– la velocidad pico a la cual los datos pueden ser transferidas entre un dispositivo E/S y la memoria principal o el procesador Dispositivo Comportamiento Partner Data rate (Mb/s) Teclado entrada Humano 0.0001 Mouse 0.0038 Impresora laser salida 3.2000 Display gráfico Red/LAN Entrada o salida maquina Disco magnético almacenamiento Rango de 8 órdenes de magnitud Here are some examples of the various I/O devices you are probably familiar with. Notice that most I/O devices that has human as their partner usually has relatively low peak data rates because human in general are slow relatively to the computer system. The exceptions are the laser printer and the graphic displays. Laser printer requires a high data rate because it takes a lot of bits to describe high resolution image you like to print by the laser writer. The graphic display requires a high data rate because all the color objects we see in the real world and take for granted are very hard to replicate on a graphic display. Data rates span eight orders of magnitude and are always quoted in base 10 so that 10 Mb/sec = 10,000,000 bits/sec

4 Comunicación de los dispositivos de E/S y el procesador
Como el procesador maneja los dispositivos de E/S Instrucciones especiales de E/S Se deben especificar el dispositivo y el comando Dispositivo de E/S mapeado por memoria Partes de las direcciones de la memoria de alto nivel están designadas para cada dispositivo de entrada/salida E/S (I/O) La lectura y escritura en dichas posiciones de memoria son interpretadas como comandos por dichos dispositivos de E/S Carga/almacenamiento en dichos espacios de memora designados a los dispositivos de E/S es solamente realizada por el Sistema Operativo (OS) Como se comunica el dispositivo de E/S con el procesador Polling – El procesador periodicamente realiza un chequeo del estatus del dispositivo de E/S para determinar su necesidad de servicio El procesador está totalmente en control- Sin embargo realiza todo el trabajo Puede gastarse innecesariamente una cantidad considerable de tiempo de procesador debido a las diferencias de velocidad. Manejo de interrupciones– El dispositivo de E/S realiza una interrupción al procesador para indicarle su necesidad de atención. If special I/O instructions are used, the OS will use the I/O instruction to specify both the device number and the command word. The processor then executes the special I/O instruction by passing the device number to the I/O device (in most cases) via a set of control lines on the bus and at the same time sends the command to the I/O device using the bus’s data lines. Special I/O instructions are not used that widely. Most processors use memory-mapped I/O where portions of the address space are assigned to the I/O device. Read and write to this special address space are interpreted by the memory controller as I/O commands and the memory controller will do right thing to communicate with the I/O device. If a polling check takes 100 cycles and the processor has a 500 MHz clock, a mouse running at 30x/s takes only % of the processor, a floppy running at 50KB/s takes only 0.5%, but a disk running at 2MB/sec takes 10%.

5 (Ejemplo) E/S en SPIM SPIM soporta un dispositivo de E/S mapeado por memoria – una terminal con dos unidades independientes El receptor lee caracteres desde el teclado El transmisor escribe caracteres en la pantalla Processor Control F. datos Memoria Dispositivos Rx Tx

6 Repaso: Configuración de memoria MIPS (spim)
Memory f f f f f f f c Mem Map I/O Kernel Code & Data $sp 7f f e f f fc Stack 230 words Dynamic data $gp ( ) Static data Note that stack grows down into dynamic data area. User Code PC Reserved

7 Control de recepción de terminal (entrada) con SPIM
La terminal de entrada es controlada por medio de dos registros de memoria mapeados para el dispositivo. (cada registro se encuentra en una ubicación de memoria especial) 7 Dato recibido (0xffff0004) unused Byte recibido (read only) 1 Control de recepción (0xffff0000) unused The interrupt enable bit is initially zero. If it is enabled, an interrupt is requested by the terminal on level zero whenever the ready bit is 1. Note that the ready bit is read only and, as we will see, it changes automatically from zero to one when a character is typed at the keyboard and from one to zero when it is read from the receiver data register interrupt enable ready (read only)

8 Control de la terminal de salida con SPIM
La terminal de salida es controlada por dos registros mapeados en la memoria (cada registro aparece en una dirección especial de memoria) 7 Dato transmitido (0xffff000c) unused Byte transmitido 1 Control de transmisión (0xffff0008) unused Habilitación de interrupción ready (read only)

9 Interrupciones de E/S Una interrupción de E/S es usada como señal de petición de servicio Puede tener diferentes niveles de urgencia (debido a que su atención podría ser prioritaria) Necesita de alguna manera trasladar la identidad del dispositivo que genera la interrupción. Una interrupción de E/S es una ejecución de una instrucción de escritura asincrona Una interrupción de E/S no está asociada con ninguna instrucción y no provoca que ninguna instrucción deje de completarse Se puede elegir un punto de conveniencia para ejecutar la interrupción Ventaja El progreso de la ejecución del programa del usuario es solamente parada (halted) durante la transferencia de datos de E/S desde/hacia el usuario desde el espacio en memoria Desventaja – hardware especial es necesario para Causar la interrupción (Dispositivo de E/S) Detectar una interrupción y salvar la información adecuada para poder reanudar el programa después de haber servido la interrupción (procesador) An I/O interrupt is asynchronous with respect to the instruction execution while exception such as overflow or page fault are always associated with a certain instruction. Also for exception, the only information needs to be conveyed is the fact that an exceptional condition has occurred but for interrupt, there is more information to be conveyed. Let me elaborate on each of these two points. Unlike exception, which is always associated with an instruction, interrupt is not associated with any instruction. The user program is just doing its things when an I/O interrupt occurs. So I/O interrupt does not prevent any instruction from completing so you can pick your own convenient point to take the interrupt. As far as conveying more information is concerned, the interrupt detection hardware must somehow let the OS know who is causing the interrupt. Furthermore, interrupt requests needs to be prioritized.

10 Manejo de interrupción para entrada
1. input interrupt Procesador add sub and or beq user program Memoria Receptor Teclado lbu sb ... jr input interrupt service routine : For class handout memory

11 Manejo de interrupción para entrada
1. Interrupción entrada Procesador add sub and or beq lbu sb ... jr 2.4 retorno al programa original user program 2.1 salvar PC 2.2 salto a la rutina de servicio de la interrupción Memoria Receptor 2.3 servicio de interrupción Teclado Rutina de servicio de interrupción de entrada For lecture That is, whenever an I/O device needs attention from the processor, it interrupts the processor from what it is currently doing. This is how an I/O interrupt looks in the overall scheme of things. The processor is minding its business when one of the I/O device wants its attention and causes an I/O interrupt. The processor then save the current PC, branch to the address where the interrupt service routine resides, and start executing the interrupt service routine. When it finishes executing the interrupt service routine, it branches back to the point of the original program where we stop and continue. The advantage of this approach is efficiency. The user program’s progress is halted only during actual transfer. The disadvantage is that it require special hardware in the I/O device to generate the interrupt. And on the processor side, we need special hardware to detect the interrupt and then to save the proper states so we can resume after the interrupt. +2 = 62 min. (Y:42) memoria

12 Manejo de interrupción para entrada en SPIM
El receptor indica con una interrupción que hay una entrada de un nuevo caracter desde el teclado en el registro de recepción de datos La escritura en el registro de recepción de datos (Receiver data register) cambia el estado del “ready bit” de dicho registro a 1 El programa en ejecución responde a la interrupción tranfiriendo el control a la rutina de servicio de la interrupción que copia el caracter de entrada en la espacio de memoria del usuario La lectura del registro de recepción de datos hace “reset” del “ready bit” del registro de control de datos (cambia su valor de nuevo a 0 ) received byte Receiver data (0xffff0004) unused 65 Receiver control (0xffff0000) unused 1 1 0 interrupt enable ready That is, whenever an I/O device needs attention from the processor, it interrupts the processor from what it is currently doing. This is how an I/O interrupt looks in the overall scheme of things. The processor is minding its business when one of the I/O device wants its attention and causes an I/O interrupt. The processor then save the current PC, branch to the address where the interrupt service routine resides, and start executing the interrupt service routine. When it finishes executing the interrupt service routine, it branches back to the point of the original program where we stop and continue. The advantage of this approach is efficiency. The user program’s progress is halted only during actual transfer. The disadvantage is that it require special hardware in the I/O device to generate the interrupt. And on the processor side, we need special hardware to detect the interrupt and then to save the proper states so we can resume after the interrupt.

13 Manejo de la interrupción para salida
1.Interrupción de salida add sub and or beq Programa en ejecución Procesador Memoria Transmisor lbu sb ... jr Rutina de servicio Para la atención de la interrupción de salida Pantalla For class handout memoria

14 Interrupt Driven Output
1.Interrupción de salida add sub and or beq Programa original Procesador 2.1 salvar PC 2.4 retorno al programa original 2.2 salto a rutina de servicio de interrupción 2.3 servicio de interrupcion Memoria Trnsmttr lbu sb ... jr Rutina de servicio de interrupción de salida Pantalla For lecture memoria

15 Manejo de interrupción para salida en SPIM
El transmisor indica con una interrupción que ha sido de manera exitosa mostrado el caracter en el registro de transmisión de datos (Transmiter data register) en la pantalla (display) La lectura del “Transmitter data register” cambia el valor del “ready bit” de dicho registro a 1 El programa del usuario responde a dicha interrupción tranfiriendo control a la rutina de servicio de la interrupción que escribe el siguiente caracter al la salida desde el espacio de memoria del usuar2io al registro de transmisión de datos La escritura al “Transmitter data register” hace “reset” del “ready bit” de dicho registro a 0 transmitted byte Transmitter data (0xffff000c) unused 65 Transmitter control (0xffff0008) unused 1 1 0 interrupt enable ready

16 Excepciones en General
Manejo de excepción del sistema user program Excepción normal control flow: sequential, jumps, branches, calls, returns Retorno Desde excepción Excepción = transferencias de control no programadas El sistema entra en acción para manajar la excepción Debe guardar la dirección la intrucción interrumpida o la próxima por ejecutar y salvar (y reestablecer) el estado de usuario Retorna el control al programa en ejecución después del manejo de la excepción

17 Dos tipos de excepciones
Interrupciones Causadas por eventos externos (tales como peticiones de dispositivos de E/S) Ejecución de programa asíncrona Pueden ser manejadas entre las instrucciones Simplemente suspenden y restablecen el programa en ejecución (user program) Trampas (Traps) (Excepciones) Causadas por eventos internos Condiciones de excepción (e.g., sobreflujo (overflow) aritmético, instrucción indefinida.) errores (e.g., fallo de hardware, error de paridad de memoria) fallos (e.g., non-resident page – page fault) Sincrónicas respecto a la ejecución del programa La condición debe ser remediada por el manejador de traps La instrucción debe ser reintentada (o simulada) y el programa continuar o ser abortado

18 Adiciones al set de instrucciones MIPS para el manejo de excepciones
El coprocesador 0 almacena la información que el software necesita para manejar las excepciones EPC (registro 14) – mantiene el valor de la dirección+4 de la instrucción que fue ejecutada cuando la excepción ocurrió Status (registro 12) – mascara de trampa/interrupción y bits de habilitación (enable) Intr Mask = 1 bit por cada uno de los 6 niveles de excepciones de hardware y los 2 niveles de exepciones de nivel de software for each of 6 hardware and (1 activa excepciones en ese nivel) User mode = 0 si está corriendo en “kernel mode” cuando la excepción occurre; 1 si se está corriendo en modo usuario (fijo en 1 en SPIM) Excp level = normalmente 1 (excepciones desabilitadas) después de que una excepción occurre; debe ser “reseteado” por el manejo de la excepción (exception handler) cuando finaliza Intr enable = 1 si las excepciones están habilitadas; 0 si están desabilitadas 15 8 4 1 Intr Mask User mode Intr enable Excp level

19 Addiciones al ISA de MIPS, Con’t
BadVAddr (registro 8) – dir de memoria cuando la referencia pasó Cause (registro 13) – tipo de excepción y “pending bits” Pending: bit activados si la excepción ocurrie pero no ha sido servida todavía Maneja casos donde más de una excepción occurre al mismo tiempo, o graba peticiones de excepción cuando las excepciones están desabilitadas Codificación de excepciones: codígos para causas de excepción 0 (INT)  Interrupción externa (petición de dispositivo de E/S) 4 (AdEL)  trampa (trap) para error de direccionamiento (load o instr fetch) 5 (AdES)  trampa para error de direccionamiento (store) 6 (IBE)  error de bus o fetch de instrucción 7 (DBE)  error de bus en obtención (load) o almacenamiento (store) de datos 8 (Sys)  trampa de llamada de sistema (syscall) 9 (Bp)  trampa de punto de quiebre (breakpoint) 10 (RI)  intrucción de trampa reservada (o indefina) 12 (Ov)  trampa para sobreflujo aritmético (overflow) 15 8 Pending 6 2 Code

20 Adiciones al ISA de MIPS ISA para interrupciones de E/S
Las señales de control escriben el EPC (EPCWrite), causa (CauseWrite), y estatus El Hardware almacena el tipo de interrupción en “Cause” Se modifica la máquina de estados finita para que: La dirección del “interrupt handler” ( hex) pueda ser almacenada en el registro PC, por lo que debe ser incrementado el tamaño del multiplexor PC (PC mux) Y salvar la dirección de la próxima instrucción en EPC

21 Flujo de datos multiciclo modificado para interrupciones
Interrupt EPCWrite PCWriteCond CauseWrite PCWrite PCSource IorD ALUOp MemRead Control ALUSrcB MemWrite ALUSrcA EPC MemtoReg RegWrite IRWrite RegDst Cause PC[31-28] Instr[31-26] Shift left 2 3 Instr[25-0] 2 1 Address Memory PC Read Addr 1 A IR Read Data 1 Register File 1 1 zero Read Addr 2 Read Data (Instr. or Data) ALUout ALU Write Addr For class handout Write Data 1 Read Data 2 B MDR 1 Write Data 4 1 2 Instr[15-0] Sign Extend Shift left 2 3 32 ALU control Instr[5-0]

22 Flujo de datos multiciclo modificado para interrupciones
Interrupt EPCWrite PCWriteCond CauseWrite PCWrite PCSource IorD ALUOp MemRead Control ALUSrcB MemWrite ALUSrcA EPC MemtoReg RegWrite IRWrite RegDst Cause PC[31-28] Instr[31-26] Shift left 2 3 Instr[25-0] 2 1 Address Memory PC Read Addr 1 A IR Read Data 1 Register File 1 1 zero Read Addr 2 Read Data (Instr. or Data) ALUout ALU Write Addr For lecture Write Data 1 Read Data 2 B MDR 1 Write Data 4 1 2 Instr[15-0] Sign Extend Shift left 2 3 32 ALU control Instr[5-0]

23 Maquina de estados modificada para interr.
Decode IorD = 0 MemRead;IRWrite ALUSrcA = 0 ALUsrcB = 01 ALUOp = 00 PCSource = 00 PCWrite Instr Fetch 1 ALUSrcA = 0 ALUSrcB = 11 ALUOp = 00 Start (Op = R-type) (Op = beq) 2 (Op = lw or sw) (Op = j) 6 8 9 ALUSrcA = 1 ALUSrcB = 00 ALUOp = 01 PCSource = 01 PCWriteCond ALUSrcA = 1 ALUSrcB = 10 ALUOp = 00 ALUSrcA = 1 ALUSrcB = 00 ALUOp = 10 PCSource = 10 PCWrite Execute (Op = lw) (Op = sw) 3 5 7 Memory Access RegDst = 1 RegWrite MemtoReg = 0 MemWrite IorD = 1 MemRead IorD = 1 For class handout 4 RegDst = 0 RegWrite MemtoReg = 1 Write Back

24 Maquina de estados modificada para interr.
Decode IorD = 0 MemRead;IRWrite ALUSrcA = 0 ALUsrcB = 01 ALUOp = 00 PCSource = 00 PCWrite Instr Fetch 1 ALUSrcA = 0 ALUSrcB = 11 ALUOp = 00 Start (Op = R-type) (Op = beq) 2 (Op = lw or sw) (Op = j) 6 8 9 ALUSrcA = 1 ALUSrcB = 00 ALUOp = 01 PCSource = 01 PCWriteCond ALUSrcA = 1 ALUSrcB = 10 ALUOp = 00 ALUSrcA = 1 ALUSrcB = 00 ALUOp = 10 PCSource = 10 PCWrite Execute (Op = lw) (Op = sw) 3 5 7 Memory Access RegDst = 1 RegWrite MemtoReg = 0 MemWrite IorD = 1 MemRead IorD = 1 For lecture 11 Interrupt pending? CauseWrite EPCWrite;PCWrite IntrOrExcp = 0 PCSource = 11 4 RegDst = 0 RegWrite MemtoReg = 1 Write Back

25 Ejemplo de una rutina de servicio de interrupción para E/S
.ktext 0x sw $t0, save0 #save working reg’s . . . mfc0 $k0, $13 #move Cause into $k0 mfc0 $k1, $14 #move EPC into $k1 sgt $t0, $k0, 0x00 #is it an interrupt? bgtz $t0, excpt intrpt: li $t0, 0xffff0000 lw $t1, 0($t0) #test Receiver control beq $t1, $0, tstout # for input ready inpt: lb $v0, 4($t0) #input char. into $v0 tstout: lw $t1, 8($t0) #test Trans. control beq $t1, $0, excpt # for output ready sb $v1, c($t0) #output char. from $v1 j done # excpt: #code to handle excpts addiu $k1, $k1, 4 #do not re-execute # faulting instr done: lw $t0, save0 #restore working reg’s eret #return to user code .kdata save0: .word 0 Assumes the input character should be returned to the code in $v0 and that the output character is in $v1 The interrupt handler cannot save the registers on the stack, as would an ordinary routine, because the cause of the interrupt might have been a memory reference that used a bad value (such as 0) in the stack pointer. Instead, the interrupt handler stores the registers in memory locations. If the interrupt routine itself could be interrupted, two locations would not be enough since the second interrupt would overwrite values saved during the first interrupt. Notice that interrupts are disabled coming into the interrupt handler through the k/e bit shifting in the status register (moving to kernel mode with interrupts disabled). And that this code finishes running before reenabling interrupts (rfe) that shifts the k/e bits back restoring the “prev” state to the “current” state (back to user mode with interrupts enabled).

26 Adiciones al ISA de MIPS para trampas
Instrucciones especiales para manejo de trampas lwc0 y swc0 – para obtener (guardar) un word del espacio de memoria en un registro del coprocesador 0 mfc0 and mtc0 – para mover desde (hacia) un registro del coprocesador 0 hacia (desde) un registro del procesador eret – retorno desde excepción (return from exception) (limpia el bit EXC del “Status register” y produce un salto a la instrucción a la que apunta EPC) Las señales de control escriben en EPC (EPCWrite & IntrOrExcp), Cause (CauseWrite), Status, & BadVAddr Hardware almacena el tipo de trampa en “Cause” Modificación adicional a la máquina de estados finita de tal manera que: Para las trampas, se almacena la dirección de la instrucción actual en el EPC, por lo que se debe deshacer el PC = PC + 4 hecho en el proceso de fetch 15 8 4 1 Intr Mask Intr enable User mode Excp level

27 Flujo de datos multiciclo modificado para trampas
Interrupt EPCWrite PCWriteCond IntrOrExcp CauseWrite PCWrite PCSource IorD ALUOp MemRead Control ALUSrcB MemWrite ALUSrcA EPC MemtoReg RegWrite IRWrite RegDst Cause PC[31-28] Instr[31-26] Shift left 2 3 Instr[25-0] 2 1 Address Memory PC Read Addr 1 A IR Read Data 1 Register File 1 1 zero Read Addr 2 Read Data (Instr. or Data) ALUout ALU Write Addr For class handout Write Data 1 Read Data 2 B MDR 1 Write Data 4 1 2 Instr[15-0] Sign Extend Shift left 2 3 32 ALU control Instr[5-0]

28 Flujo de datos multiciclomodificado para trampas
Interrupt EPCWrite PCWriteCond IntrOrExcp CauseWrite PCWrite PCSource IorD ALUOp MemRead Control ALUSrcB MemWrite ALUSrcA EPC MemtoReg RegWrite 1 IRWrite RegDst Cause PC[31-28] Instr[31-26] Shift left 2 3 Instr[25-0] 2 1 Address Memory PC Read Addr 1 A IR Read Data 1 Register File 1 1 zero Read Addr 2 Read Data (Instr. or Data) ALUout ALU Write Addr For lecture Write Data 1 Read Data 2 B MDR 1 Write Data 4 1 2 01 Instr[15-0] Sign Extend Shift left 2 3 32 ALU control Instr[5-0]

29 Como el control detecta dos trampas
Instrucción indefinida (Undefined instruction) (RI) – detecta cuando no hay un nuevo estado definido a partir del estado 1 del valor del código de operación Define el nuevo valor de estado para todo los valores de operacion diferentes a lw, sw, R-type, jmp, and beq como el nuevo estado 10 Sobreflujo aritmético (overflow) (OVF) – La señal de “overflow” de la ALU es usada en el estado 6 (si no se quiere completar el RegWrite) o en el estado 7 para especificar el proximo correcto nuevo estado Se necesita modificar la máquina de estados de una manera similar para las trampas restantes El desafio consiste en el manejo de las interacciones entre las intrusciones y los eventos que causan excepciones para que la lógica de control se mantenga relativamente pequeña y rápida Interacciones de nivel complejo son el aspecto más desafiante del diseño de hardware, especialmente para procesadores “pipelined”

30 Modificación de máquina de estados (trampas)
Decode IorD = 0 MemRead;IRWrite ALUSrcA = 0 ALUsrcB = 01 ALUOp = 00 PCSource = 00 PCWrite Instr Fetch 1 ALUSrcA = 0 ALUSrcB = 11 ALUOp = 00 Start (Op = R-type) (Op = beq) (Op = other) 2 (Op = lw or sw) (Op = j) 6 8 9 ALUSrcA = 1 ALUSrcB = 00 ALUOp = 01 PCSource = 01 PCWriteCond ALUSrcA = 1 ALUSrcB = 10 ALUOp = 00 ALUSrcA = 1 ALUSrcB = 00 ALUOp = 10 PCSource = 10 PCWrite Execute (Op = lw) (Op = sw) 3 5 7 Memory Access RegDst = 1 RegWrite MemtoReg = 0 MemWrite IorD = 1 MemRead IorD = 1 Overflow For class handout 11 Interrupt pending? CauseWrite EPCWrite;PCWrite IntrOrExcp = 0 PCSource = 11 4 No Overflow RegDst = 0 RegWrite MemtoReg = 1 Write Back

31 Modificación de máquina de estados (trampas)
Decode IorD = 0 MemRead;IRWrite ALUSrcA = 0 ALUsrcB = 01 ALUOp = 00 PCSource = 00 PCWrite Instr Fetch 1 ALUSrcA = 0 ALUSrcB = 11 ALUOp = 00 Start (Op = R-type) (Op = beq) (Op = other) 2 (Op = lw or sw) (Op = j) 6 8 9 ALUSrcA = 1 ALUSrcB = 00 ALUOp = 01 PCSource = 01 PCWriteCond ALUSrcA = 1 ALUSrcB = 10 ALUOp = 00 ALUSrcA = 1 ALUSrcB = 00 ALUOp = 10 PCSource = 10 PCWrite Execute (Op = lw) (Op = sw) 3 5 7 Memory Access 10 CauseWrite ALUSrcA =0 ALUSrcB = 01 ALUOp = 01 EPCWrite;PCWrite IntrOrExcp = 1 PCSource = 11 RegDst = 1 RegWrite MemtoReg = 0 MemWrite IorD = 1 MemRead IorD = 1 Overflow For lecture 11 Interrupt pending? CauseWrite EPCWrite;PCWrite IntrOrExcp = 0 PCSource = 11 4 No Overflow RegDst = 0 RegWrite MemtoReg = 1 Write Back

32 Ejemplo de rutina de servicio de trampa
.kdata s1: .word 0 s2: .word 0 .ktext 0x move $k1, $at # Save $at sw $v0, s1 # Not re-entrant and we can't trust $sp sw $a0, s2 mfc0 $k0, $13 # Save Cause sgt $v0, $k0, 0x00 # ignore interrupt exceptions bgtz $v0, ret addu $0, $0, 0 li $v0, 4 # syscall 4 (print_str) la $a0 __m1_ syscall li $v0, 1 # syscall 1 (print_int) srl $a0, $k0, 2 # shift Cause reg lw $a0, __excp($k0) bne $k0, 0x18, ok_pc # Bad PC requires special checks . . . ok_pc:li $v0, 4 # syscall 4 (print_str) la $a0, __m2_ mtc0 $0, $13 # Clear Cause register ret:lw $v0, s1 lw $a0, s2 move $at, $k1 # Restore $at mfc0 $k0, $14 # read EPC addiu $k0, $k0, 4 # EPC = EPC +4 mtc0 $k0, $14 # to return to next instruction eret # Return from exception handler The interrupt handler cannot save the registers on the stack, as would an ordinary routine, because the cause of the interrupt might have been a memory reference that used a bad value (such as 0) in the stack pointer. Instead, the interrupt handler stores the registers in memory locations. If the interrupt routine itself could be interrupted, two locations would not be enough since the second interrupt would overwrite values saved during the first interrupt. Notice that interrupts are disabled coming into the interrupt handler through the k/e bit shifting in the status register (moving to kernel mode with interrupts disabled). And that this code finishes running before reenabling interrupts (rfe) that shifts the k/e bits back restoring the “prev” state to the “current” state (back to user mode with interrupts enabled).

33 Problemas de interconectividad para sistemas de E/S
Procesador Señales de interrupción Memoria cache bus Memory - I/O Bus I/O Controller I/O Controller I/O Controller Main Memory Terminal Disk Disk Network This is a more in-depth picture of the I/O system of a typical computer. The I/O devices are shown here to be connected to the computer via I/O controllers that sit on the Memory I/O busses. We will talk about buses on Friday. For now, notice that I/O system is inherently more irregular than the Processor and the Memory system because all the different devices (disk, graphics) that can attach to it. So when one designs an I/O system, performance is still an important consideration. But besides raw performance, one also has to think about expandability and resilience in the face of failure. For example, one has to ask questions such as: (a)[Expandability]: is there any easy way to connect another disk to the system? (b) And if this I/O controller (network) fails, is it going to affect the rest of the network? Usualmente existe más de un dispositivo de E/S en el sistema conectado al procesador via un bus Cada dispositivo de E/S es controlado por un controlador de E/S (I/O Controller)

34 Buses Un bus es un canal de comunicación compartido (un único conjunto de cables usado para conectar multiples subsistemas) que necesita soportar un rango de dispositivos con latencias y velocidades de tranferencias de magnitud altamente variable Ventajas Versatil – nuevos dispositivos pueden ser facilmente añadidos y movidos entre sistemas computacionales que utilizar en mismo estándar de bus Bajo costo – un único conjunto de cables compartido en multiples vías Desventajas Crea un cuello de botella en las comunicaciones– el ancho de banda del bus limita la máxima capacidad de tramisión de E/S (throughput) La velocidad máxima del bus es altamente limitada por La longitud del bus El numero de dispositivos en dicho bus The two major advantages of the bus organization are versatility and low cost. By versatility, we mean new devices can easily be added. Furthermore, if a device is designed according to a industry bus standard, it can be move between computer systems that use the same bus standard. The bus organization is a low cost solution because a single set of wires is shared in multiple ways. The major disadvantage of the bus organization is that it creates a communication bottleneck. When I/O must pass through a single bus, the bandwidth of that bus can limit the maximum I/O throughput. The maximum bus speed is also largely limited by: (a) The length of the bus. (b) The number of I/O devices on the bus. (C) And the need to support a wide range of devices with a widely varying latencies and data transfer rates.

35 Mediciones del desempeño de E/S
Ancho de banda de E/S (throughput) – magnitud de la imformación que puede ser puesta en la entrada (o salida) y comunicada a través de una interconexión (tal como un bus) al procesador/memoria (dispositivo de E/S) por unidad de tiempo ¿Que tanta información se puede mover a través del sistema en un cierto tiempo? ¿Cuantas operaciones de E/S se pueden realizar por unidad de tiempo? Tiempo de respuesta para E/S (latencia) – el tiempo total que toma completar una operación de entrada o salida Es una métrica de desempeño especialmente importante en sistemas en tiempo real Muchas aplicaciones requieren ambos: alto ancho de banda y pequeños tiempos de respuesta

36 Tipos de Buses Bus entre el procesador y la memora (propietario)
Corto y de alta velocidad Ajustado al sistema de memoria para maximizar el ancho de banda entre el procesador y la memoria Optimizado para transferencias de blocks en cache Bus de E/S (estandar industrial, ej., SCSI, USB, Firewire) Usualmente es largo y más lento Necesita ajustarse a un rango muy alto de dispositivos de E/S Se conecta al bus entre el procesador y la memoria o al “backplane bus” Backplane bus (industry standard, e.g., ATA, PCIexpress) El “backplane” es una estructura interconectada a lo interno del chasis Es usado como un bus intermediario para la conección de buses de E/S al bus entre el procesador y la memoria Buses are traditionally classified as one of 3 types: processor memory buses, I/O buses, or backplane buses. The processor memory bus is usually design specific while the I/O and backplane buses are often standard buses. In general processor bus are short and high speed. It tries to match the memory system in order to maximize the memory-to-processor BW and is connected directly to the processor. I/O bus usually is lengthy and slow because it has to match a wide range of I/O devices and it usually connects to the processor-memory bus or backplane bus. Backplane bus receives its name because it was often built into the backplane of the computer--it is an interconnection structure within the chassis. It is designed to allow processors, memory, and I/O devices to coexist on a single bus so it has the cost advantage of having only one single bus for all components. +2 = 16 min. (X:56)

37 Ejemplo: Los buses del Pentium 4
System Bus (“Front Side Bus”): 64b x 800 MHz (6.4GB/s), 533 MHz, or 400 MHz Memory Controller Hub (“Northbridge”) Graphics output: 2.0 GB/s DDR SDRAM Main Memory Gbit ethernet: GB/s Hub Bus: 8b x 266 MHz 2 serial ATAs: 150 MB/s PCI: b x 33 MHz The northbridge chip is basically a DMA controller (to the memory, the graphical output device (monitor) and the southbridge chip). The southbridge connects the northbridge to a cornucopia of I/O buses I/O Controller Hub (“Southbridge”) 2 parallel ATA: 100 MB/s 8 USBs: 60 MB/s

38 El ancho de banda del Bus determina
El ancho de banda del bus está determinado por: El hecho de si el mismo es síncrono o asíncrono y las características de temporización del protocolo utilizado El ancho del bus (el número de líneas de datos) El hecho de que el bus soporte transferencias de bloques de datos o solamente una palabra (word) por vez Firewire USB 2.0 Tipo I/O Lineas de datos 4 2 Clocking Asynchronous Synchronous Max # devices 63 127 Máximo largo 4.5 meters 5 meters Ancho de banda pico 50 MB/s (400 Mbps) 100 MB/s (800 Mbps) 0.2 MB/s (low) MB/s (full) MB/s (high)

39 Transición en la tecnología de los buses
Existe una transición de las compañias desde los buses sincronos, paralelos y anchos, a buses asíncronos y angostos Interferencia electromagnética de los cables y variaciones en la temporización dificultan el uso de 16 a 64 cables en paralelo a altas frecuencias de reloj (ej., ~400 MHz) por lo que las compañias están en transición hacia buses con pocos cables de una via corriendo a altas tasas de tranferencia de reloj (~2 GHz) PCI PCIexpress ATA Serial ATA Total # wires 120 36 80 7 # data wires 32 – (2-way) 2 x (1-way) (2-way) 2 x (1-way) Clock (MHz) 33 – 133 635 50 150 Peak BW (MB/s) 128 – 1064 300 100 375 (3 Gbps) PCIexpress is the serial successor to the parallel PCI bus (32 to 64 wires running at 33 MHz to 133 MHz with a peak bandwidth of 132 to 1064 MB/s). PCIexpress uses just 4 wires in each direction operating at 625 MHz to provide a peak bandwidth of 300 MB/s per direction.

40 ATA Cable Sizes Serial ATA cables (red) are much thinner than parallel ATA cables (green)


Descargar ppt "Lectura 7: Manejo de interrupciones y excepciones"

Presentaciones similares


Anuncios Google