Baixe o app para aproveitar ainda mais
Prévia do material em texto
1 5-1.1INE5355 – Sistemas Operacionais I Capítulo 5: Sistemas de E/S � Parte 1 • Hardware de E/S • Software de E/S • Níveis de software de E/S � Parte 2 • Disco 5-1.2INE5355 – Sistemas Operacionais I Hardware de E/S � Princípios do Hardware de E/S • Chips, ligações elétricas, componentes físicos do hardware • Interface de software, comandos aceitos, funções e erros � Dispositivos de E/S • Dispositivos de bloco • armazena informação em blocos de tamanho fixo, com endereço (exemplo: disco) • Dispositivo de caractere • envia ou recebe fluxo de caracteres sem considerar qualquer estrutura de blocos (exemplo: impressoras, interface de rede, mouse) • Outros dispositivos: relógio 2 5-1.3INE5355 – Sistemas Operacionais I Figure 3.1. Device-handling subsystem overview 5-1.4INE5355 – Sistemas Operacionais I Hardware de E/S Alguns dispositivos típicos e suas taxas de dados -1963 80MB 50/100Kb/s -1986 765MB 2Mb/s -1992 2GB 10Mb/s (3,75) - 1997 29.3GB 20/40Mb/s (0,25) - 2002 80GB 100MB/s (1,5) 3 5-1.5INE5355 – Sistemas Operacionais I Figure 3.2. Hardware–software interface. 5-1.6INE5355 – Sistemas Operacionais I Controladores de Dispositivos � Dispositivos de E/S tem componentes: • mecânico • eletrônico � O componente eletrônico é o controlador do dispositivo • Placa controladora circuito impresso, conector para o dispositivo • Pode tratar com múltiplos dispositivos � Interface entre controlador e dispositivo • Padrão oficial (ANSI,IEEE,ISO), padrão de fato • Interface de nível baixo: unidade de disco entrega fluxo serial de bits (preâmbulo+4096bits(setor)+checksum-ECC) � Tarefas do Controlador • converter um “stream” serial de bits em blocos de bytes • realizar correção de erros se necessário • tornar dados disponíveis para memória principal • SO inicia o controlador com parâmetros 4 5-1.7INE5355 – Sistemas Operacionais I Barramento PC 5-1.8INE5355 – Sistemas Operacionais I Figure 3.3. A simple device interface with (a) interrupts disabled and (b) interrupts enabled. 5 5-1.9INE5355 – Sistemas Operacionais I Hardware E/S: comunicação c/ dispositivos � E/S mapeada em memória • Cada controlador tem registradores para comunicação com CPU • O SO comanda dispositivos através da escrita destes – entregar ou receber dados, ligar, desligar executar tarefa • O SO verifica o estado dos dispositivos através da leitura destes • Dispositivos também tem buffer de dados, SO pode ler ou escrever Questão: como a CPU se comunica com os registradores dos controladores e com os buffers de dados dos dispositivos? 5-1.10INE5355 – Sistemas Operacionais I Hardware E/S: comunicação c/dispositivos � Porta de E/S (IBM360) • Registrador associado a porta (inteiro 8,16 bits) • IN reg,porta ; OUT porta,reg • Espaços de endereçamento diferentes (figura) • Instruções IN r0,4 e MOV r0,4 � E/S Mapeada na memória (PDP11) • Mapear registradores no espaço de endereçamento da memória • Cada registrador é associado a endereço de memória único � Esquema híbrido(Pentium) • Portas de E/S de 0 a 64K e endereços 640K a 1M buffers (dispositivos PC) • CPU coloca endereço nas linhas de endereço do barramento e emite READ • Segunda linha de sinal indica se E/S ou memória 6 5-1.11INE5355 – Sistemas Operacionais I E/S Mapeada na memória (1) a) Espaço de E/S e memória separados b) E/S Mapeada na memória c) Híbrido 5-1.12INE5355 – Sistemas Operacionais I E/S Mapeada na memória � Vantagens da E/S mapeada � Não precisa instruções especiais (código específico) para ler/escrever nos registradores � Sem necessidade de mecanismo especial de proteção, não mapear EE dos registradores no EEV do usuário. � Registradores de controle são variáveis na memória, ou seja, Driver pode ser escrito totalmente em C � Instruções de referencia a memória referenciam registradores � Loop: TEST PORT_4 BEQ READY BRANCH LOOP READY: � Desvantagens � Um espaço de endereçamento para todos, módulos de memória e dispositivos devem examinar referencias – responder � Barramento de memória de alta velocidade, dispositivos de E/S não conseguem examinar 7 5-1.13INE5355 – Sistemas Operacionais I E/S Mapeada em Memoria (a) Arquitetura unico barramento (b) Arquitetura barramento duplo 5-1.14INE5355 – Sistemas Operacionais I Polling e Interrupções 8 5-1.15INE5355 – Sistemas Operacionais I Figure 3.3. A simple device interface with (a) interrupts disabled and (b) interrupts enabled. 5-1.16INE5355 – Sistemas Operacionais I Ciclo de E/S com Interrupções Dispositivo gera interrupção, controlador de interrupção executa ação adequada e coloca número nas linhas de endereço (índice do vetor de interrupções). Tratador de interrupção executa, confirma a interrupção. 9 5-1.17INE5355 – Sistemas Operacionais I Figure 3.5. The interrupt mechanism. (a) Before the interrupt is taken. (b) After the interrupt is taken. 5-1.18INE5355 – Sistemas Operacionais I Figure 3.6. Device interrupt handling and interrupt vectors. 10 5-1.19INE5355 – Sistemas Operacionais I Figure 3.10. An example showing nested interrupts. 5-1.20INE5355 – Sistemas Operacionais I Figure 3.8. Direct memory access. 11 5-1.21INE5355 – Sistemas Operacionais I Ciclo de E/S com transferência por DMA O processador precisa endereçar os controladores dos dispositivos para trocar dados com eles, por exemplo, requisitar dados um byte a cada vez. Ex: leitura de disco 5-1.22INE5355 – Sistemas Operacionais I Princípios de Software de E/S Metas do Software de E/S (1) Vamos ver os objetivos do software de E/S e como a E/S pode ser feita do ponto de vista do SO � Independência do dispositivo • programas podem acessar qualquer dispositivo de E/S • Sem especificar o dispositivo antecipadamente : sort <input>output · (floppy, hard drive, or CD-ROM) � Nomeação uniforme • nome de um arquivo ou dispositivo: string de caracteres ou numero inteiro independente do dispositivo • não dependente de qual máquina � Tratamento de Erro • Tratar o mais proximo do hardware possível, apenas se não for possível tratar informar camadas superiores 12 5-1.23INE5355 – Sistemas Operacionais I Metas do Software de E/S (2) � Transferência síncrona vs. assíncrona • Transferência bloqueante vs. orientada p/interrupção � Utilização de buffer • Dados vindos de um dispositivo não podem ser armazenados diretamente em seu destino final (Ex. Pacote na rede) � Dispositivos dedicados vs. compartilhados • discos são compartilhados • Fitas não deveriam ser (deadlock) 5-1.24INE5355 – Sistemas Operacionais I Formas de realizar E/S � E/S Programada • Processo fica esperando (busy-waiting) pelo término da operação � E/S dirigida por Interrupção • Comando de E/S é emitido • Processador continua executando • Modulo de E/S envia interrupção quando termina � E/S usando DMA • Driver de E/S programa controlador DMA • Processador não participa da transferência 13 5-1.25INE5355 – Sistemas Operacionais I E/S Programada (1) Passos na impressão de um string Monta buffer, SO copia buffer, imprime caracter 1 a 1 5-1.26INE5355 – Sistemas Operacionais I E/S Programada (2) Dados são copiados para o núcleo, SO entra em laço de envio dos caracteres. A cada saída o processador fica verificando se o dispositivo esta pronto para o próximo. 14 5-1.27INE5355 – Sistemas Operacionais I E/S dirigida por Interrupção � Se impressora leva 10ms/c, processador pode chavear contexto • Código executado quando função de impressão e chamada • Rotina de tratamento da interrupção 5-1.28INE5355 – Sistemas Operacionais I E/S usando DMA � A impressão de cada caracter causa uma interrupção, alternativa DMA • codigo executado na chamada • Rotina de atendimento da interrupção 15 5-1.29INE5355 – Sistemas Operacionais I Níveis de software de E/S Camadas de Software do Sistema de E/S 5-1.30INE5355 – Sistemas Operacionais I Tratadores de Interrupção (1) � Tratadores de interrupção são partedo SO, usualmente bem escondidos • Tendo o driver iniciado uma operação de E/S o mesmo é bloqueado até que a operação se complete e uma interrupção ocorra • Operações sobre semáforos, receive mensagem � Ocorrendo a Interrupção a rotina de interrupção faz sua tarefa • Em seguida libera o driver que iniciou a operação de E/S • Processar uma interrupção não é apenas interceptar uma interrupção, sinalizar o driver e executar um IRET • Existe trabalho adicional realizado pelo SO 16 5-1.31INE5355 – Sistemas Operacionais I Tratadores de Interrupção (2) � Passos que devem ser realizados em software depois da interrupção ser completada 1. Salvar regs ainda não salvos por hardware 2. Inicializar contexto para rotina de interrupção(TLB, MMU, tab. páginas) 3. Inicializar pilha para rotina de interrupção 4. Atender controlador de interrupções, reabilitar interrupções 5. Copiar registradores de onde foram salvos (pilha) para tabela de processos 6. Executa rotina de tratamento, extrai informações dos registradores do controlador do dispositivo que está interrompendo 7. Escolhe próximo processo a executar. 8. Estabelece contexto MMU para próximo processo 9. Carrega registradores do próximo processo (PSW) 10. Inicia execução do processo 5-1.32INE5355 – Sistemas Operacionais I � Posicionamento lógico dos drivers de dispositivos � Comunicações entre os drivers e os controladores dos dispositivos acontece através do barramento Tipos: Bloco Caracter Interface padrão Kernel / usuário Estáticos/dinâmicos Programação do dispositivo Reentrantes Interação com o SO Drivers de Dispositivos 17 5-1.33INE5355 – Sistemas Operacionais I Software Independente de dispositivo � Interface uniforme para os drivers dos dispositivos • Padrão de interface para o SO • Nomes dos dispostivos : /dev/disk0 • Padrão de proteção (rwx) � Armazenamento em Buffer • Dispositivos de bloco – manter até bloco inteiro ser escrito • Dispositivos de caracter – escrita + rápida que saída, entrada chega antes � Relatório de erros • Erros reportados independente do dispositivo � Alocação e liberação de dispositivos dedicados � Tamanho de bloco independente de dispositivo • Nem todos os discos tem o mesmo tamanho de setor 5-1.34INE5355 – Sistemas Operacionais I Software Independente de dispositivo (2) (a) Sem uma interface padrão do driver (b) Com uma interface padrão do driver Tamanho de bloco independente de dispositivo Alocação e liberação de dispositivos dedicados Relatório de erros Armazenamento em Buffer Interface uniforme para os drivers dos dispositivos 18 5-1.35INE5355 – Sistemas Operacionais I Figure 3.13. I/O buffers. 5-1.36INE5355 – Sistemas Operacionais I Software de E/S no espaço do usuário • Bibliotecas de E/S - write(fd,buffer,nbytes), printf(“....”), scanf, .. • sppoling (daemon) – gerencia dispositivos dedicados 19 5-1.37INE5355 – Sistemas Operacionais I Camadas do sistema de E/S e as funções principais de cada camada. Ex: leitura de arquivo (bloco) 5-1.38INE5355 – Sistemas Operacionais I UNIX SVR4 E/S 20 5-1.39INE5355 – Sistemas Operacionais I Figure 3-16. Two ways of structuring user- system communication. 5-1.40INE5355 – Sistemas Operacionais I Figure 3-18. Outline of the main procedure of an I/O device driver. 21 5-1.41INE5355 – Sistemas Operacionais I Figure 2-46. (a) Worst case for reading a block requires eleven messages. (b) Best case for reading a block requires four messages. 5-1.42INE5355 – Sistemas Operacionais I Linux Input and Output � Linux splits all devices into three classes: • block devices allow random access to completely independent, fixed size blocks of data • character devices include most other devices; they don’t need to support the functionality of regular files. • network devices are interfaced via the kernel’s networking subsystem Silberschatz, Galvin and Gagne 2002 22 5-1.43INE5355 – Sistemas Operacionais I Linux Device-Driver Block Structure Silberschatz, Galvin and Gagne 2002 5-1.44INE5355 – Sistemas Operacionais I Block Devices � Provide the main interface to all disk devices in a system. � The block buffer cache serves two main purposes: • it acts as a pool of buffers for active I/O • it serves as a cache for completed I/O � The request manager manages the reading and writing of buffer contents to and from a block device driver. Silberschatz, Galvin and Gagne 2002 23 5-1.45INE5355 – Sistemas Operacionais I Character Devices � A device driver which does not offer random access to fixed blocks of data. � A character device driver must register a set of functions which implement the driver’s various file I/O operations. � The kernel performs almost no preprocessing of a file read or write request to a character device, but simply passes on the request to the device. � The main exception to this rule is the special subset of character device drivers which implement terminal devices, for which the kernel maintains a standard interface. Silberschatz, Galvin and Gagne 2002 5-1.46INE5355 – Sistemas Operacionais I Linux Device Management � Each time the device is given a command, for example ``move the read head to sector 42 of the floppy disk'' the device driver has a choice as to how it finds out that the command has completed. � Two basic approaches to device management in Linux are available: • Use Polling to determine when a device has completed an operation. • Use interrupts. Gary Nutt 2001 24 5-1.47INE5355 – Sistemas Operacionais I Linux Device Management � Polling case, the user process performs an I/O request (read()) at the system call interface. This cause the device driver to start the device.The task polls the device to determine when the operation is completed. Gary Nutt 2001 5-1.48INE5355 – Sistemas Operacionais I Linux Device Management � Interrupts - An interrupt driven device driver is one where the hardware device being controlled will raise a hardware interrupt whenever it needs to be serviced. For example, an ethernet device driver would interrupt whenever it receives an ethernet packet from the network. The Linux kernel needs to be able to deliver the interrupt from the hardware device to the correct device driver. This is achieved by the device driver registering its usage of the interrupt with the kernel. It registers the address of an interrupt handling routine and the interrupt number that it wishes to own. � You can see which interrupts are being used by the device drivers, as well as how many of each type of interrupts there have been, by looking at /proc/interrupts: • 0: 727432 timer • 1: 20534 keyboard • 2: 0 cascade • 3: 79691 + serial • 4: 28258 + serial • 5: 1 sound blaster • 11: 20868 + aic7xxx • 13: 1 math error • 14: 247 + ide0 • 15: 170 + ide1 � http://www.tldp.org/LDP/tlk/tlk.html Gary Nutt 2001 25 5-1.49INE5355 – Sistemas Operacionais I Linux Device Management � A device driver, IRQ, ISR, and a device bottom half might be involved in carrying out the operation. � When a process issues an I/O request to the kernel the device driver checks the status of the device and, if the device is available, starts it on the I/O operation. � The task blocks in state TASK_INTERRUPTIBLE � Meanwhile, the device operates until it completes the operation, at which time it issues an IRQ to the CPU Gary Nutt 2001 5-1.50INE5355 – Sistemas Operacionais I Linux Device Management � The IRQ causes the ISR that is associted with the IRQ to be executed � The ISR performs a minimum of the processing tasks associated wth the completion of the operation and marks its bottom half for later processing if needed. Gary Nutt 2001 26 5-1.51INE5355 – Sistemas Operacionais I Linux Device Management � Once the ISR, and all other ISRs that might have interrupted the original ISR, have completed, the ret_from_sys_call code block is executed. �It is also run when any system call is completed, runs all marked bottom halves, marks the completed processes as ready (TASK_RUNNING), and then calls the scheduler. Gary Nutt 2001 5-1.52INE5355 – Sistemas Operacionais I Linux Device Management � The Device Driver • Device drivers and devices are referenced by using major and minor numbers. • If you issue the ls –l command, you’ll see two number. These numbers are the major and minor device number for the particular device. Gary Nutt 2001 27 5-1.53INE5355 – Sistemas Operacionais I Linux Device Management � Major number • Traditionally, the major number identifies the driver associated with the device. For example, /dev/null and /dev/zero are both managed by driver 1, whereas virtual consoles and serial terminals are managed by driver 4; similarly, both vcs1 and vcsa1 devices are managed by driver 7. Modern Linux kernels allow multiple drivers to share major numbers, but most devices that you will see are still organized on the one-major-one-driver principle. When one instance of an ISR might get interrupted by a second instance of the same ISR, parts of the ISR work can be relegated to a bottom half. � Minor number • The minor number is used by the kernel to determine exactly which device is being referred to. Gary Nutt 2001 5-1.54INE5355 – Sistemas Operacionais I Linux Device Management � Classes of Devices • UNIX devices are classically divided into block devices and character devices. • The APIs for the two classes are different – the functions implemented in a block device driver differ from those in a character device driver. • When a machine is booted, the device divers are usually registered with the OS. A kernel function is called to register a device. • It requires the major number, device name, and a list of type struct file_operations that identify the entry point for each device operation supported by the driver. • This registration process saves the device driver name and file operations in either the chrdevs[ ] or blkdevs[ ] kernel tables, using the major number as the table index. Gary Nutt 2001 28 5-1.55INE5355 – Sistemas Operacionais I chrdevs[ ] 5-1.56INE5355 – Sistemas Operacionais I Linux Device Management � Handling Interrupts • The ISR is associated with a particular IRQ via an explicit kernel function, request_irq() . • Arguments of this function to specify the IRQ: for fast or slow interrupt, entry point of the ISR, • If the IRQ already has a ISR associated with it, then the request fails. • A computer contains a limited number of IRQ identifiers, as determined by the hardware. So, if two different devices must use the same IRQ, a master ISR must demultiplex IRQs to a collection of ISRs. • It does this by polling the hardware to determine which device actually caused the IRQ, and then i selects the proper ISR from the collection. Gary Nutt 2001 29 5-1.57INE5355 – Sistemas Operacionais I Linux Device Management � Handling Interrupts • The ISR can be constructed to perform any work that is needed to complete the I/O operation after the devices finishes. • For example, it might check the device status to ensure that the operation completed sucessfully. For a read operation, it might also transfer data from the device buffer to primary memory. • When one instance of an ISR might get interrupted by a second instance of the same ISR, parts of the ISR work can be relegated to a bottom half. • When ret_from_sys_call runs , it will detect the marked bottom half and run it before calling the scheduler. • A maximum of 32 different bottom halves can be marked for execution. Gary Nutt 2001
Compartilhar