47
CSE 3320 Operating Systems I/O Devices Jia Rao Department of Computer Science and Engineering http://ranger.uta.edu/~jrao

CSE3320 Operating Systems I/O Devices

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CSE3320 Operating Systems I/O Devices

CSE 3320OperatingSystems

I/ODevices

Jia RaoDepartmentofComputerScience and Engineering

http://ranger.uta.edu/~jrao

Page 2: CSE3320 Operating Systems I/O Devices

RecapofPreviousClasseso CPUscheduling

o Memorymanagement

o FileSystems

o Thischapterà I/Odevices(e.g.,harddisks)

Page 3: CSE3320 Operating Systems I/O Devices

I/OofanOSMainFunction:Controlallthecomputer’sI/Odevices

o Issuecommandstothedevices,catchinterrupts,andhandleerrors

o Provideinterfacebetweenthedevicesandtherestofsystemthatissimpleandeasytouse

WhatwecareI/Odevicesmostassoftwaredesignersandprogrammers?

Theinterfacepresentedtous:(1)Thecommandsthehardwareaccepts(2)Thefunctionsitcarriesout(3)Theerrorsthatcanbereportedback

Page 4: CSE3320 Operating Systems I/O Devices

PrinciplesofI/OHardware:I/ODevices

Sometypicaldevice,network,anddatabaserates

• Blockdevices• Characterdevices• Others

Page 5: CSE3320 Operating Systems I/O Devices

DeviceControllers• I/Odeviceshavetwocomponents:

o mechanicalcomponento electroniccomponent

• Theelectroniccomponentisthedevicecontrollero maybeabletohandlemultiplebutidenticaldevices

• Controller'staskso convertserialbitstreamtoblockofbyteso performerrorcorrectionasnecessaryo makeblocksavailabletomainmemory

buffer/cache

Devicecontroller

I/ODevice

Standardinterface:IDE,SCSI

register

Page 6: CSE3320 Operating Systems I/O Devices

CPUàI/O:SpecialI/OInstructions• HowdoestheCPUcommunicatewiththecontrolregistersandthedevicedata

buffers?Twomethodsareavailable.• MethodI:Special(assembly)I/OInstructions(IBM360)

o EachcontrolregisterisassignedanI/Oportnumber(device#)INREG,PORT

OUTPORT,REG

o ThememoryaddressspaceandI/OaddressspacearedifferentINR0,4 ;port4

MOVR0,4 ;memoryword4

Page 7: CSE3320 Operating Systems I/O Devices

CPUàI/O:Memory-mappedI/O° MethodII:Memory-mappedI/O(Pentium)

• Eachregisterisassignedauniquememoryaddresstowhichnomemoryisassigned;read/writetoaddressesareI/Ooperations

• Howitworks?

Page 8: CSE3320 Operating Systems I/O Devices

CPUàI/O:Memory-mappedI/O(2)° AdvantagesofMemory-mappedI/O

• AnI/OdevicedrivercanbewritteninC,insteadofassembly• Protectioniseasy(byaddresstranslation);userprogramsarepreventedfrom

issuingI/Ooperationsdirectly- ThatI/O-mappedspacenotinanyuser’svirtualaddr.space

(a)SeparateI/Oandmemoryspace;(b)Memory-mappedI/O;(c)Hybrid(PDP-11) (Pentium)

Page 9: CSE3320 Operating Systems I/O Devices

CPUàI/O:Memory-mappedI/O(3)° DisadvantagesofMemory-mappedI/O

• Cachingadevicecontrolregisterwouldbedisastrous• BothmemoryandallI/Odevicesmustexamineallmemoryreferencestosee

whichonestorespondto,noteasyifbushierarchy

(a)Asingle-busarchitecture;(b)Adual-busmemoryarchitecture

Howtoovercomethedisadvantages?Selectivecachingandmore...

Page 10: CSE3320 Operating Systems I/O Devices

CPUàI/O:Memory-mappedI/O(4)• PCIbridgechipfiltersaddressestodifferentbuses

Page 11: CSE3320 Operating Systems I/O Devices

I/Oà CPU:DeviceNotifyingtheCPU• TheOSneedstoknowwhen:

o TheI/Odevicehascompletedanoperationo TheI/Ooperationhasencounteredanerror

• Thiscanbeaccomplishedintwodifferentways:o Polling(BusyWaiting):

} TheI/Odeviceputinformationinastatusregister} TheCPUperiodicallyorcontinuouslycheckthestatusregister

o I/OInterrupt:} WheneveranI/Odeviceneedsattentionfromtheprocessor,

itinterruptstheprocessorfromwhatitiscurrentlydoing.

Inreal-timesystems,ahybridapproachisoftenused} UseaclocktoperiodicallyinterrupttheCPU,atwhichtimetheCPUpollsallI/Odevices

Page 12: CSE3320 Operating Systems I/O Devices

DataTransfer:ProgrammedI/O(BusyWaiting)

CPU

IOC

device

Memory

Is thedata

ready?

readdata

storedata

yes no

done? noyes

busywaitloopnotanefficient

waytousetheCPUunlessthedevice

isveryfast!

• Advantage:o Simple:theprocessoristotallyincontrolanddoesallthework

• Disadvantage:o PollingoverheadcanconsumealotofCPUtime

Page 13: CSE3320 Operating Systems I/O Devices

• Advantage:o Userprogramprogressisonlyhaltedduringactualtransfer

• Disadvantage,specialhardwareisneededto:o Causeaninterrupt(I/Odevice)o Detectaninterrupt(processor)o Savetheproperstatestoresumeaftertheinterrupt(processor)

DataTransfer:InterruptDrivenaddsubandornop

readstore...rtimemory

userprogram(1) I/O

interrupt

(2) save PC

(3) interruptservice addr

interruptserviceroutine(4)

CPU

IOC

device

Memory

:

Page 14: CSE3320 Operating Systems I/O Devices

DirectMemoryAccess(DMA)° DMAcontrollerhasaccesstosystembusindependentofCPU

• Amemoryaddressregister• Abytecountregister• Acontrolregister(direction,transferunit,andtransfermode)• Multiplereg.setsifmultipletransferatonce

OperationofaDMAtransfer

Page 15: CSE3320 Operating Systems I/O Devices

DMATransferModes° Cyclestealingmode:word-at-a-time,sneaksinandstealsanoccasional

buscyclefromtheCPUonceinawhile

° Burstmode:asksI/Odevicetoacquirethebus,issueaseriesoftransfers,thenreleasethebus

° Tradeoff:I/OefficiencyandCPUblockedWhyneedaninternalbufferatthediskcontroller?

Checksumcalculationandbusblocking

Page 16: CSE3320 Operating Systems I/O Devices

InterruptsRevisited° OnewayofhowI/OnotifiesCPU

• Interruptvectorandinterruptserviceprocedures• Priorityifmultiplesimultaneousinterrupts• CPUdelaysACKuntilitisreadytohandlethenextinterruptisawaytoavoid

raceconditions involvingmultiplealmostsimultaneousinterrupts

Page 17: CSE3320 Operating Systems I/O Devices

GoalsofI/OSoftware• Deviceindependence

o WriteprogramsthatcanaccessanyI/Odevicewithoutspecifyingdeviceinadvance

· (floppy,harddrive,orCD-ROM)

• Uniformnamingo nameofafileordeviceastringoraninteger(e.g.,pathname)o notdependingonwhichmachine/deviceo UNIXMountSystem

• Errorhandlingo handleasclosetothehardwareaspossible,i.e.,controllerfirst

thendevicedrivernext

Page 18: CSE3320 Operating Systems I/O Devices

GoalsofI/OSoftware(2)• Synchronousvs.asynchronoustransfers

o blockedtransfersvs.interrupt-driven

o Logicallysynchronoustoprogrammersandphysicallyasynchronous

• Buffering

o datacomingoffadevicecannotbestoreddirectly infinaldestination,e.g.,network-I/Ooperations

} Forchecksumandtimingconstraints

• Sharablevs.dedicateddevices

o disksaresharable

o tapedriveswouldnotbe

o dedicationintroducesdeadlockWhatarethreefundamentaldifferentwaysofperformingI/O?

Page 19: CSE3320 Operating Systems I/O Devices

ProgrammedI/O° Polling(busywaiting)

• CPUcontinuouslypollsthedevice(register)toseeifitisready• SimplebutCPUtimewasteful

Stepsinprintingastring

Page 20: CSE3320 Operating Systems I/O Devices

ProgrammedI/O(2)

WritingastringtotheprinterusingprogrammedI/O

Whatiftheprintercanprint100character/sec?

CPUwouldbeidlefor10mseachloopiteration!Whynotswitchingtoanotherprocess?

Page 21: CSE3320 Operating Systems I/O Devices

Interrupt-DrivenI/O

Writingastringtotheprinterusinginterrupt-drivenI/O(a)Codeexecutedwhenprintsystemcallismade(b)Interruptserviceprocedure

° AwaytoallowtheCPUtodosomethingelsewhilewaitingfortheprintertobecomeready

Still,aninterruptoccurseverycharacter,whattodo?

Page 22: CSE3320 Operating Systems I/O Devices

I/OUsingDMA

• PrintingastringusingDMA

o codeexecutedwhentheprintsystemcallismade

o interruptserviceprocedure

° Awaytoreducethenumberofinterruptsfromonepercharactertooneperbufferprinted• Transfersablockofdatadirectlytoorfrommemory• Aninterruptissentwhenthetaskiscomplete• Theprocessorisonlyinvolvedatthebeginningandendofthetransfer

Page 23: CSE3320 Operating Systems I/O Devices

I/OSoftwareHierarchy

LayersoftheI/OSoftwareSystem

Oneobjective:aslittleofOSaspossibleknowsabouttheinterrupts

Howaboutthefollowingjobs:(1) Checkiftheuserispermittedtousethedevice(2) Writingcommandstothedeviceregisters(3) Formattingtheoutputdataforprinting

Page 24: CSE3320 Operating Systems I/O Devices

OSInterruptHandling

• Interruptvectoro containstheaddressoftheinterruptserviceprocedures

o Jumptable

SkeletonofwhatlowestlevelofOSdoeswhenaninterruptoccurswhenaprocessisrunning

Page 25: CSE3320 Operating Systems I/O Devices

InterruptHandlers• Interrupthandlersarebesthidden

o havedriverstartinganI/Ooperationblockuntilinterruptnotifiesofcompletion

• Interruptproceduredoesitstask,handlinginterruptso thenunblocksdriverthatstartedit

• Butactually,manyOSstepsmustbeperformedinsoftwareafterhardwareinterrupt hascompleted

1. Saveregs notalreadysavedbyinterrupthardware2. Setupcontextforinterruptserviceprocedure3. ……

Page 26: CSE3320 Operating Systems I/O Devices

DeviceDrivers

• Logicalpositionofdevicedriversisshownhere• Communicationsbetweendriversanddevicecontrollersgooverthebus

° Devicedrivers:providedbydevice’smanufacturer,device-specificcodeforcontrollingthedevice(viadevicecontrollerregisters)

Page 27: CSE3320 Operating Systems I/O Devices

DeviceDriversInstallationHowtoinstalldevicedriverstoOSkernel?• Staticinstallationandrecompiling(Unix)

o Recompilethekernelwiththenewdriver• Staticregistrationandrebooting(earlyWindows)

o MakeanentryinanOSfileandrebootthesystem• Dynamicinstallation(Windows&Unix)

o On-the-flyloadingintothesystemduringtheexecution

Page 28: CSE3320 Operating Systems I/O Devices

Device-IndependentI/OSoftware° ThebasicfunctionistoperformtheI/Ofunctionsthatarecommontoall

devicesandtoprovideauniforminterfacetotheuser-levelsoftware

Functionsofthedevice-independentI/Osoftware

Uniform interfacing for device drivers

Buffering

Error reporting

Allocating and releasing dedicate devices

Providing a device-independent block size

Page 29: CSE3320 Operating Systems I/O Devices

AnExampleofDevice-independentI/OSoftware

Page 30: CSE3320 Operating Systems I/O Devices

Buffering° (a)Unbuffered input:doesn’tithavetoomanyinterrupts?

° (b)Bufferinginuserspace:Whathappensifthebufferispagedout (todisk)whenacharacterarrives?Gopinning?

° (c)Bufferinginthekernelfollowedbycopyingtouserspace

• Whathappenstocharactersthatarrivewhilethepagewiththeuserbufferisbeingbrought(inmemory)fromthedisk?

° (d)Doublebuffering inthekernel;twobufferstaketurns.

Page 31: CSE3320 Operating Systems I/O Devices

DisadvantagesofBuffering° Whytheprocessdoesnotcopythedatatothewiredirectlyfromkernel

memory?• Buthowabouttheperformance?

- Whynotbit-by-bitfromthekernelbuffertothenetwork?

Networkingmayinvolvemanycopiesofapacket,andallstepsmusthappensequentially

Page 32: CSE3320 Operating Systems I/O Devices

User-SpaceI/OSoftware

LayersoftheI/Osystemandthemainfunctionsofeachlayer

° SomeofI/Osoftwareconsistsofuser-spacelibraries• ThestandardI/OlibrarycontainsanumberofproceduresthatinvolvewithI/O

andallrunaspartofuserprograms

- E.g.,scanf(),printf()forI/Oformatting,IntelDPDKforhigh-speedNICs

Page 33: CSE3320 Operating Systems I/O Devices

HardDisks

• Theconventionalsector-track-cylindermodelo Astackofplatters,asurfacewithamagneticcoatingo Magneticdisksareorganizedintocylinders,forS/R/W

• Overlappedseeks:onediskcontrollerseeks2+drivessimultaneouslyo Transferbetweenthediskandthecontrollercanbesimultaneouso Butonetransferbetweenthecontrollerandthemainmemory

Sector

Track

Page 34: CSE3320 Operating Systems I/O Devices

Three-StageDiskR/WProcess• Three-stageDiskR/Wprocess:timerequiredtoreadorwriteadisk

blockdeterminedmainlyby3factors1. Seektime2. Rotationaldelay3. Actualtransfertime

• Seektimedominates

DiskAccessTime=Seektime+RotationalLatency+Transfertime+ControllerTime+QueuingDelay

Howtooptimizeseektime?Diskarmschedulingalgorithms

Page 35: CSE3320 Operating Systems I/O Devices

SSFDiskArmSchedulingAlgorithm° Howtooptimizeseektimeifatableavailable,indexedbycylinder

number,withallthependingdiskrequests foreachcylinderchainedinalinkedlist headedbythetableentries?• Example:11(c),1,36,16,34,9,12byFCFSandSSF

• SSFcutsaverageseektimeofFCFSalmostinhalf(111à61)

ShortestSeekFirst(SSF)diskschedulingalgorithm

Initialposition

Pendingrequests

WhatisthekeyproblemwithSSF?Howwouldyoudealwithit?

Page 36: CSE3320 Operating Systems I/O Devices

TheElevatorDiskArmSchedulingAlgorithm

Theelevatoralgorithmforschedulingdiskrequests

° Elevatoralgorithm:keepmovinginthesamedirectionuntiltherearenomoreoutstanding requestsinthatdirection• Onecurrentdirectionbit:UPandDown• Property:givenanycollectionofrequests,theupperboundonthetotal

motionisfixed:twicethenumberofcylinders

• Example:11(c),1,36,16,34,9,12bytheelevator

Page 37: CSE3320 Operating Systems I/O Devices

ErrorHandling

Controllerdoessectorsubstitution OSdoesstep(c)• Adisktrackwithabadsector.• Substitutingaspare forthebadsector• Shifting allthesectorstobypassthebadone

° Twogeneralapproachestodealwithbadblocks/sectors• diskcontrollerbasedvs.OSbased

Page 38: CSE3320 Operating Systems I/O Devices

Clocks(Timers)° Clockhardware:generateinterruptsatknownintervals

• Aprogrammableclock:itsinterruptfrequencycanbecontrolledbysoftware

• A500MHzcrystalwitha32-bitregistercangenerateinterruptevery2nsto8.6s

Aprogrammableclock

Page 39: CSE3320 Operating Systems I/O Devices

ClockSoftware° ClockSoftware(clockdriver):

• Maintainingthetimeofday

• supporttime-sharedscheduling

• AccountingCPUusage

• Handlingthealarm systemcall

• …

Page 40: CSE3320 Operating Systems I/O Devices

MaintainingtheTimeofDay

Threewaystomaintainthetimeofday

(a)Using64-bitscounter(b)Recordingtimeintermsofsecondswithasecondcounterinticks(c) Relativetosystemboottime,insteadofafixedexternalmoment

° Howaboutincrementingacounterateachclocktick?• Givenaclockrateof60Hz,a32-bitcounterlastabout2years

Page 41: CSE3320 Operating Systems I/O Devices

SoftTimers• Thereisaneedofasecondhardwareclocktocausetimer

interruptsatwhateverrateaprogramneedso specifiedbyapplicationso noproblemsifinterruptfrequencyislow

• TwowaysofmanagingI/Oo Pollinghasanaveragelatencyofhalfthepollingintervalo Interruptcanbecostly,say4.45µsona300MHzPIIo AGiga-bitEthernetasksforapacketevery12µs

• Softtimersavoidcostlyinterruptso kernelchecksforsofttimerexpirationbeforeitexitstouser

modeo howwellthisworksdependsonrateofkernelentries!Thecombinationofsofttimersandalow-frequencyhardwaretimermaybebetterthanpureinterrupt-drivenI/Oorpurepolling

Page 42: CSE3320 Operating Systems I/O Devices

PowerManagement

Powerconsumptionofvariouspartsofalaptopcomputer

° Powerconsumptionisimportanttodesktopsandbattery-poweredcomputer

° TwoGeneralapproachestobatteryconservation• Turnoff(down)someparts,top3powereaters:display,harddisk,andCPU• Applicationuseslesspower,multiplestates:on/off,sleep,hibernating

Power-awarecomputinginmobileandsensornetworks,manytradeoffs!

Page 43: CSE3320 Operating Systems I/O Devices

OSIssues:TheDisplay

° On-offswitching• Displayconsistofsomezonesthatcanbeindependentlypoweredupor

down

Page 44: CSE3320 Operating Systems I/O Devices

OSIssues:TheHardDisk° Ittakessubstantialenergytokeepitspinningathighspeed,evenifthere

arenodiskaccesses

° ButRestartingaharddiskconsumesconsiderableenergy• Whatisthebreak-evenpoint?• Td [5s,15s]• Ifthenextdiskaccessisexpectedsometimet inthefuture,comparet toTd

determinestheappropriatediskaction

° Alternative:haveasubstantialdiskcacheinRAM

° Alternative:OSkeepsrunningprogramsinformedaboutthediskstates,sothatsomeaccessescanbedelayed(andclustered)

SomethingcanbedonetoCPUtoo!

Page 45: CSE3320 Operating Systems I/O Devices

OSIssues:TheCPU

• Runningatfullclockspeed(fullvoltage)• Cuttingvoltagebytwo

o cutsclockspeedbytwoo cutspowerbyfour(powerconsumption~voltage^2)

Page 46: CSE3320 Operating Systems I/O Devices

Summary• OSresponsibilitiesinI/Ooperations

o ProtectionandSchedulingo CPUcommunicateswithI/Odeviceso I/OdevicesnotifyOS/CPU

• I/Osoftwarehierarchy

o Interrupthandlerso Devicedriverso Buffering

• StorageSystems

o Diskheadschedulingalgorithms• PowerManagement

Page 47: CSE3320 Operating Systems I/O Devices

Ref.MOS3E,OS@Austin,Columbia,RochesterUC.ColoradoSpringsCS4500/5500

Thankyouall!