Post on 20-Jan-2019
21/11/16
1
InterfacesePeriféricosSubsistemadeE/SdoSOe
Drivers
Prof.JoãoPauloA.Almeida(jpalmeida@inf.ufes.br)
IncluislidesdeRobertaLimaGomes
MaterialdidáHco• Capítulodelivrotexto:AndrewS.Tanenbaum,Modern
Opera+ngSystems,2ªedição,Pren?ce-Hall.Capítulo5:Input/Output.– Tambémdisponívelemportuguês:SistemasOperacionaisModernos,2a.Edição,Pearson-Pren?ce-HalldoBrasil,2003.
3
CamadasdoSoLwaredeE/S
CamadasdosistemadesoLwaredeE/S
4
CamadasdoSoLwaredeE/S
SubsistemadeE/SdoSistemaOperacional
BibliotecasdeE/SInterfacedoSistemaOperacional
(ChamadasdeSistema)
Barramento/Controladores
5
CamadasdoSoLwaredeE/S
SubsistemadeE/SdoSistemaOperacional
BibliotecasdeE/S
Barramento/Controladores
InterfacedoSistemaOperacional(chamadasc/interrupçõesemsoLware)
InterrupçõesdeE/Semhardware
21/11/16
2
7
DriversdosDisposiHvos
Independente de dispositivo
Interface padrão
Chamadas de sistema
8
Subsistema(SoLware)deEntradaeSaída
• ObjeHvos– Fornecerumainterface“amigável”parauHlizaçãodosdisposiHvosdeE/S• UniformizarotratamentodosdisposiHvos• “Esconder”detalhesdemais“baixonível”
– PermiHrainclusãodenovosdisposiHvos– FacilitaracorreçãodeerrosgeradospelodisposiHvo
– ExplorareficientementeosdisposiHvosdeE/S• Desempenho
– ComparHlhardisposiHvosdeE/S– AlocardisposiHvos– Escalonarrequisições
9
FunçõesdosoLwaredeE/SindependentedediposiHvo
Interface uniforme para os drivers dos dispositivos
Identificação de dispositivo
Proteção de dispositivo
Armazenamento em buffer
Relatório dos erros
Alocação e liberação de dispositivos dedicados
Fornecimento de tamanho de bloco independente de dispositivo
10
CamadasdoSub-SistemadeE/S
CamadasdosistemadeE/Seasprincipaisfunçõesdecadacamada
21/11/16
3
14
SoLwaredeE/SIndependentedeDisposiHvo(3)
a) EntradasemuHlizaçãodebufferb) UHlizaçãodebuffernoespaçodousuárioc) UHlizaçãodebuffernonúcleoseguidodecópiaparaoespaçodo
usuário
15
SoLwaredeE/SIndependentedeDisposiHvo(4)
Aoperaçãoemredepodeenvolvermuitascópiasdeumpacote
17
SoLwaredeE/SIndependentedeDisposiHvo(2)
(a)Semumainterface-padrãododriver(b)Comumainterface-padrãododriver
19 Profa. Roberta L.G. LPRM/DI/UFES
Subsistema(SoLware)deEntradaeSaída(4)
• SoLwaredeE/Sdeusuário:– RealizachamadasdealtonívelaosoLwaredeE/SindependentededisposiHvo:
– Wrappersparachamadasdesistema• Abrir/fechararquivo,ler/escreverdados,etc.
20 Profa. Roberta L.G. LPRM/DI/UFES
Subsistema(SoLware)deEntradaeSaída(5)
• InterfacedosubsistemadeE/S– disposiHvos“abstratos”deE/S– CadarepresentaumaclassededisposiHvosdeE/S
• DisposiHvos“abstratos”– Orientadoabloco(blockdevice)– Orientadoacaractere(stream,characterdevice)– Rede
21/11/16
4
21 Profa. Roberta L.G. LPRM/DI/UFES
Subsistema(SoLware)deEntradaeSaída(6)
• InterfacedosubsistemadeE/S(cont.)– DisposiHvosOrientadoabloco
• Organizadadosemblocosdetamanhofixo• Acessadiretamenteumblocodedados• BlocossãoidenHficadosporendereços(númerodobloco)
– ex:blocosdedisco• Operaçõesipicas:• open(),read(),write()eclose()• Disponibilizadasaosusuáriosviasistemadearquivos
22 Profa. Roberta L.G. LPRM/DI/UFES
Subsistema(SoLware)deEntradaeSaída(7)
• InterfacedosubsistemadeE/S(cont.)– DisposiHvosOrientadoacaractere
• ControladisposiHvosqueproduzemouconsomemconjuntodedadosdetamanhoarbitrário
• Operaçõesipicas:– put()eget()[implementadascomopen,read,write]– ex:teclado,vídeo,mouse,impressora,etc...
• Operaçõesespecíficas(inversãodecores,bip,inicialização,etc)sãofornecidasporumafunçãogenérica– io_control()
23 Profa. Roberta L.G. LPRM/DI/UFES
Subsistema(SoLware)deEntradaeSaída(8)
• InterfacedosubsistemadeE/S(cont.)– DisposiHvosOrientadoarede
• ControleeacessoadisposiHvosqueestãofisicamenteinstaladosemoutrosequipamentos
• Necessárioestabelecimentodeconexões• Interfaceipicasãosockets• Operaçõesipicas:
– open(),close(),create()• Suporteaserviços:
– orientadoaconexão:connect(),accept(),read(),write()– semconexão:send()erecv()
24 Profa. Roberta L.G. LPRM/DI/UFES
Subsistema(SoLware)deEntradaeSaída(9)
• SoLwaredeE/SindependentededisposiHvo– ImplementafunçõesgeraiscomunsatodososdisposiHvos– AtribuiçãouniformedonomeindependentedodisposiHvo
• OUNIXéumexemploclássico:– NomedodisposiHvoéumstring
25 Profa. Roberta L.G. LPRM/DI/UFES
EntradaeSaídanoUnix• OUnixmapeiaosdisposiHvosdeentradaesaídaemarquivos
especiais• DisposiHvoslocalizadosnodiretório/dev
– /dev/fd0Disquete– /dev/hda–MestredobarramentoIDE1– /dev/hdb–EscravodobarramentoIDE1– /dev/hdc–MestredobarramentoIDE2– /dev/hdd–EscravodobarramentoIDE2
• Nocasodediscos,umnúmerointeiroconcatenadoaodisposiHvoindicaaparHção
• /dev/hda1–PrimeiraparHçãododisposiHvomestredobarramentoide1
ChamadasdeSistema(Linux)%eax Name Source %ebx %ecx %edx
1 sys_exit kernel/exit.c int - -
2 sys_fork arch/i386/kernel/process.c struct pt_regs - -
3 sys_read fs/read_write.c unsigned int char * size_t
4 sys_write fs/read_write.c unsigned int const char * size_t
5 sys_open fs/open.c const char * int int
6 sys_close fs/open.c unsigned int - -
7 sys_waitpid kernel/exit.c pid_t unsigned int * int
8 sys_creat fs/open.c const char * int -
9 sys_link fs/namei.c const char * const char * -
10 sys_unlink fs/namei.c const char * - -
11 sys_execve arch/i386/kernel/process.c struct pt_regs - -
21/11/16
5
EsquemasdeEntrada/Saída
• 3esquemasdiferentespararealizaçõesdeE/S:– 1 – E/S Programada com Espera Ocupada (busy wait,polling)
– 2–E/SDirigidaporInterrupção– 3–E/ScomAcessoDiretoàMemória(DMA)
28
E/SProgramada(1)
Passosdaimpressãodeumacadeiadecaracteres
29
E/SProgramada(2)
EscritadeumacadeiadecaracteresparaaimpressorausandoE/Sprogramada
30
E/SOrientadaaInterrupção
• EscritadeumacadeiadecaracteresparaaimpressorausandoE/Sorientadaàinterrupção
a) Códigoexecutadoquandoquandoéfeitaachamadaaosistemaparaimpressão
b) RoHnadetratamentodeinterrupção
31
E/SUsandoDMA
• ImpressãodeumacadeiadecaracteresusandoDMAa) Códigoexecutadoquandoquandoéfeitaachamadaao
sistemaparaimpressãob) RoHnadetratamentodeinterrupção
DiscoRígido
21/11/16
6
TamanhodeSetor
Buffers…paraescritanoarquivo Buffers
https://lwn.net/Articles/457667/
Opçõesdeopenintopen(constchar*pathname,intflags)• O_NONBLOCKorO_NDELAY• Whenpossible,thefileisopenedinnonblockingmode.Neithertheopen()noranysubsequentoperaHonsonthefiledescriptorwhichisreturnedwillcausethecallingprocesstowait.
• O_SYNC• ThefileisopenedforsynchronousI/O.Anywrite(2)sontheresulHngfiledescriptorwillblockthecallingprocessunHlthedatahasbeenphysicallywrizentotheunderlyinghardware.
Flush• #include<stdio.h>• intfflush(FILE*stream);• Foroutputstreams,fflush()forcesawriteofalluser-spacebuffereddataforthegivenoutputorupdatestreamviathestream'sunderlyingwritefuncHon.
• IfthestreamargumentisNULL,fflush()flushesallopenoutputstreams.
• Notethatfflush()onlyflushestheuserspacebuffersprovidedbytheClibrary.Toensurethatthedataisphysicallystoredondiskthekernelbuffersmustbeflushedtoo,forexample,withsync(2)orfsync(2).
21/11/16
7
Sync• sync()causesallbufferedmodificaHonstofilemetadataanddatatobewrizentotheunderlyingfilesystems.
• syncfs()islikesync(),butsynchronizesjustthefilesystemcontainingfilereferredtobytheopenfiledescriptorfd.
• Bugs• AccordingtothestandardspecificaHon(e.g.,POSIX.1-2001),sync()schedulesthewrites,butmayreturnbeforetheactualwriHngisdone.However,sinceversion1.3.20Linuxdoesactuallywait.(ThissHlldoesnotguaranteedataintegrity:moderndiskshavelargecaches.)
ArHgo• Relaçãodesempenhonotempoxconfiabilidade(integridadededados)
• Abstraçãoxrealidadedohardware• Impactonodesempenhopordiferentespremissas(comoosoLwareassumequeohardwarefunciona)
Perguntas• Porqueoautordizqueosdiscosesuascontroladores“mentem”?QualéamenHra?
• Qualéoproblemadeconfiabilidadequeéintroduzidoaotentarmaximizardesempenhonotempo?
• Qualoproblemaquetagqueueingresolve?Comofunciona?
• QualoproblemadasimplementaçõesSATAsemNCQ?• Discutaasconsequênciasdoaumentodotamanhodosetor.Quaissãoasmétricasafetadas?Porque?
A1amenHra• Paraevitarqueademandasejareprimida(próximasdemandasviriamsomenteapósumarequisiçãosercompletamenteatendida,ousejaatéqueosdadossejamescritosnamídia)ascontroladoresdizemqueosdadosjáforamescritosassimqueosdadosestãonocache(memóriavoláHl)
• Istofazcomquecrashslevemosistemaaumestadoinconsistente(aplicaçãoachaquejáescreveu,masdadosnãoforamescritos)
• ÉistoqueelechamademenHra:asubversãoda“semânHca”doflush
• DopontodevistadedesempenhoéposiHvo,gerandopipeline
Tagqueueing • PermitemúlHplasrequisiçõessimultaneamente• Cadaumaéconfirmadaindependentementequandoforescritaemdisco
• Pipelineépossível• Escalonamentoeficienteépossível(acessarossetoresmaispróximosantesconsiderandoarotaçãododisco)– Pensenoelevador
NaHveCommandQueueing
21/11/16
8
AumentodoTamanhodoSetor Escritaleva2voltasnodisco
CiclodevidadeE/S• Comoosdriverssãocarregados?
48
CamadasdoSoLwaredeE/S
SubsistemadeE/SdoSistemaOperacional
BibliotecasdeE/SInterfacedoSistemaOperacional
(ChamadasdeSistema)
Barramento/Controladores
BIOS
49
CamadasdoSoLwaredeE/S
SubsistemadeE/SdoSistemaOperacional
BibliotecasdeE/SInterfacedoSistemaOperacional
(ChamadasdeSistema)
Barramento/Controladores
BIOS
BIOS=BasicInput/OutputSystem• DisponívelemROMouFLASH(firmware)• Bootstrapping
– BIOSrecebecontrole– Endereço�sico000FFFF0h
• Power-OnSelfTest(POST)• Configuraçãobásicadecontroladores• CargadoSistemaOperacional
– OudeumBootLoaderdesegundonível– LILO,bootfromnetwork,SCSI,USB
• Fornecidopelosprodutoresdeplacamãe• hzp://en.wikipedia.org/wiki/BIOS• hzp://www.embeddedarm.com/Manuals/EBIOS-UM.PDF
21/11/16
9
POST• PrincipaisaHvidadesdurantePOST:
– VerificaintegridadedaBIOS(updatesflash)– Verificaamemória– Descobrir,inicializarecatalogarbarramentosedisposiHvos
– Proverinterfacec/usuárioparaconfiguração– IdenHficareselecionardisposiHvosparaboot– Construirambienteparacargadosistemaoperacional
http://en.wikipedia.org/wiki/Image:Phoenix_-_AwardBIOS_CMOS_Setup_Utility.jpg
BIOS=BasicInput/OutputSystem• Usadoparaentradaesaídabásicaduranteosprocedimentosdebooteconfiguraçãodehardware
• Etambémduranteaexecuçãodesistemasoperacionaismaissimples(DOSporexemplofaziausoextensivodaBIOSparaentradaesaída)– ParaissoaBIOSofereciaumainterfacesimilaràinterfacedosSistemasOperacionais
– UsandointerrupçõesdesoLware– Usandoatabeladevetoresdeinterrupção
InterrupçõesdeSoLware
• InterrupçõesdesoLwarepodemseraHvadasporsoLware• InstruçãoINT<número-interrupção>
– ACPUentãousaestenúmeroparaindexarumatabelade256entradas(vetordeinterrupções)paraencontraroendereçodaro?nadetratamentodeinterrupçãoaserexecutada
– Vetordeinterrupçõesseencontranoendereço0• 256x4bytes
• DoisHposdeinterrupções– InterrupçõesdoSistemaOperacional(DOS,Linux,etc.)
– InterrupçõesdaBIOS• ParagerarinterrupçõesdoDOSuse:INT21h• ParagerarinterrupçõesdoLinuxuse:INT80h
ChamadasdeSistema• INT21h–DOS/Windows(16-bits)
– Quandousamosestainstrução,oDOSchamaumaroHnadetratamentoespecífica,dependendodoHpodeinterrupção
– OHpodeinterrupçãoserádefinidoemfunçãodovalorqueesHverarmazenadonoregistradorAL
• INT80h–Linux– hzp://asm.sourceforge.net/
• INT11h-1ah–BIOS– ChamadopeloDOS
56
Interrupções…nãoconfundir!InterfacedoSistemaOperacional
(chamadasc/interrupçõesemsoLware)
InterrupçõesdeE/Semhardware
BIOS
InterfacedoBIOS(chamadasc/interrupçõesemsoLware)
Natabeladeinterrupçõesestátudomisturado!
21/11/16
10
TabeladeInterrupção(IVT)Interrupt Description
INT 00h CPU: Division by Zero
INT 01h CPU: Single Step for debugging
INT 02h CPU: NMI, used e.g. by POST for memory errors (Power-On Self Test)
INT 03h CPU: Breakpoint for debugging
INT 04h CPU: Numeric Overflow
INT 05h Print Screen
INT 08h IRQ0: Called by system timer 18.2 times per second
INT 09h IRQ1: Called by keyboard
INT 0Bh IRQ3: Called by 2nd serial port COM2
INT 0Ch IRQ4: Called by 1st serial port COM1
INT 0Dh IRQ5: Called by hard disk controller (PC/XT) or 2nd parallel port LPT2 (AT)
INT 0Eh IRQ6: Called by floppy disk controller
INT 0Fh IRQ7: Called by 1st parallel port LPT1 (printer)
Em vermelho as interrupções de E/S de hardware
TabeladeInterrupção
INT 70h IRQ8: Called by RTC INT 74h IRQ12: Called by mouse INT 75h IRQ13: Called by math coprocessor INT 76h IRQ14: Called by primary IDE controller INT 77h IRQ15: Called by secondary IDE controller
TabeladeInterrupção
INT 10h Video Services (ROM BIOS Extension on VGA controller)
AH=00h Set Video Mode AH=01h Set Cursor Shape AH=02h Set Cursor Position
AH=03h Get Cursor Position And Shape
AH=04h Get Light Pen Position AH=05h Set Display Page AH=06h Clear/Scroll Screen Up
AH=07h Clear/Scroll Screen Down
AH=08h Read Character and Attribute at Cursor
AH=09h Write Character and Attribute at Cursor
AH=0Ah Write Character at Cursor
AH=0Bh Set Border Color
AH=0Eh Write Character in TTY Mode
AH=0Fh Get Video Mode AH=13h Write String
TabeladeInterrupção(facilidadesBIOS)• INT11h–Equipamentosinstalados
– Onreturnfromint11h,theAXregistercontainsabit-encodedequipmentlistwiththefollowingvalues:
– Bit0Floppydiskdriveinstalled– Bit1Mathcoprocessorinstalled– Bits4,5IniHalvideomode00-none01-40x25color10-80x25color11-
80x25b/w– Bits6,7Numberofdiskdrives– Bit8DMApresent– Bits9,10,11NumberofRS-232serialcardsinstalled– Bit12GameI/Ocardinstalled– Bit13Serialprinterazached– Bits14,15Numberofprintersazached.
• INT12h–Indicaamemóriadisponível– ValoremAX:qualoproblema?
TabeladeInterrupção(facilidadesBIOS)Interrupt Description
INT 13h Low Level Disk Services
AH=00h Reset Disk Drives
AH=01h Check Drive Status
AH=02h Read Sectors From Drive
AH=03h Write Sectors To Drive
AH=04h Verifies Sectors On Drive
AH=05h Format Track On Drive
AH=08h Get Drive Parameters
AH=09h Init Fixed Drive Parameters
AH=0Ch Seek To Specified Track
AH=0Dh Reset Fixed Disk Controller
AH=15h Get Drive Type
AH=16h Get Floppy Drive Media Change Status
• http://en.wikipedia.org/wiki/BIOS_call
TabeladeInterrupçãoINT 14h Routines for communicating via the serial port. Used
by software programs. AH=00h Serial Port Initialization AH=01h Transmit Character AH=02h Receive Character AH=03h Status
INT 15h Miscellaneous AH=4FH Keyboard Intercept AH=83H Event Wait AH=84H Read Joystick AH=85H Sysreq Key Callout AH=86H Wait AH=87H Move Block
AH=88H Get Extended Memory Size
AH=C0H Get System Parameters
AH=C1H Get Extended BIOS Data Area Segment
AH=C2H Pointing Device Functions
21/11/16
11
TabeladeInterrupção
INT 16h Implemented by the BIOS or operating system. Provides routines to be called by software programs which communicate with the keyboard.
AH=00h Read Character AH=01h Read Input Status
AH=02h Read Keyboard Shift Status
AH=10h Read Character Extended
AH=11h Read Input Status Extended
AH=12h Read Keyboard Shift Status Extended
INT 17h Print Services - used by software programs to communicate with the printer
AH=00h Print Character to Printer AH=01h Initialize Printer AH=02h Check Printer Status
...emaistabeladeinterrupçãoINT 19h After POST this interrupt is used by BIOS to load the
operating system.
INT 1Ah Real Time Clock Services - called by software programs to communicate with the RTC
AH=00h Read RTC AH=01h Set RTC AH=02h Read RTC Time AH=03h Set RTC Time AH=04h Read RTC Date AH=05h Set RTC Date AH=06h Set RTC Alarm AH=07h Reset RTC Alarm
InterrupçõesdeSoLware(DOS)
• INT21h(Entrada:AH<-01h,Saída:caracter->AL)– LêumcaracterdaconsoleecolocaoseucódigoASCIInoregistradorAL– ComogeraresteHpodeInterrupção
1. Copieovalor08hdentrodoregistradorAH2. Chameainstrução“INT21h”
Apósestachamada,assimquefordigitadoumcaracter,seucódigoASCIIserácolocadodentrodeAL
• INT21h(Entradas:AH<-02h,DL<-caracter)– Imprimeocaracterouoexecuta,sefordoHpobeep,linefeedou
assemelhados– ComogeraresteHpodeInterrupção
1. Copieovalor02hdentrodoregistradorAH2. CopieocódigoASCIIdocaracterquedesejaimprimirdentrodoregistrador
DL3. Chameainstrução“INT21h”
Arquivo.com(DOS,16-bit);hi.asm-simple"helloworld"program;assemblewith"nasm-fbin-ohi.comhi.asm"org100h;informNasmthisisa.comfile ;int21hisgoingtowant...movdx,msg;theaddressoformessageindxmovah,9;ah=9-"printstring"sub-funcHonint21h ;calldosservicesmovah,4Ch;"terminateprogram"sub-funcHonint21h;calldosservicesmsgdb'Hello,World!',0Dh,0Ah,'$';$-terminatedmessage
TabeladeChamadasdeSistema(DOS)AH Description AH Description
01 Read character from STDIN 02 Write character to STDOUT
05 Write character to printer 06 Console Input/Output
07 Direct char read (STDIN), no echo 08 Char read from STDIN, no echo
09 Write string to STDOUT 0A Buffered input
0B Get STDIN status 0C Flush buffer for STDIN
0D Disk reset 0E Select default drive
19 Get current default drive 25 Set interrupt vector
2A Get system date 2B Set system date
2C Get system time 2D Set system time
2E Set verify flag 30 Get DOS version
35 Get Interrupt vector
36 Get free disk space 39 Create subdirectory
3A Remove subdirectory 3B Set working directory
3C Create file 3D Open file
3E Close file 3F Read file
40 Write file 41 Delete file
42 Seek file 43 Get/Set file attributes
47 Get current directory 4C Exit program
4D Get return code 54 Get verify flag
56 Rename file 57 Get/Set file date
Exemplosdechamada(DOS)• AH=05h-WRITECHARACTERTOPRINTER• Entry:DL=charactertoprint• Notes:• keyboardcheckedfor^C/^Break• STDPRNisusuallythefirstparallelport,butmayberedirectedunderDOS2+
• iftheprinterisbusy,thisfuncHonwillwait
21/11/16
12
Exemplosdechamada(DOS)• AH=06h-DIRECTCONSOLEOUTPUT• Entry:DL=character(exceptFFh)• Return:AL=characteroutput• Notes:doesnotcheck^C/^Break• SeeAlso:AH=02h,AH=09h
Exemplosdechamada(DOS)• AH=06h-DIRECTCONSOLEINPUT• Entry:AH=06hDL=FFh• Return:• ZFsetifnocharacteravailableandAL=00h• ZFclearifcharacteravailableAL=characterread• Notes:• ^C/^BreakareNOTchecked• ifthereturnedcharacteris00h,theuserpressedakeywithanextendedkeycode,whichwillbereturnedbythenextcallofthisfuncHon
Exemplosdechamada(DOS)AH=01h-READCHARACTERFROMSTANDARDINPUT,WITHECHO
Return:AL=characterreadNotes:^C/^Breakarechecked^PtogglestheDOS-internalecho-to-printerflag^Zisnotinterpreted,thusnotcausinganEOFifinputisredirectedcharacterisechoedtostandardoutput
Exemplosdechamada(DOS)• AH=02h-WRITECHARACTERTOSTANDARDOUTPUT• Entry:DL=charactertowrite• Return:AL=lastcharacteroutput• Notes:• ^C/^Breakarechecked• thelastcharacteroutputwillbethecharacterinDLunlessDL=09honentry,inwhichcaseAL=20hastabsareexpandedtoblanks
• ifstandardoutputisredirectedtoafile,noerrorchecks(write-protected,fullmedia,etc.)areperformed
Exemplosdechamada(DOS)• AH=09h-WRITESTRINGTOSTANDARDOUTPUT• Entry:DS:DX->'$'-terminatedstring• Return:AL=24h• Notes:^C/^Breakarechecked
Exemplosdechamada(DOS)• AH=2Ah-GETSYSTEMDATE• Return:CX=year(1980-2099)DH=monthDL=dayAL=dayofweek(00h=Sunday)
• AH=2Bh-SETSYSTEMDATE• Entry:CX=year(1980-2099)DH=monthDL=day• Return:• AL=00successful• FFhinvaliddate,systemdateunchanged
21/11/16
13
Exemplosdechamada(DOS)• AH=39h-"MKDIR"-CREATESUBDIRECTORY• Entry:DS:DX->ASCIZpathname• Return:• CFclearifsuccessfulAXdestroyed• CFsetonerrorAX=errorcode(03h,05h)Chequemhzp://spike.scu.edu.au/~barry/interrupts.html#ah01paraumalistacompleta