SlideShare a Scribd company logo
1 of 12
1
I/O Systems (Galvin Notes,9th Ed.)
Chapter 13: I/O Systems
 OVERVIEW
 I/O HARDWARE
 Polling
 Interrupts
 Direct Memory Access
 APPLICATION I/O INTERFACE
 Block and Character Devices
 Network Devices
 Clocks and Timers
 Blocking and Non-blocking I/O
 KERNEL I/O SUBSYSTEM
 I/O Scheduling
 Buffering
 Caching
 Spooling and Device Reservation
 Error Handling
 I/O Protection
 Kernel Data Structures
 TRANSFORMING I/O REQUESTS TO HARDWARE OPERATIONS
 PERFORMANCE (Optional)
Content
OVERVIEW
 Management ofI/O devices is a veryimportant part of the operating system - soimportant andso varied that entire I/O subsystems are
devotedto its operation. (Consider the range of devices ona moderncomputer, from mice, keyboards, disk drives, display ada pters, USB
devices, network connections, audioI/O, printers, special devices for the handicapped, and many special -purpose peripherals.) I/O
Subsystems must contend withtwo (conflicting?) trends:(1) The gravitationtowards standard interfaces for a wide range of d evices, making
it easier to addnewlydevelopeddevices to existing systems, and (2) the development ofentirelynew typ es of devices, for whichthe existing
standard interfaces are not always easy to apply.
 Device drivers are modules that canbe pluggedintoanOS to handle a particular device or categoryof similar devices.
I/O HARDWARE
 I/O devices can be roughly categorized as storage,
communications, user-interface, andother Devices communicate
with the computer via signals sent over wiresor through the air.
Devices connect with the computer via ports, e.g. a serial or
parallel port.
 A common set of wires connectingmultiple devices is termed a
bus. Busesinclude rigidprotocols for the types ofmessages that
can be sent across the bus and the procedures for resolving
contentionissues. Figure 13.1 below illustrates three of the four
bus types commonly found in a modern PC:
o The PCI bus connects high-speed high-bandwidth
devices to the memory subsystem (and the CPU.)
o The expansion bus connects slower low-bandwidth
devices (suchas keyboard and serial/parallel ports),
which typically deliver data one character at a time
(with buffering.)
o The SCSIbus connects a number of SCSI devicesto a
common SCSI controller.
o A daisy-chain bus, (not shown) is whena string ofdevicesis connected to each other like beads on a chain, andonlyone of the
devices is directlyconnected to the host.
2
I/O Systems (Galvin Notes,9th Ed.)
In figure 13.1, In the upper-right portionof the figure, four disks are connectedtogether on a SCSI bus pluggedintoa SCSI
controller.
 A controller is a collectionof electronics that can operate a port, a bus, or a device. A serial-port controller is a simple device controller. It is a
single chip(or portionof a chip) inthe computer that controls the signals onthe wires of a serialport. Bycontrast, a SCSI bus controller is not
simple. Because the SCSI protocol is complex, the SCSI bus controller is often implemented as a separate circuit board (or a host adapter)
that plugs into the computer. It typicallycontains a processor, microcode, andsome private memoryto enable it to process the SCSI protocol
messages. Some devices have their ownbuilt-in controllers. If youlook at a disk drive, you willsee a circuit board attached to one side. This
board is the diskcontroller. It implements the diskside of the protocol for some kind of connection - SCSI or ATA, for instance. It has
microcode, and a processor to do many tasks, such as bad-sector mapping, prefetching, buffering, and caching.
 How can the processor give commands and data to a controller to accomplishan I/O transfer? The short answer is that the controller has
one or more registers for data andcontrol signals. The processor communicates withthe controller byreading and writing bit patterns in
these registers. One wayinwhich thiscommunicationcanoccur is through the use of special I/O instructions that specify the transfer of a
byte or word to an I/O port address. The I/O instructiontriggers bus lines to select the proper device and to move bits into or out of a device
register. Alternatively, the device controller cansupport memory-mappedI/O. In this case,the device-control registers are mappedinto the
address space of the processor. The CPU executesI/O requests using the standarddata-transfer instructions to read and write the device-
control registers. (From site: Memory-mapped I/O is suitable for devices which must move large quantities of data quickly, such as graphics
cards. Memory-mapped I/O can be used either
instead of or more often in combination with
traditional registers. For example, graphics cards still
use registers for control information such as setting
the video mode.)
 Some systems use both techniques. For instance,
PCs use I/O instructions to control some devices and
memory-mappedI/O to control others. Figure 13.2
shows the usual I/O port addresses for PCs. The
graphics controller has I/O ports for basic control
operations, but the controller has a large memory-
mappedregionto hold screen contents. The process
sends output to the screenbywritingdata into the
memory-mappedregion. The controller generates
the screen image based on the contents of this
memory. This technique is simple to use. Moreover,
writingmillions of bytes to the graphics memory is
faster thanissuingmillions of I/O instructions. But
the ease of writing to a memory-mappedI/O controller is offset bya disadvantage. Because a common type of software fault is a write
through anincorrect pointer to anunintendedregionof memory, a memory-mappeddevice register is vulnerable to accidentalmodification.
 An I/O port typicallyconsists of four registers, called the (1) status, (2) control, (3) data-in, and(4) data-out registers. Registers maybe one to
four bytes in size, and may typically include (a subset of) the following four.
o The data-in register is read by the host to get input.
o The data-out register is written by the host to send output.
o The status register contains bits that canbe readbythe host. These bits indicate states, suchas whether the current commandhas
completed, whether byte is available to be read from the data -in register, and whether a device error has occurred.
o The control register can be writtenbythe host to start a commandor to change the mode of a device. For instance, a certainbit in
the control register of a serial port chooses between full-duplex and half-duplex communication, another bit enables parity
checking, a thirdbit sets the wordlengthto 7 or 8 bits, and other bits select one of the speeds supported by the serial po rt.
Polling
 The complete protocol for interactionbetweenthe host anda controller canbe intricate, but the basic handshaking notion is simple. We
explainhandshakingwith an example. We assume that 2 bits are used to coordinate the producer-consumer relationship between the
controller andthe host. The controller indicates its state through the busy bit in the status register (set means 1, clear means 0). The
controller sets the busybit whenit is busyworkingandclears the busybit when it is readyto accept the next command. The host signals its
wishes via the command-readybit inthe command register. The host sets the command-ready bit when a command is available for the
controller to execute. For this example, the host writes output through a port, coordinating with the controller byhandshaking as follows:
o The host repeatedly reads the busy bit until that bit becomes clear.
o The host sets the write bit in the command register and writes a byte into the data-out register.
o The host sets the command-ready bit.
o When the controller notices that the command-ready bit is set, it sets the busy bit.
o The controller reads the commandregister andseesthe write command. It reads the data-out register to get the byte and does
the I/O to the device.
o The controller clears the command-readybit, clears the error bit inthe status register to indicate that the device I/O succeeded,
and clears the busy bit to indicate that it is finished.
This loop is repeated for each byte.
 In step1, the host is busy-waiting or polling: It is in a loop, readingthe status register over and over until the busybit becomes clear. If the
controller anddevice are fast, this methodis a reasonable one. But if the wait maybe long, the host shouldprobablyswitch to another task.
How, then, does the host knowwhenthe controller hasbecome idle?For some devices, the host must service the device quickly, or data will
3
I/O Systems (Galvin Notes,9th Ed.)
be lost. For instance, whendata are streaming in ona serialport or from a keyboard, the small buffer on the controller wil l overflow and
data will be lost if the host waits too long before returning to read the bytes.
 In manycomputer architectures, three CPU-instructioncycles are sufficient to poll a device: read a device register, logical-and to extract a
status bit, and branch if not zero. Clearly, the basic pollingoperationis efficient. But polling becomes inefficient when it is attempted
repeatedlyyet rarelyfinds a device to be readyfor service, while other useful CPU processing remains undone. Insuchinsta nces, it may be
more efficient to arrange for the hardware controller to notifythe CPU whenthe device becomes readyfor service, rather tha n to require
the CPU to poll repeatedly for an I/O completion. The hardware mechanism that enables to notify the CPU is calle d an interrupt.
Interrupts
 The basic interrupt mechanism works as follows. The CPU hardware
has a wire called the interrupt-request line that the CPU senses after
executingeveryinstruction. Whenthe CPU detects that a controller
has asserteda signal on the interrupt request line, the CPU performs
a state save and jumps to the interrupt-handler routine at a fixed
address in memory. The interrupt handler determines the cause of
the interrupt, performs the necessaryprocessing, performs a state
restore, and executes a return from interrupt instruction to
return the CPU to the execution state prior to the interrupt. We say
that the device controllers raisesaninterrupt byassertinga signalon
the interrupt request line, the CPU catches the interrupt and
dispatches it to the interrupt handler, and the handler clears the
interrupt by servicing the device. Figure 13.3 summarizes the
interrupt-driven I/O cycle.
 This basic interrupt mechanismenables the CPU to respond to an
asynchronous even, as whena device controller becomes ready for
service. In a modern operating system, however, we need more
sophisticated interrupt handling features.
o We needthe ability to defer interrupt handling during
critical processing.
o We need an efficient way to dispatch to the proper
interrupt handler for a device without first poling all the
devices to see which one raised the interrupt.
o We need multilevel interrupts, so that the operating
systemcan distinguish between high-and low-priority
interrupts and can respond with the appropriate degree of urgency
In modern computer hardware, these three features are provided by the CPU and by the interrupt-controller hardware.
 Most CPUs have two interrupt request lines. One is the nonmaskable interrupt, whichis reservedfor events suchas uncrecoverable memory
errors. The secondinterrupt line is maskable:It canbe turnedoff bythe CPU before the executionof critical instructionsequencesthat must
not be interrupted. The maskable interrupt is used by device controllers to request service.
 The interrupt mechanism accepts an address—a number that selects a specific interrupt-handling routine from a small set. In most
architectures, this addressis anoffset ina table called the interrupt vector.
This vector contains the memoryaddressesof specializedinterrupt handlers.
The purpose of a vectoredinterrupt mechanism is to reduce the need for a
single interrupt handler to search all possible sources of interrupts to
determine which one needs service. In practice, however, computers have
more devices (and, hence, interrupt handlers) than they have address
elements inthe interrupt vector. A common wayto solve this problem is to
use interrupt chaining, in whicheach element inthe interrupt vector points to
the headof a list of interrupt handlers. When an interrupt is raised, the
handlers on the corresponding list are called one by one, until one is found
that can service the request. This structure is a compromise between the
overheadof a huge interrupt table and the inefficiency of dispatching to a
single interrupt handler.
 Figure 13.4 illustrates the designof the interrupt vector for the Intel Pentium
processor. The events from0 to 31, which are nonmaskable, are usedto signal
various error conditions. The events from32 to 255, which are maskable, are
used for purposes such as device-generated interrupts.
 The interrupt mechanism also implements a system of interrupt priority
levels. These levels enable the CPU to defer the handling of low-priority
interrupts without masking all interrupts andmakesit possible for a high priority interrupt to preempt the execution of a low-priority
interrupt.
 A modern operating systeminteracts withthe interrupt mechanism in several ways. At boot time, the operating system probes t he
hardware buses to determine what devices are present and installs the corresponding interrupt handlers into the interrupt vector.
 During I/O, the various device controllers raise interrupts when they are ready for service. These interrupts signify that ou tput has
completed, or that input data are available, or that a failure has beendetected. The interrupt mechanism is also used to handle a wide
varietyof exceptions, such as dividing by0, accessing a protectedor nonexistent memoryaddress, or attempting to execute a privileged
instruction from user mode.
4
I/O Systems (Galvin Notes,9th Ed.)
 An operatingsystemhas other good uses for an efficient hardware and software mechanismthat saves a small amount of processor state
and then callsa privileged routine inthe kernel. For example, manyoperatingsystems use the interrupt mechanism for virtua l memory
paging. A page fault is an exceptionthat raises an interrupt. The interrupt suspends the current process andjumps to the page-fault handler
in the kernel. This handler saves the state of the process, moves the process to the wait queue, performs page -cache management,
schedules anI/O operationto fetch the page, schedules another process to resume execution, and then returns from the interrupt.
 An operatingsystemhas other good uses for an efficient hardware and software mechanismthat saves a small amount of process or state
and then callsa privileged routine inthe kernel. For example, manyoperatingsystems use the interrupt mechanism for virtua l memory
paging. A page fault is an exceptionthat raises an interrupt. The interrupt suspends the current process andjumps to the page-fault handler
in the kernel. This handler saves the state of the process, moves the process to the wait queue, performs page -cache management,
schedules anI/O operationto fetch the page, schedules another process to resume execution, and then returns from the interrupt.
 Another example is foundinthe implementationof system calls. Usually, a program uses library calls to issue system calls. The library
routines checkthe arguments givenbythe application, build a data structure to conveythe arguments to the kernel, and then execute a
specialinstruction calleda software interrupt, or trap. This instructionhas anoperandthat identifies the desired kernel service. When a
process executesthe trapinstruction, the interrupt hardware saves the state ofthe user code, switches to kernel mode, and dispatches to
the kernel routine that implements the requestedservice. The trapis givena relativelylowinterrupt prioritycomparedwith those assigned
to device interrupts—executinga system call onbehalf ofanapplicationis less urgent than servicing a device controller before its FIFO
queue overflows and loses data.
 Interrupts canalsobe usedto manage the flow of control withinthe kernel. For example, consider one example of the process ing required
to complete a diskread. One stepis to copydata fromkernel space to the user buffer. Thiscopying is time consuming but no t urgent—it
should not block other high-priorityinterrupt handling. Another stepis to start the next pending I/O for that disk drive. This step has higher
priority. Ifthe disks are to be used efficiently, we needto start the next I/O as soonas the previous one completes. Conse quently, a pair of
interrupt handlers implements the kernel code that completes a diskread. The high-priorityhandler records the I/O status, clears the device
interrupt, starts the next pending I/O, andraises a low-priorityinterrupt to complete the work. Later, when the CPU is not occupied with
high prioritywork, the low-priorityinterrupt willbe dispatched. The corresponding handler completes the user-level I/O by copying data
from kernel buffers to the application space and then calling the scheduler to place the application on the ready queue.
 A threadedkernel architecture is well suitedto implement multiple interrupt priorities and to enforce the precedence of interrupt handling
over backgroundprocessing in kernel andapplicationroutines. We illustrate this point withthe Solaris kernel. InSolaris, interrupt handlers
are executedas kernel threads. A range of high prioritiesis reservedfor these threads. These priorities give interrupt handlers precedence
over application code andkernel housekeepingandimplement the priorityrelationships among interrupt handlers. The priorities cause the
Solaris threadscheduler to preempt low priorityinterrupt handlers in favor of higher-priority ones, and the threaded implementation
enables multiprocessor hardware to run several interrupt handlers concurrently. We describe the interrupt architecture of Windows XP and
UNIX in Chapter 19 and Appendix A, respectively.
 In summary, interrupts are used throughout modern operating systems to handle asynchronous events and to trap to supervisor-mode
routines inthe kernel. To enable the most urgent workto be done first, modern computers use a system of interrupt priorities. Device
controllers, hardware faults, andsystemcallsall raise interrupts to trigger kernelroutines. Because interrupts are used s o heavily for time-
sensitive processing, efficient interrupt handling is required for good system performance.
Directory Memory Access
 For a device that does large transfers, such as a diskdrive, it seems wasteful to use anexpensive general-purpose processor to watch status
bits andto feed data into a controller register one byte at a time—a process termed programmed I/O (PIO). Many computers avoid
burdening the mainCPU with PIO byoffloadingsome ofthis work to a special -purpose processor called a direct-memory-access (DMA)
controller.
 To initiate a DMA transfer, the host writes a DMA commandblock into memory. This block contains a pointer to the source of a transfer, a
pointer to the destinationof the transfer, anda count of the number of bytes to be transferred. The CPU writes the address of this command
block to the DMA controller, thengoes onwithother work. The DMA controller proceeds to operate the memory bus directly, pl acing
addresses onthe bus to perform transfers without the helpof the mainCPU. A simple DMA controller is a standardcomponent inall modern
computers, from smartphones to mainframes.
 Handshaking between the DMA controller and the device controller is performed via a pair of wires called DMA-request and DMA-
acknowledge. The device controller places a signal onthe DMA-request wire when a wordof data is available for transfer. Thissignal causes
the DMA controller to seize the memorybus, place the desired address on the memory-address wires, and place a signal on the DMA-
acknowledge wire. Whenthe device controller receives the DMA-acknowledge signal, it transfers the word ofdata to memoryand removes
the DMA-request signal.
 When the entire transfer is finished, the DMA controller interrupts the
CPU. This process is depictedinFigure 13.5. When the DMA controller
seizes the memory bus, the CPU is momentarily prevented from
accessing mainmemory, althoughit can still access data items in its
primaryandsecondary caches. Although this cycle stealing can slow
down the CPU computation, offloadingthe data-transfer work to a DMA
controller generally improves the total system performance.
 Some computer architectures use physical memoryaddresses for DMA,
but others perform direct virtual memory access (DVMA), using virtual
addresses that undergotranslation to physical addresses. DVMA can
perform a transfer betweentwo memory-mappeddevices without the
intervention of the CPU or the use of main memory.
 On protected-mode kernels, the operating system generally prevents
processes fromissuingdevice commands directly. Thisdiscipline protects
data fromaccess-control violations andalso protects the system from
5
I/O Systems (Galvin Notes,9th Ed.)
erroneous use of device controllers that could cause a system crash. Instead, the operating system exports functions that a sufficiently
privilegedprocess canuse to access low-level operations onthe underlying hardware. On kernels without memoryprotection, processescan
access device controllers directly. Thisdirect accesscanbe usedto achieve highperformance, since it can avoid kernel commun ication,
context switches, andlayers of kernelsoftware. Unfortunately, it interferes withsystemsecurityand stability. The trendingeneral-purpose
operatingsystems is to protect memoryanddevices so that the system can try to guard against erroneous or malicious applica tions.
I/O Hardware Summary
 Although the hardware aspects ofI/O are complex whenconsidered at the level of detail of electronics-hardware design, the concepts that
we have just described are sufficient to enable us to understand manyI/O features of operating systems. Let’s review the mai n concepts:
• A bus • A controller • An I/O port andits registers • The handshaking relationship between the host and a device controller • The
executionof this handshakingina pollingloop or via interrupts • The offloading of this work to a DMA controller for large transfers
 We gave a basic example of the handshakingthat takes place betweena device controller and the host earlier in this section. In reality, the
wide varietyof available devicesposes a problem for operating-system implementers. Eachkindof device has its own set of capabilities,
control-bit definitions, andprotocols for interacting withthe host—andtheyare alldifferent. How canthe operating system be designed so
that we canattach newdevicesto the computer without rewriting the operating system? Andwhenthe devices varysowidely, h ow can the
operating system give a convenient, uniform I/O interface to applications? We address those questions next.
APPLICATIONI/O INTERFACE
Continuing from the last line ofthe previous section, in this section, we
discuss structuring techniquesandinterfacesfor the operating system that
enable I/O devicesto be treatedina standard, uniformway. We explain, for
instance, how an applicationcanopena file on a diskwithout knowing what
kind of diskit is andhownew disks and other devices can be added to a
computer without disruption of the operating system.
 Like other complex software-engineeringproblems, the approach
here involves abstraction, encapsulation, and software layering.
Specifically, we canabstract awaythe detaileddifferences in I/O
devices byidentifyinga few general kinds. Each general kind is
accessed througha standardized set of functions —an interface.
The differencesare encapsulatedin kernel modules called device
drivers that internallyare custom-tailoredto specific devices but
that export one of the standard interfaces. Figure 13.6 illustrates
how the I/O-related portions of the kernel are structured in
software layers.
 The purpose of the device-driver layer is to hide the differences amongdevice controllers fromthe I/O subsystem of the kernel, muchas the
I/O system callsencapsulate the behaviour of devices in a few generic classes that hide hardware differences fromapplications. Making the
I/O subsystem independent of the hardware simplifies the job of the operating-system developer. It also benefits the hardware
manufacturers. Theyeither designnew devices to be compatible withan existing host controller interface (such as SATA), or they write
device drivers to interface the new hardware to popular operatingsystems. Thus, we canattach new peripherals to a computer without
waiting for the operating-system vendor to develop support code.
 Unfortunatelyfor device-hardware manufacturers, eachtype of operating systemhas its ownstandards for the device -driver interface. A
given device may ship with multiple device drivers —for instance, drivers for Windows, Linux, AIX, and Mac OS X.
 Devices varyon manydimensions, as illustrated in Figure 13.7. :
o Character-stream or block. A character-stream device transfers
bytes one byone, whereas a block device transfers a block of bytes
as a unit.
o Sequential or random access. A sequential device transfers data in
a fixed order determined by the device, whereas the user of a
random-accessdevice caninstruct the device to seek to any of the
available data storage locations.
o Synchronous or asynchronous. A synchronous device performs
data transfers withpredictable response times, incoordinationwith
other aspects of the system. An as ynchronous device exhibits
irregular or unpredictable response times not coordinated with
other computer events.
o Sharable or dedicated. A sharable device canbe usedconcurrently
by several processes or threads; a dedicated device cannot.
o Speed of operation. Device speeds range from a few bytes per second to a few gigabytes per second.
o Read–write, read only, or write only. Some devices perform both input andoutput, but others support only one data transfer
direction.
 For the purpose of applicationaccess, manyof these differences are hiddenbythe operating system, andthe devices are groupedintoa few
conventionaltypes. The resulting styles of device access have beenfoundto be useful and broadlyapplicable. Although the e xact system
calls maydiffer acrossoperatingsystems, the device categories are fairly standard. The major access conventions include block I/O,
character-streamI/O, memory-mappedfile access, andnetwork sockets. Operatingsystems alsoprovide specialsystem callsto accessa few
6
I/O Systems (Galvin Notes,9th Ed.)
additional devices, suchas a time-of-dayclock anda timer. Some operating systems provide a set ofsystemcallsfor graphicaldisplay, video,
and audio devices.
 Most operatingsystems alsohave an escape (or back door) that transparentlypasses arbitrarycommands fromanapplication to a device
driver. In UNIX, this system call is ioctl() (for “I/O control”). The ioctl() system call enables anapplication to access anyfunctionality that can
be implemented byanydevice driver, without the needto invent a new system call. The ioctl() systemcall has three arguments. The first is a
file descriptor that connects the applicationto the driver byreferring to a hardware device managedbythat driver. The secondis aninteger
that selects one of the commands implemented inthe driver. The thirdis a pointer to anarbitrarydata structure inmemorythat enablesthe
application and driver to communicate any necessary control information or data.
Block and Character Devices
 Block devices are accesseda blockat a time, andare indicated bya "b"as the first character ina long listing on UNIX sys tems. Operations
supported include read(), write(), and seek().
 Raw I/O and Direct I/O: Accessingblocks ona hard drive directly(without going throughthe filesystem structure) is calledraw I/O, and can
speedup certainoperations bybypassing the bufferingandlocking normally conducted by the OS. (It then becomes the applica tion's
responsibilityto manage those issues.) A new alternative is direct I/O, which uses the normal filesystem access, but whichdisables buffering
and locking operations.
 Memory-mapped file I/O can be layeredontop ofblock-device drivers. Rather thanreading in the entire file, it is mapped to a range of
memoryaddresses, andthen paged into memoryas neededusing the virtual memory system. Access to the file is then acco mplished
through normal memoryaccesses, rather thanthroughread()and write() systemcalls. This approach is commonly used for execu table
program code. Because the transfers are handled bythe same mechanism as that used for demand-pagedvirtual memory access, memory-
mappedI/O is efficient. Memorymapping is alsoconvenient for programmers—accessto a memory-mapped file is as simple as readingfrom
and writing to memory.
 Character devices are accessedone byte at a time, andare indicatedbya "c" inUNIXlonglistings. Supported operations include get() and
put(), with more advanced functionality such as reading an entire line supported by higher-level library routines.
Network Devices
 Because network access is inherentlydifferent from local diskaccess, most systems provide a separate interface for network devices. One
common andpopular interface is the socket interface, which acts like a cable or pipeline connectingtwo networked entities. Data canbe put
into the socket at one end, andreadout sequentiallyat the other end. Sockets are normallyfull-duplex, allowing for bi-directional data
transfer. The select() system call allows servers (or other applications) to identifysockets which have data waiting, without having to poll all
available sockets. (To support the implementation of servers, the socket interface alsoprovides a functioncalled select() that manages a set
of sockets. A call to select() returns informationabout whichsockets have a packet waiting to be receivedandwhich sockets have room to
accept a packet to be sent. The use of select() eliminatesthe polling andbusywaiting that wouldotherwise be necessary for network I/O.)
Clocks and Timers
Most computers have hardware clocks andtimers that provide three basic functions:• Give the current time. • Give the elapsed time. • Set a timer
to trigger operation X at time T.
 These functions are used heavilybythe operatingsystem, as well as bytime-sensitive applications. Unfortunately, the system calls that
implement these functions are not standardized across operating systems.
 The hardware to measure elapsed time and to trigger operations is called a programmable interval timer. It can be set to wait a certain
amount of time andthengenerate an interrupt, and it canbe set to do thisonce or to repeat the process to generate periodic interrupts. The
scheduler uses thismechanismto generate an interrupt that will preempt a process at the endof its time slice. The disk I/O subsystem uses
it to invoke the periodic flushingof dirtycache buffers to disk, andthe network subsystem usesit to cancel operations tha t are proceeding
too slowly because of network congestion or failures.
 The operating systemmayalsoprovide an interface for user processes to use timers. The operatingsystemcansupport more timer requests
than the number of timer hardware channelsbysimulatingvirtual clocks. To doso, the kernel (or the timer device driver) maintains a list of
interrupts wantedbyits ownroutinesandbyuser requests, sorted in earliest-time-first order. It sets the timer for the earliest time. When
the timer interrupts, the kernel signals the requester and reloads the timer with the next earliest time.
 In most computers, the hardware clockis constructedfrom a high-frequencycounter. Insome computers, the value of this counter can be
read from a device register, inwhichcase the counter canbe considered a high-resolution clock. Although this clock does not generate
interrupts, it offers accurate measurements of time intervals.
 (Site): A programmable interrupt timer, PIT can be used to trigger operations and to measure elapsed time. It can be set to trigger an
interrupt at a specific future time, or to trigger interrupts periodically on a regular basis.
o The scheduler uses a PIT to trigger interrupts for ending time slice s.
o The disk system may use a PIT to schedule periodic maintenance cleanup, such as flushing buffers to disk.
o Networks use PITto abort or repeat operations that are takingtoo long to complete. I.e. resending packets ifanacknowledgement
is not received before the timer goes off.
o More timers than actuallyexist can be simulatedbymaintaining anorderedlist of timer events, andsetting the physicaltimer to go
off when the next scheduled event should occur.
 On most systems the system clock is implementedbycountinginterrupts generated bythe PIT. Unfortunatelythis is limitedin its resolution
to the interrupt frequencyof the PIT, and maybe subject to some drift over time. An alternate approachis to provide direct accessto a high
frequency hardware counter, which provides much higher resolution and accuracy, but which does not support interrupts.
7
I/O Systems (Galvin Notes,9th Ed.)
Blocking and Non-blocking I/O (Book: Nonblocking and Asynchronous I/O)
 With blocking I/O a process is movedto the wait queue when an I/O request is made, and movedbackto the readyqueue whenthe request
completes, allowing other processes to run in the meantime.
 With non-blocking I/O the I/O request returns immediately, whether the requestedI/Ooperation has (completely ) occurred or not. This
allows the process to check for available data without getting hungcompletelyifit is not there. (The regular non-blocking I/O, as compared
to the asynchronous I/O, returns immediatelywith whatever results are available, but does not complete the operation and notify the
process later.) One approachfor programmers to implement non-blocking I/O is to have a multi-threadedapplication, in which one thread
makes blocking I/O calls (sayto reada keyboardor mouse), while other threads continue to update the screen or perform other tasks.
 A subtle variation ofthe non-blockingI/O is the asynchronous I/O, inwhichthe I/O request returns immediately allowing the process to
continue onwith other tasks, and thenthe process is notified (via changing a processvariable, or a software interrupt, or a callback function)
when the I/O operation has completed and the data is available for use.
Book
 Another aspect ofthe system-callinterface relates to the choice betweenblocking I/O and nonblockingI/O. When an application issues a
blocking system call, the executionof the applicationis suspended. The application is movedfrom the operating system’s run queue to a
wait queue. After the systemcallcompletes, the application is movedback to the runqueue, where it is eligible to resume execution. When
it resumes execution, it will receive the valuesreturnedbythe system call. The physical actions performed by I/O devices a re generally
asynchronous—theytake a varying or unpredictable amount of time. Nevertheless, most operating systems use blockingsystem callsfor the
application interface, because blocking application code is easier to understand than nonblocking application code.
 Some user-level processesneed nonblocking I/O. One example is a user interface that receives keyboardandmouse input while processing
and displaying data on the screen. Another example is a videoapplication that reads frames from a file on disk while simulta neously
decompressing anddisplayingthe output on the display. One way an application writer can overlap execution with I/O is to write a
multithreadedapplication. Some threads canperform blockingsystemcalls, while others continue executing. Some operating systems
provide nonblocking I/O system calls. A nonblocking call does not halt the executionof the application for an extended time. Instead, it
returns quickly, witha returnvalue that indicates how many bytes
were transferred.
 An alternative to a nonblocking system call is an asynchronous
systemcall. An asynchronous call returns immediately, without
waiting for the I/O to complete. The application continues to
execute its code. The completionof the I/O at some future time is
communicatedto the application, either through the setting of
some variable inthe address space of the application or through
the triggeringof a signal or software interrupt or a call-back routine
that is executedoutside the linear control flowof the application.
The difference between nonblocking andasynchronous system calls
is that a nonblocking read() returns immediately with whatever
data are available—the full number of bytes requested, fewer, or none at all. An asynchronous read() call requests a transfer that will be
performed in its entirety but will complete at some future time. These two I/O methods are shown in Figure 13.8.
 A good example ofnonblocking behavior is the select() system call for networksockets. This system call takesanargument that specifies a
maximum waitingtime. Bysettingit to 0, anapplicationcanpoll for networkactivitywithout blocking. But using select() introduces extra
overhead, because the select() call onlychecks whether I/O is possible. For a data transfer, select() must be followed bysome kindof read()
or write() command.
KERNEL I/O SUBSYSTEM
 Kernels provide manyservicesrelatedto I/O. Several services—scheduling, buffering, caching, spooling, device reservation, and error
handling—are providedbythe kernel’s I/O subsystem and build onthe hardware anddevice driver infrastructure. The I/O subsystem is
also responsible for protecting itself from errant processes and malicious users.
I/O Scheduling
 To schedule a set of I/O requests means to determine a good order inwhichto execute them. The order in which applica tions issue
systemcalls rarelyis the best choice. Scheduling canimprove overall system performance, can share device access fairly amo ng
processes, andcan reduce the average waiting time for I/O to
complete.
 Operating-system developers implement scheduling by
maintaining await queue of requests for each device. When an
applicationissues a blocking I/O systemcall, the request is placed
on the queue for that device. The I/O scheduler rearranges the
order of the queue to improve the overall system effici ency and
the average response time experienced by applications. The
operatingsystemmayalsotryto be fair, sothat no one application
receives especiallypoor service, or it maygive priority service for
delay-sensitive requests. For instance, requests from the virtual
memorysubsystem maytake priorityover application requests.
Several schedulingalgorithms for diskI/O are detailed in Section
10.4.
 When a kernel supports asynchronous I/O, it must be able to keeptrackof manyI/O requests at the same time. For this purpose, the
operatingsystemmight attachthe wait queue to a device-status table. The kernel manages this table, whichcontains anentry for each
8
I/O Systems (Galvin Notes,9th Ed.)
I/O device, as shownin Figure 13.9. Each table entryindicates the device’s type, address, a ndstate (not functioning, idle, or busy). If the
device is busy with a request, the type of request and other parameters will be stored in the table entry for that device.
 Scheduling I/O operations is one wayinwhichthe I/Osubsystem improves the effici ency of the computer. Another way is by using
storage space in main memory or on disk via buffering, caching, and spooling.
Buffering
 A buffer is a memoryarea that stores data beingtransferredbetweentwo devices or between a device and an application. Buffering is done
for three reasons. One reason is to cope with a speed mismatch between the producer and consumer of a data stream.
 Suppose, for example, that a file is being receivedvia modemfor storage on the harddisk. The modemis abou t a thousand times slower
than the hard disk. Soa buffer is created inmain memoryto accumulate the bytes receivedfrom the modem. Whenanentire buffer of data
has arrived, the buffer can be writtento diskina single operation. Since the diskwrite is not instantaneous and the modem still needs a
place to store additional incoming data, twobuffers are used. After the modemfills the first buffer, the disk write is requ ested. The modem
then starts to fillthe secondbuffer while the first buffer is writtento disk. Bythe time the modem has filledthe secondbuffer, the diskwrite
from the first one should have completed, so the modem canswitchbackto the first buffer while the diskwritesthe second o ne. Thisdouble
buffering decouplesthe producer of data fromthe consumer, thus relaxing
timing requirements betweenthem. The need for this decoupling is illustrated
in Figure 13.10, whichlists the enormous differences in device speeds for
typical computer hardware.
 A seconduse of bufferingis to provide adaptations for devices that have
different data-transfer sizes. Such disparities are especially common in
computer networking, where buffers are usedwidelyfor fragmentation and
reassemblyof messages. At the sendingside, a large message is fragmented
into small networkpackets. The packets are sent over the network, and the
receiving side places themina reassembly buffer to form an image of the
source data.
 A third use of bufferingis to support copysemantics for application I/O. For
example, whenanapplicationmakesa request for a disk write (i.e., call the
write() systemcall, the data is copied from the user's memory area into a
kernel buffer. Now the application can change their copyof the data, but the
data which eventuallygets written out to diskis the version ofthe data at the
time the write request was made.
Copying of data betweenkernel buffers andapplicationdata space is commoninoperating systems, despite the overhead that this
operationintroduces, because of the clean semantics. The same effect canbe obtained more efficiently by clever use of virtual memory
mapping and copy-on-write page protection.
Caching
 A cache is a regionof fast memorythat holds copies ofdata. Access to the cachedcopyis more efficient than access to the original. For
instance, the instructions of the currentlyrunningprocessare storedondisk, cached in physical memory, and copied again i n the CPU’s
secondaryandprimarycaches. The difference betweena buffer anda cache is that a buffer mayholdthe onlyexisting copy of a data item,
whereas a cache, by definition, holds a copy on faster storage of an item that resides elsewhere.
 Cachingandbuffering are distinct functions, but sometimes a regionof memorycan be used for bothpurpo ses. For instance, to preserve
copysemantics andto enable efficient schedulingof diskI/O, the operatingsystem uses buffers inmain memory to hold disk data. These
buffers are also used as a cache, to improve the I/O efficiencyfor files that are sharedbyapplications or that are being written and reread
rapidly. When the kernel receives a file I/O request, the kernel first accesses the buffer cache to see whether that region o fthe file is already
available inmainmemory. If it is, a physicaldiskI/O canbe avoidedor deferred. Also, disk writes are accumulated in the buffer cache for
several seconds, so that large transfers are gatheredto allowefficient write schedules. This strategy of delaying writes to improve I/O
efficiency is discussed, in the context of remote file access, in Section 17.9.2.
Spooling and Device Reservation
 A spool is a buffer that holds output for a device, suchas a printer, that cannot accept interleaved data streams. Although a printer canserve
onlyone jobat a time, several applications maywishto print their output concurrently, without having their output mixed together. The
operatingsystemsolves thisproblem byinterceptingall output to the printer. Eachapplication’s output is spooled to a sep arate disk file.
When anapplicationfinishes printing, the spooling system queues the correspondingspool file for output to the printer. The spoolingsystem
copies the queuedspool files to the printer one at a time. In some operating systems, spooling is managedbya system daemon process. In
others, it is handled byanin-kernel thread. Ineither case, the operatingsystem providesa control interface that enables users and system
administrators to displaythe queue, remove unwantedjobs before those jobs print, suspend printing while the printer is serviced, and soon.
 Some devices, suchas tape drives andprinters, cannot usefullymultiplex the I/Orequests of multiple concurrent applications. Spooling is
one wayoperating systems can coordinate concurrent output. Another wayto deal withconcurrent device access is to provide explicit
facilitiesfor coordination. Some operatingsystems provide support for exclusive device access, other operating systems enforce a limit of
one openfile handle to sucha device. Manyoperating systems provide functions that enable processes to coordinate exclusive access
among themselves.
9
I/O Systems (Galvin Notes,9th Ed.)
Error Handling
 Error Handling I/O requests canfailfor manyreasons, either transient (buffers overflow)or permanent (disk crash). I/O req uests usually
return an error bit (or more)indicating the problem. UNIXsystems also set the global variable errno to one of a hun dred or so well-defined
values to indicate the specific error that has occurred. (See errno.h for a complete listing, or manerrno.)Some devices, suchas SCSI devices,
are capable ofproviding muchmore detailedinformationabout errors, andevenkeep an on-boarderror logthat can be requested by the
host (For instance, a failure of a SCSI device is reported by the SCSI protocol in three levels of detail...).
I/O Protection
 To prevent users fromperforming illegal I/O,we define all I/O instructions to be privileged instructions. Thus, users cannot issue I/O
instructions directly;theymust doit throughthe operatingsystem. To do I/O, a user program executes a system call to requ est that the
operatingsystemperformI/O onits behalf. The operating system, executing inmonitor mode, checks that the request is valid and, if it is,
does the I/O requested. The operating system then returns to the user.
 In addition, anymemory-mapped and I/O port memorylocations must be protectedfrom user access by the memory-protection system.
Note that a kernel cannot simplydenyall user access. Most graphics games andvideo editing andplayback software need direct access to
memory-mappedgraphics controller memoryto speedthe performance
of the graphics, for example. The kernel might in this case provide a
lockingmechanismto allow a sectionof graphics memory(representing a
window on screen) to be allocated to one process at a time.
Kernel Data Structures
 The kernelmaintains a number of important data structures pertaining
to the I/O system, suchas the open file table (fromSection12.1, 9th Ed).
These structures are object-oriented, and flexible to allow access to a
wide varietyof I/O devices through a common interface. (See Figure
13.12 below.) Windows NT carries the object-orientation one step
further, implementingI/O as a message-passingsystemfrom the source
through various intermediaries to the device.
Kernel I/O Subsystem Summary
 In summary, the I/O subsystemcoordinates an extensive collection of
services that are available to applications andto other parts of the kernel. The I/O subsystem supervises these procedures:
• Management of the name space for filesanddevices
• Access control to files and devices
• Operationcontrol (for example, a modem cannot seek())
• File-system space allocation
• Device allocation
• Buffering, caching, andspooling
• I/O scheduling
• Device-status monitoring, error handling, andfailure recovery
• Device-driver configurationandinitialization
The upper levelsof the I/O subsystem access devices via the uniform interface providedbythe device drivers.
TRANSFORMING I/O REQUESTS TO HARDWARE OPERATIONS
 Earlier, we describedthe handshakingbetweena device driver and a device controller, but we did not explain how the operating system
connects an application request to a set of network wires or to a specific disk sector.
 Consider, for example, reading a file from disk. The applicationrefers to the data bya file name. Withina disk, the file s ystemmaps from the
file name throughthe file-systemdirectoriesto obtain the space allocation ofthe file. For instance, inMS-DOS, the name maps to a number
that indicatesanentryin the file-accesstable, andthat table entrytells which disk blocks are allocatedto the file. InUNIX, the name maps
to an inode number, andthe corresponding inode contains the space-allocation information. But how is the connectionmade from the file
name to the disk controller (the hardware port address or the memory-mapped controller registers)?
 One methodis that usedbyMS-DOS, a relativelysimple operating system. The first part of anMS-DOSfile name, preceding the colon, is a
string that identifiesa specific hardware device. For example, C:is the first part of everyfile name onthe primaryhard disk. The fact that C:
represents the primaryhard diskis built into the operating system; C:is mappedto a specific port address througha device table. Because
of the colon separator, the device name space is separate from the file-system name space. This separation makes it easyfor the operating
system to associate extra functionality with each device.
 If, instead, the device name space is incorporated inthe regular file-system name space, as it is in UNIX, the normal file -system name
services are provided automatically. If the file systemprovides ownershipandaccess control to all file names, thendevices have owners and
access control. Since files are stored ondevices, suchaninterface provides access to the I/O system at two levels. Names can be used to
access the devices themselves or to access the files stored on the devices.
 UNIXrepresents device names in the regular file-systemname space. Unlike an MS-DOS filename, which has a colonseparator, a UNIX path
name has noclear separation ofthe device portion. In fact, nopart of the pathname is the name of a device. UNIX has a mount table that
associates prefixes of pathnames withspecific device names. To resolve a pathname, UNIXlooks up the name in the mount table to find
the longest matching prefix;the corresponding entryin the mount table gives the device name. This device name also has the form of a
10
I/O Systems (Galvin Notes,9th Ed.)
name inthe file-systemname space. WhenUNIXlooks upthis name inthe file-system directorystructures, it finds not aninode number but
a<major, minor>device number. The major device number identifies a device driver that should be calledto handle I/O to this device. The
minor device number is passedto the device driver to index into a device table. The corresponding device-table entrygives the port address
or the memory-mapped address of the device controller.
 Modern operatingsystems gainsignificant flexibility from the
multiple stages of lookuptables inthe pathbetween a request
and a physical device controller. The mechanisms that pass
requests betweenapplications and drivers are general. Thus, we
can introduce new devices and drivers intoa computer without
recompiling the kernel. Infact, some operating systems have
the abilityto load device drivers on demand. At boot time, the
systemfirst probes the hardware buses to determine what
devices are present. It thenloads inthe necessarydrivers, either
immediately or when first required by an I/O request.
 We next describe the typical life cycle ofa blocking read
request, as depictedinFigure 13.13. The figure suggests that an
I/O operationrequiresa great manysteps that together
consume a tremendous number of CPU cycles.
1. A process issues a blocking read()systemcallto a file
descriptor of a file that has beenopenedpreviously.
2. The system-callcode inthe kernel checks the parameters for
correctness. In the case of input, if the data are alreadyavailable
in the buffer cache, the data are returnedto the process, and
the I/O request is completed.
3. Otherwise, a physical I/O must be performed. The processis
removed fromthe run queue andis placed onthe wait queue
for the device, andthe I/O request is scheduled. Eventually, the
I/O subsystem sends the request to the device driver.
Depending onthe operatingsystem, the request is sent via a
subroutine call or anin-kernelmessage.
4. The device driver allocates kernel buffer space to receive the
data andschedules the I/O. Eventually, the driver sends
commands to the device controller bywriting intothe device-
control registers.
5. The device controller operates the device hardware to
perform the data transfer.
6. The driver maypoll for status anddata, or it mayhave set up
a DMA transfer into kernel memory. We assume that the
transfer is managedbya DMA controller, which generates an
interrupt whenthe transfer completes.
7. The correct interrupt handler receives the interrupt via the
interrupt vector table, stores anynecessarydata, signals the device driver, and returns from the interrupt.
8. The device driver receives the signal, determines which I/O request has completed, determines the request’s status, andsignals the
kernel I/O subsystemthat the request has beencompleted.
9. The kernel transfers data or returncodesto the address space ofthe requesting process andmoves the process fromthe wait q ueue back
to the readyqueue.
10. Moving the process to the readyqueue unblocks the process. Whenthe scheduler assigns the processto the CPU, the process resumes
executionat the completion ofthe systemcall.
PERFORMANCE
 I/O is a major factor insystemperformance. It placesheavydemands onthe CPU to execute device-driver code and to schedule processes
fairlyand efficientlyas theyblock andunblock. The resulting context switches stress the CPU andits hardware caches. I/O also exposes any
inefficiencies in the interrupt-handling mechanisms inthe kernel. Inaddition, I/O loads downthe memorybus duringdata copies between
controllers and physicalmemoryandagainduring copiesbetweenkernel buffers andapplicationdata space. Coping gracefullywi thall these
demands is one of the major concerns of a computer architect.
 Although modern computers canhandle manythousands of interrupts per second, interrupt handling is a relatively expensive task. Each
interrupt causesthe systemto performa state change, to execute the interrupt handler, andthen to restore state. Programmed I/O can be
more efficient thaninterrupt-drivenI/O, if the number of cycles spent in busywaiting is not excessive. An I/O completiontypicallyunblocks a
process, leading to the full overhead of a context switch.
 (Refer the Network Traffic case in “Assorted Content” to better consolidate what you have read).
 ****(To quote from Wiki): Memory-mapped I/O (not to be confused withmemory-mapped file I/O)uses the same addressbus to address
both memoryandI/O devices – the memoryand registers ofthe I/O devices are mappedto (associatedwith) address val ues. In memory-
mappedI/O, the CPU instructions used to access the memorycan also be used for accessing devices. Each I/O device monitors the CPU's
address bus andresponds to anyCPU access of anaddress assigned to that device, connectingthe data bus to the desireddevice's hardware
register.
 ***Readthe port-mappedI/O (PMIO) (whichis also calledisolatedI/O)vs Memory-mapped I/O (MMIO)content from Wiki. These two are
complementary (similar).
11
I/O Systems (Galvin Notes,9th Ed.)
 Other systems use separate front-endprocessors for terminal I/O to reduce the interrupt burden onthe mainCPU. For instance, a terminal
concentrator can multiplex the traffic fromhundreds of remote terminals into one port on a large computer. An I/O channel is a dedicated,
special-purpose CPU found in mainframes and inother high-endsystems. The jobof a channel is to offloadI/O work from the mainCPU. The
idea is that the channels keepthe data flowingsmoothly, while the mainCPU remains free to processthe data. Like the device controllers
and DMA controllers found insmaller computers, a channel can process more general and sophisticatedprograms, so channelscanbe tuned
for particular workloads.
 We can employ several principles to improve the efficiency of I/O:
• Reduce the number of context switches.
• Reduce the number of times that data must be copied in memory while passing between device and application.
• Reduce the frequency of interrupts by using large transfers, smart controllers, and polling (if busy waiting can be minimized).
• Increase concurrency by using DMA-knowledgeable controllers or channels to offload simple data copying from the CPU.
• Move processingprimitives into hardware, to allowtheir operationin device controllers to be concurrent with CPU and bus operation.
• Balance CPU, memorysubsystem, bus, and I/O performance, because an overload in any one area will cause idleness in others.
 I/O devices varygreatlyincomplexity. For instance, a mouse is simple. The mouse movements andbuttonclicks are converted into numeric
values that are passed fromhardware, throughthe mousedevice driver, to the application. Bycontrast, the functionality provided by the
Windows disk device driver is complex. It not onlymanages individual disks but also implements RAID arrays (Section 10.7). To do so, it
converts an application’s reador write request intoa coordinated set of disk I/O operations. Moreover, it implements sophis ticated error-
handling and data-recovery algorithms and takes many steps to optimize disk performance.
 Where should the I/O functionalitybe implemented—inthe device hardware, inthe device driver, or inapplication software?Sometimeswe
observe the progression depicted in Figure 13.16.
o Initially, we implement experimentalI/O algorithms at the application level, because applicationcode is flexible and application
bugs are unlikelyto cause system crashes. Furthermore, bydevelopingcode at the applicationlevel, we avoidthe need to reb oot
or reload device drivers after everychange to the code. An application-level implementationcan be inefficient, however, because
of the overheadof context switches andbecause the application
cannot take advantage of internal kernel data structures andkernel
functionality(suchas efficient in-kernelmessaging, threading, and
locking).
o When an application-level algorithmhas demonstratedits worth,
we mayreimplement it inthe kernel. Thiscanimprove
performance, but the development effort is more challenging,
because anoperating-system kernelis a large, complex software
system. Moreover, an in-kernel implementationmust be
thoroughlydebuggedto avoiddata corruptionandsystemcrashes.
o The highest performance maybe obtained througha specialized
implementationinhardware, either in the device or inthe
controller. The disadvantages of a hardware implementation
include the difficultyandexpense of making further improvements
or of fixingbugs, the increased development time (months rather thandays), andthe decreasedflexibility. For instance, a
hardware RAID controller maynot provide anymeans for the kernel to influence the order or location ofindividualblockreads and
writes, even if the kernel has special informationabout the workloadthat wouldenable it to improve the I/O performance.
SUMMARY
 The basic hardware elements involvedinI/O are buses, device controllers, andthe devices themselves. The work of moving data between
devices andmainmemoryis performed bythe CPU as programmedI/O or is offloadedto a DMA controller. The kernel module that controls
a device is a device driver. The system-callinterface providedto applications is designed to handle several basic categories of hardware,
includingblock devices, character devices, memory-mappedfiles, network sockets, and programmedinterval timers. The system calls usually
block the processes that issue them, but nonblocking andasynchronous calls are used bythe kernel itself andbyapplications that must not
sleep while waiting for an I/O operation to complete.
 The kernel’s I/O subsystem provides numerous services. Among these are I/O scheduling, buffering, caching, spooling, device reservation,
and error handling. Another service, name translation, makes the connections betweenhardware devices andthe symbolic file names used
byapplications. It involves several levelsof mappingthat translate from character-string names, to specific device drivers and device
addresses, and thento physical addresses of I/O ports or bus controllers. Thismapping mayoccur withinthe file-system name space, as it
does in UNIX, or in a separate device name space, as it does in MS-DOS.
 I/O system callsare costlyinterms of CPU consumption because of the many layers of software between a physical device and an
application. These layers implyoverhead fromseveral sources:context switching to cross the kernel’s protection boundary, s ignal and
interrupt handling to service the I/O devices, and the load on the CPU and memory system to copy data between kernel buffers and
application space.
12
I/O Systems (Galvin Notes,9th Ed.)
AssortedContent
 Network traffic canalsocause a high context-switch rate. Consider, for
instance, a remote login from one machine to another. Each character
typed on the local machine must be transportedto the remote machine.
On the local machine, the character is typed; a keyboard interrupt is
generated;andthe character is passedthroughthe interrupt handler to
the device driver, to the kernel, and then to the user process. The user
process issues a network I/O system call to send the character to the
remote machine. The character then flows into the local kernel, through
the network layers that construct a network packet, andintothe network
device driver. The network device driver transfers the packet to the
network controller, whichsends the character andgeneratesaninterrupt.
The interrupt is passed back upthroughthe kernelto cause the network
I/O system call to complete. Now, the remote system’s networkhardware
receives the packet, and an interrupt is generated. The character is
unpackedfrom the network protocols and is given to the appropriate
network daemon. The networkdaemon identifies which remote login
sessionis involved and passes the packet to the appropriate subdaemon
for that session. Throughout this flow, there are context switches and
state switches(Figure 13.15). Usually, the receiver echoes the character
back to the sender;that approach doubles the work. To eliminate the
context switches involved in movingeach character between daemons
and the kernel, the Solarisdevelopers reimplemented the telnet daemon
using in-kernel threads. Sun estimatedthat this improvement increased
the maximum number of network logins from a few hundred to a few
thousand on a large server.

More Related Content

What's hot

Chp3 designing bus system, memory & io copy
Chp3 designing bus system, memory & io   copyChp3 designing bus system, memory & io   copy
Chp3 designing bus system, memory & io copymkazree
 
SYBSC IT SEM IV EMBEDDED SYSTEMS UNIT II Embedded Systems Memory
SYBSC IT SEM IV EMBEDDED SYSTEMS UNIT II  Embedded Systems MemorySYBSC IT SEM IV EMBEDDED SYSTEMS UNIT II  Embedded Systems Memory
SYBSC IT SEM IV EMBEDDED SYSTEMS UNIT II Embedded Systems MemoryArti Parab Academics
 
Input Output Organization
Input Output OrganizationInput Output Organization
Input Output OrganizationKamal Acharya
 
Memory & I/O interfacing
Memory & I/O  interfacingMemory & I/O  interfacing
Memory & I/O interfacingdeval patel
 
Pin diagram of 8085
Pin diagram of 8085Pin diagram of 8085
Pin diagram of 8085ShivamSood22
 
1.microprocessor
1.microprocessor1.microprocessor
1.microprocessorraja p
 
Io processing
Io processingIo processing
Io processingTech_MX
 
Microprocessor & Interfacing (Part-1) By Er. Swapnil V. Kaware
Microprocessor & Interfacing (Part-1) By Er. Swapnil V. KawareMicroprocessor & Interfacing (Part-1) By Er. Swapnil V. Kaware
Microprocessor & Interfacing (Part-1) By Er. Swapnil V. KawareProf. Swapnil V. Kaware
 
Input Output Operations
Input Output OperationsInput Output Operations
Input Output Operationskdisthere
 
Assembly Language
Assembly LanguageAssembly Language
Assembly LanguageVijay Kumar
 
Microprocessor & Interfacing (Part-2) By Er. Swapnil V. Kaware
Microprocessor & Interfacing (Part-2) By Er. Swapnil V. KawareMicroprocessor & Interfacing (Part-2) By Er. Swapnil V. Kaware
Microprocessor & Interfacing (Part-2) By Er. Swapnil V. KawareProf. Swapnil V. Kaware
 
Data transfer techniques 8085
Data transfer techniques 8085Data transfer techniques 8085
Data transfer techniques 8085ShivamSood22
 
Microprocessors-based systems (under graduate course) Lecture 5 of 9
Microprocessors-based systems (under graduate course) Lecture 5 of 9 Microprocessors-based systems (under graduate course) Lecture 5 of 9
Microprocessors-based systems (under graduate course) Lecture 5 of 9 Randa Elanwar
 
Microprocessor 8086
Microprocessor 8086Microprocessor 8086
Microprocessor 8086Waleed Khan
 

What's hot (19)

Chp3 designing bus system, memory & io copy
Chp3 designing bus system, memory & io   copyChp3 designing bus system, memory & io   copy
Chp3 designing bus system, memory & io copy
 
Unit 5
Unit 5Unit 5
Unit 5
 
SYBSC IT SEM IV EMBEDDED SYSTEMS UNIT II Embedded Systems Memory
SYBSC IT SEM IV EMBEDDED SYSTEMS UNIT II  Embedded Systems MemorySYBSC IT SEM IV EMBEDDED SYSTEMS UNIT II  Embedded Systems Memory
SYBSC IT SEM IV EMBEDDED SYSTEMS UNIT II Embedded Systems Memory
 
Input Output Organization
Input Output OrganizationInput Output Organization
Input Output Organization
 
Memory & I/O interfacing
Memory & I/O  interfacingMemory & I/O  interfacing
Memory & I/O interfacing
 
Pin diagram of 8085
Pin diagram of 8085Pin diagram of 8085
Pin diagram of 8085
 
1.microprocessor
1.microprocessor1.microprocessor
1.microprocessor
 
Io processing
Io processingIo processing
Io processing
 
Io pro
Io proIo pro
Io pro
 
Microprocessor & Interfacing (Part-1) By Er. Swapnil V. Kaware
Microprocessor & Interfacing (Part-1) By Er. Swapnil V. KawareMicroprocessor & Interfacing (Part-1) By Er. Swapnil V. Kaware
Microprocessor & Interfacing (Part-1) By Er. Swapnil V. Kaware
 
Interface
InterfaceInterface
Interface
 
Input Output Operations
Input Output OperationsInput Output Operations
Input Output Operations
 
Assembly Language
Assembly LanguageAssembly Language
Assembly Language
 
IO hardware
IO hardwareIO hardware
IO hardware
 
Microprocessor & Interfacing (Part-2) By Er. Swapnil V. Kaware
Microprocessor & Interfacing (Part-2) By Er. Swapnil V. KawareMicroprocessor & Interfacing (Part-2) By Er. Swapnil V. Kaware
Microprocessor & Interfacing (Part-2) By Er. Swapnil V. Kaware
 
Data transfer techniques 8085
Data transfer techniques 8085Data transfer techniques 8085
Data transfer techniques 8085
 
Microprocessors-based systems (under graduate course) Lecture 5 of 9
Microprocessors-based systems (under graduate course) Lecture 5 of 9 Microprocessors-based systems (under graduate course) Lecture 5 of 9
Microprocessors-based systems (under graduate course) Lecture 5 of 9
 
Microprocessor 8086
Microprocessor 8086Microprocessor 8086
Microprocessor 8086
 
Important questions
Important questionsImportant questions
Important questions
 

Similar to Io systems final

IOhardware_operting_systems_2022_libya.pdf
IOhardware_operting_systems_2022_libya.pdfIOhardware_operting_systems_2022_libya.pdf
IOhardware_operting_systems_2022_libya.pdfaptinstallpython3
 
IO and file systems
IO and file systems IO and file systems
IO and file systems EktaVaswani2
 
UNIT 5- UNDERSTANDING THE SYSTEM DESIGN PROCESS.pptx
UNIT 5- UNDERSTANDING THE SYSTEM DESIGN PROCESS.pptxUNIT 5- UNDERSTANDING THE SYSTEM DESIGN PROCESS.pptx
UNIT 5- UNDERSTANDING THE SYSTEM DESIGN PROCESS.pptxLeahRachael
 
The primary purpose of memory interfacing is to facilitate the transfer of da...
The primary purpose of memory interfacing is to facilitate the transfer of da...The primary purpose of memory interfacing is to facilitate the transfer of da...
The primary purpose of memory interfacing is to facilitate the transfer of da...Sindhu Mani
 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organizationchidabdu
 
Input output accessing
Input output accessingInput output accessing
Input output accessingankitraosingh
 
I/O Hardware-R.D.Sivakumar
I/O Hardware-R.D.SivakumarI/O Hardware-R.D.Sivakumar
I/O Hardware-R.D.SivakumarSivakumar R D .
 
CO--MODULE-1 (b) - Input-Output-Organization.pptx
CO--MODULE-1 (b) - Input-Output-Organization.pptxCO--MODULE-1 (b) - Input-Output-Organization.pptx
CO--MODULE-1 (b) - Input-Output-Organization.pptxahmedsalik057
 
Unit2 p1 io organization-97-2003
Unit2 p1 io organization-97-2003Unit2 p1 io organization-97-2003
Unit2 p1 io organization-97-2003Swathi Veeradhi
 
Computer organization
Computer organizationComputer organization
Computer organizationRvishnupriya2
 
COA-Unit5-ppt2.pptx
COA-Unit5-ppt2.pptxCOA-Unit5-ppt2.pptx
COA-Unit5-ppt2.pptxRuhul Amin
 
COMPUTER ORGANIZATION NOTES Unit 3 4
COMPUTER ORGANIZATION NOTES  Unit 3 4COMPUTER ORGANIZATION NOTES  Unit 3 4
COMPUTER ORGANIZATION NOTES Unit 3 4Dr.MAYA NAYAK
 

Similar to Io systems final (20)

IOhardware_operting_systems_2022_libya.pdf
IOhardware_operting_systems_2022_libya.pdfIOhardware_operting_systems_2022_libya.pdf
IOhardware_operting_systems_2022_libya.pdf
 
IO and file systems
IO and file systems IO and file systems
IO and file systems
 
UNIT 5- UNDERSTANDING THE SYSTEM DESIGN PROCESS.pptx
UNIT 5- UNDERSTANDING THE SYSTEM DESIGN PROCESS.pptxUNIT 5- UNDERSTANDING THE SYSTEM DESIGN PROCESS.pptx
UNIT 5- UNDERSTANDING THE SYSTEM DESIGN PROCESS.pptx
 
I/O System
I/O SystemI/O System
I/O System
 
The primary purpose of memory interfacing is to facilitate the transfer of da...
The primary purpose of memory interfacing is to facilitate the transfer of da...The primary purpose of memory interfacing is to facilitate the transfer of da...
The primary purpose of memory interfacing is to facilitate the transfer of da...
 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organization
 
Input output accessing
Input output accessingInput output accessing
Input output accessing
 
I/O Hardware-R.D.Sivakumar
I/O Hardware-R.D.SivakumarI/O Hardware-R.D.Sivakumar
I/O Hardware-R.D.Sivakumar
 
unit-5 ppt.ppt
unit-5 ppt.pptunit-5 ppt.ppt
unit-5 ppt.ppt
 
CO--MODULE-1 (b) - Input-Output-Organization.pptx
CO--MODULE-1 (b) - Input-Output-Organization.pptxCO--MODULE-1 (b) - Input-Output-Organization.pptx
CO--MODULE-1 (b) - Input-Output-Organization.pptx
 
Unit2 p1 io organization-97-2003
Unit2 p1 io organization-97-2003Unit2 p1 io organization-97-2003
Unit2 p1 io organization-97-2003
 
Computer organization
Computer organizationComputer organization
Computer organization
 
COA-Unit5-ppt2.pptx
COA-Unit5-ppt2.pptxCOA-Unit5-ppt2.pptx
COA-Unit5-ppt2.pptx
 
COMPUTER ORGANIZATION NOTES Unit 3 4
COMPUTER ORGANIZATION NOTES  Unit 3 4COMPUTER ORGANIZATION NOTES  Unit 3 4
COMPUTER ORGANIZATION NOTES Unit 3 4
 
NAVEEN UART BATCH 43
NAVEEN UART BATCH 43NAVEEN UART BATCH 43
NAVEEN UART BATCH 43
 
IO_ORGANIZATION.pdf
IO_ORGANIZATION.pdfIO_ORGANIZATION.pdf
IO_ORGANIZATION.pdf
 
Ca 2 note mano
Ca 2 note manoCa 2 note mano
Ca 2 note mano
 
Io sys
Io sysIo sys
Io sys
 
Lec MC.ppt
Lec MC.pptLec MC.ppt
Lec MC.ppt
 
IO organization.ppt
IO organization.pptIO organization.ppt
IO organization.ppt
 

More from marangburu42

Hennchthree 161102111515
Hennchthree 161102111515Hennchthree 161102111515
Hennchthree 161102111515marangburu42
 
Sequential circuits
Sequential circuitsSequential circuits
Sequential circuitsmarangburu42
 
Combinational circuits
Combinational circuitsCombinational circuits
Combinational circuitsmarangburu42
 
Hennchthree 160912095304
Hennchthree 160912095304Hennchthree 160912095304
Hennchthree 160912095304marangburu42
 
Sequential circuits
Sequential circuitsSequential circuits
Sequential circuitsmarangburu42
 
Combinational circuits
Combinational circuitsCombinational circuits
Combinational circuitsmarangburu42
 
Karnaugh mapping allaboutcircuits
Karnaugh mapping allaboutcircuitsKarnaugh mapping allaboutcircuits
Karnaugh mapping allaboutcircuitsmarangburu42
 
Aac boolean formulae
Aac   boolean formulaeAac   boolean formulae
Aac boolean formulaemarangburu42
 
Virtualmemoryfinal 161019175858
Virtualmemoryfinal 161019175858Virtualmemoryfinal 161019175858
Virtualmemoryfinal 161019175858marangburu42
 
File system interfacefinal
File system interfacefinalFile system interfacefinal
File system interfacefinalmarangburu42
 
File systemimplementationfinal
File systemimplementationfinalFile systemimplementationfinal
File systemimplementationfinalmarangburu42
 
Mass storage structurefinal
Mass storage structurefinalMass storage structurefinal
Mass storage structurefinalmarangburu42
 
All aboutcircuits karnaugh maps
All aboutcircuits karnaugh mapsAll aboutcircuits karnaugh maps
All aboutcircuits karnaugh mapsmarangburu42
 
Virtual memoryfinal
Virtual memoryfinalVirtual memoryfinal
Virtual memoryfinalmarangburu42
 
Mainmemoryfinal 161019122029
Mainmemoryfinal 161019122029Mainmemoryfinal 161019122029
Mainmemoryfinal 161019122029marangburu42
 
Virtualmemorypre final-formatting-161019022904
Virtualmemorypre final-formatting-161019022904Virtualmemorypre final-formatting-161019022904
Virtualmemorypre final-formatting-161019022904marangburu42
 

More from marangburu42 (20)

Hol
HolHol
Hol
 
Write miss
Write missWrite miss
Write miss
 
Hennchthree 161102111515
Hennchthree 161102111515Hennchthree 161102111515
Hennchthree 161102111515
 
Hennchthree
HennchthreeHennchthree
Hennchthree
 
Hennchthree
HennchthreeHennchthree
Hennchthree
 
Sequential circuits
Sequential circuitsSequential circuits
Sequential circuits
 
Combinational circuits
Combinational circuitsCombinational circuits
Combinational circuits
 
Hennchthree 160912095304
Hennchthree 160912095304Hennchthree 160912095304
Hennchthree 160912095304
 
Sequential circuits
Sequential circuitsSequential circuits
Sequential circuits
 
Combinational circuits
Combinational circuitsCombinational circuits
Combinational circuits
 
Karnaugh mapping allaboutcircuits
Karnaugh mapping allaboutcircuitsKarnaugh mapping allaboutcircuits
Karnaugh mapping allaboutcircuits
 
Aac boolean formulae
Aac   boolean formulaeAac   boolean formulae
Aac boolean formulae
 
Virtualmemoryfinal 161019175858
Virtualmemoryfinal 161019175858Virtualmemoryfinal 161019175858
Virtualmemoryfinal 161019175858
 
File system interfacefinal
File system interfacefinalFile system interfacefinal
File system interfacefinal
 
File systemimplementationfinal
File systemimplementationfinalFile systemimplementationfinal
File systemimplementationfinal
 
Mass storage structurefinal
Mass storage structurefinalMass storage structurefinal
Mass storage structurefinal
 
All aboutcircuits karnaugh maps
All aboutcircuits karnaugh mapsAll aboutcircuits karnaugh maps
All aboutcircuits karnaugh maps
 
Virtual memoryfinal
Virtual memoryfinalVirtual memoryfinal
Virtual memoryfinal
 
Mainmemoryfinal 161019122029
Mainmemoryfinal 161019122029Mainmemoryfinal 161019122029
Mainmemoryfinal 161019122029
 
Virtualmemorypre final-formatting-161019022904
Virtualmemorypre final-formatting-161019022904Virtualmemorypre final-formatting-161019022904
Virtualmemorypre final-formatting-161019022904
 

Recently uploaded

FULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | DelhiMalviyaNagarCallGirl
 
The First Date by Daniel Johnson (Inspired By True Events)
The First Date by Daniel Johnson (Inspired By True Events)The First Date by Daniel Johnson (Inspired By True Events)
The First Date by Daniel Johnson (Inspired By True Events)thephillipta
 
Burari Call Girls : ☎ 8527673949, Low rate Call Girls
Burari Call Girls : ☎ 8527673949, Low rate Call GirlsBurari Call Girls : ☎ 8527673949, Low rate Call Girls
Burari Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
FULL ENJOY - 9953040155 Call Girls in Noida | Delhi
FULL ENJOY - 9953040155 Call Girls in Noida | DelhiFULL ENJOY - 9953040155 Call Girls in Noida | Delhi
FULL ENJOY - 9953040155 Call Girls in Noida | DelhiMalviyaNagarCallGirl
 
Strip Zagor Extra 322 - Dva ortaka.pdf
Strip   Zagor Extra 322 - Dva ortaka.pdfStrip   Zagor Extra 322 - Dva ortaka.pdf
Strip Zagor Extra 322 - Dva ortaka.pdfStripovizijacom
 
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | DelhiMalviyaNagarCallGirl
 
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | DelhiMalviyaNagarCallGirl
 
Mandi House Call Girls : ☎ 8527673949, Low rate Call Girls
Mandi House Call Girls : ☎ 8527673949, Low rate Call GirlsMandi House Call Girls : ☎ 8527673949, Low rate Call Girls
Mandi House Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
Pragati Maidan Call Girls : ☎ 8527673949, Low rate Call Girls
Pragati Maidan Call Girls : ☎ 8527673949, Low rate Call GirlsPragati Maidan Call Girls : ☎ 8527673949, Low rate Call Girls
Pragati Maidan Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Availabledollysharma2066
 
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur DubaiBur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubaidajasot375
 
9654467111 Call Girls In Noida Sector 62 Short 1500 Night 6000
9654467111 Call Girls In Noida Sector 62 Short 1500 Night 60009654467111 Call Girls In Noida Sector 62 Short 1500 Night 6000
9654467111 Call Girls In Noida Sector 62 Short 1500 Night 6000Sapana Sha
 
Faridabad Call Girls : ☎ 8527673949, Low rate Call Girls
Faridabad Call Girls : ☎ 8527673949, Low rate Call GirlsFaridabad Call Girls : ☎ 8527673949, Low rate Call Girls
Faridabad Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857delhimodel235
 
Karachi Escorts | +923070433345 | Escort Service in Karachi
Karachi Escorts | +923070433345 | Escort Service in KarachiKarachi Escorts | +923070433345 | Escort Service in Karachi
Karachi Escorts | +923070433345 | Escort Service in KarachiAyesha Khan
 
How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?
How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?
How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?kexey39068
 
Karol Bagh Call Girls : ☎ 8527673949, Low rate Call Girls
Karol Bagh Call Girls : ☎ 8527673949, Low rate Call GirlsKarol Bagh Call Girls : ☎ 8527673949, Low rate Call Girls
Karol Bagh Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
Aiims Call Girls : ☎ 8527673949, Low rate Call Girls
Aiims Call Girls : ☎ 8527673949, Low rate Call GirlsAiims Call Girls : ☎ 8527673949, Low rate Call Girls
Aiims Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
9654467111 Full Enjoy @24/7 Call Girls In Saket Delhi Ncr
9654467111 Full Enjoy @24/7 Call Girls In Saket Delhi Ncr9654467111 Full Enjoy @24/7 Call Girls In Saket Delhi Ncr
9654467111 Full Enjoy @24/7 Call Girls In Saket Delhi NcrSapana Sha
 
Call Girls in Islamabad | 03274100048 | Call Girl Service
Call Girls in Islamabad | 03274100048 | Call Girl ServiceCall Girls in Islamabad | 03274100048 | Call Girl Service
Call Girls in Islamabad | 03274100048 | Call Girl ServiceAyesha Khan
 

Recently uploaded (20)

FULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
 
The First Date by Daniel Johnson (Inspired By True Events)
The First Date by Daniel Johnson (Inspired By True Events)The First Date by Daniel Johnson (Inspired By True Events)
The First Date by Daniel Johnson (Inspired By True Events)
 
Burari Call Girls : ☎ 8527673949, Low rate Call Girls
Burari Call Girls : ☎ 8527673949, Low rate Call GirlsBurari Call Girls : ☎ 8527673949, Low rate Call Girls
Burari Call Girls : ☎ 8527673949, Low rate Call Girls
 
FULL ENJOY - 9953040155 Call Girls in Noida | Delhi
FULL ENJOY - 9953040155 Call Girls in Noida | DelhiFULL ENJOY - 9953040155 Call Girls in Noida | Delhi
FULL ENJOY - 9953040155 Call Girls in Noida | Delhi
 
Strip Zagor Extra 322 - Dva ortaka.pdf
Strip   Zagor Extra 322 - Dva ortaka.pdfStrip   Zagor Extra 322 - Dva ortaka.pdf
Strip Zagor Extra 322 - Dva ortaka.pdf
 
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
 
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
 
Mandi House Call Girls : ☎ 8527673949, Low rate Call Girls
Mandi House Call Girls : ☎ 8527673949, Low rate Call GirlsMandi House Call Girls : ☎ 8527673949, Low rate Call Girls
Mandi House Call Girls : ☎ 8527673949, Low rate Call Girls
 
Pragati Maidan Call Girls : ☎ 8527673949, Low rate Call Girls
Pragati Maidan Call Girls : ☎ 8527673949, Low rate Call GirlsPragati Maidan Call Girls : ☎ 8527673949, Low rate Call Girls
Pragati Maidan Call Girls : ☎ 8527673949, Low rate Call Girls
 
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
 
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur DubaiBur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
 
9654467111 Call Girls In Noida Sector 62 Short 1500 Night 6000
9654467111 Call Girls In Noida Sector 62 Short 1500 Night 60009654467111 Call Girls In Noida Sector 62 Short 1500 Night 6000
9654467111 Call Girls In Noida Sector 62 Short 1500 Night 6000
 
Faridabad Call Girls : ☎ 8527673949, Low rate Call Girls
Faridabad Call Girls : ☎ 8527673949, Low rate Call GirlsFaridabad Call Girls : ☎ 8527673949, Low rate Call Girls
Faridabad Call Girls : ☎ 8527673949, Low rate Call Girls
 
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
 
Karachi Escorts | +923070433345 | Escort Service in Karachi
Karachi Escorts | +923070433345 | Escort Service in KarachiKarachi Escorts | +923070433345 | Escort Service in Karachi
Karachi Escorts | +923070433345 | Escort Service in Karachi
 
How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?
How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?
How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?
 
Karol Bagh Call Girls : ☎ 8527673949, Low rate Call Girls
Karol Bagh Call Girls : ☎ 8527673949, Low rate Call GirlsKarol Bagh Call Girls : ☎ 8527673949, Low rate Call Girls
Karol Bagh Call Girls : ☎ 8527673949, Low rate Call Girls
 
Aiims Call Girls : ☎ 8527673949, Low rate Call Girls
Aiims Call Girls : ☎ 8527673949, Low rate Call GirlsAiims Call Girls : ☎ 8527673949, Low rate Call Girls
Aiims Call Girls : ☎ 8527673949, Low rate Call Girls
 
9654467111 Full Enjoy @24/7 Call Girls In Saket Delhi Ncr
9654467111 Full Enjoy @24/7 Call Girls In Saket Delhi Ncr9654467111 Full Enjoy @24/7 Call Girls In Saket Delhi Ncr
9654467111 Full Enjoy @24/7 Call Girls In Saket Delhi Ncr
 
Call Girls in Islamabad | 03274100048 | Call Girl Service
Call Girls in Islamabad | 03274100048 | Call Girl ServiceCall Girls in Islamabad | 03274100048 | Call Girl Service
Call Girls in Islamabad | 03274100048 | Call Girl Service
 

Io systems final

  • 1. 1 I/O Systems (Galvin Notes,9th Ed.) Chapter 13: I/O Systems  OVERVIEW  I/O HARDWARE  Polling  Interrupts  Direct Memory Access  APPLICATION I/O INTERFACE  Block and Character Devices  Network Devices  Clocks and Timers  Blocking and Non-blocking I/O  KERNEL I/O SUBSYSTEM  I/O Scheduling  Buffering  Caching  Spooling and Device Reservation  Error Handling  I/O Protection  Kernel Data Structures  TRANSFORMING I/O REQUESTS TO HARDWARE OPERATIONS  PERFORMANCE (Optional) Content OVERVIEW  Management ofI/O devices is a veryimportant part of the operating system - soimportant andso varied that entire I/O subsystems are devotedto its operation. (Consider the range of devices ona moderncomputer, from mice, keyboards, disk drives, display ada pters, USB devices, network connections, audioI/O, printers, special devices for the handicapped, and many special -purpose peripherals.) I/O Subsystems must contend withtwo (conflicting?) trends:(1) The gravitationtowards standard interfaces for a wide range of d evices, making it easier to addnewlydevelopeddevices to existing systems, and (2) the development ofentirelynew typ es of devices, for whichthe existing standard interfaces are not always easy to apply.  Device drivers are modules that canbe pluggedintoanOS to handle a particular device or categoryof similar devices. I/O HARDWARE  I/O devices can be roughly categorized as storage, communications, user-interface, andother Devices communicate with the computer via signals sent over wiresor through the air. Devices connect with the computer via ports, e.g. a serial or parallel port.  A common set of wires connectingmultiple devices is termed a bus. Busesinclude rigidprotocols for the types ofmessages that can be sent across the bus and the procedures for resolving contentionissues. Figure 13.1 below illustrates three of the four bus types commonly found in a modern PC: o The PCI bus connects high-speed high-bandwidth devices to the memory subsystem (and the CPU.) o The expansion bus connects slower low-bandwidth devices (suchas keyboard and serial/parallel ports), which typically deliver data one character at a time (with buffering.) o The SCSIbus connects a number of SCSI devicesto a common SCSI controller. o A daisy-chain bus, (not shown) is whena string ofdevicesis connected to each other like beads on a chain, andonlyone of the devices is directlyconnected to the host.
  • 2. 2 I/O Systems (Galvin Notes,9th Ed.) In figure 13.1, In the upper-right portionof the figure, four disks are connectedtogether on a SCSI bus pluggedintoa SCSI controller.  A controller is a collectionof electronics that can operate a port, a bus, or a device. A serial-port controller is a simple device controller. It is a single chip(or portionof a chip) inthe computer that controls the signals onthe wires of a serialport. Bycontrast, a SCSI bus controller is not simple. Because the SCSI protocol is complex, the SCSI bus controller is often implemented as a separate circuit board (or a host adapter) that plugs into the computer. It typicallycontains a processor, microcode, andsome private memoryto enable it to process the SCSI protocol messages. Some devices have their ownbuilt-in controllers. If youlook at a disk drive, you willsee a circuit board attached to one side. This board is the diskcontroller. It implements the diskside of the protocol for some kind of connection - SCSI or ATA, for instance. It has microcode, and a processor to do many tasks, such as bad-sector mapping, prefetching, buffering, and caching.  How can the processor give commands and data to a controller to accomplishan I/O transfer? The short answer is that the controller has one or more registers for data andcontrol signals. The processor communicates withthe controller byreading and writing bit patterns in these registers. One wayinwhich thiscommunicationcanoccur is through the use of special I/O instructions that specify the transfer of a byte or word to an I/O port address. The I/O instructiontriggers bus lines to select the proper device and to move bits into or out of a device register. Alternatively, the device controller cansupport memory-mappedI/O. In this case,the device-control registers are mappedinto the address space of the processor. The CPU executesI/O requests using the standarddata-transfer instructions to read and write the device- control registers. (From site: Memory-mapped I/O is suitable for devices which must move large quantities of data quickly, such as graphics cards. Memory-mapped I/O can be used either instead of or more often in combination with traditional registers. For example, graphics cards still use registers for control information such as setting the video mode.)  Some systems use both techniques. For instance, PCs use I/O instructions to control some devices and memory-mappedI/O to control others. Figure 13.2 shows the usual I/O port addresses for PCs. The graphics controller has I/O ports for basic control operations, but the controller has a large memory- mappedregionto hold screen contents. The process sends output to the screenbywritingdata into the memory-mappedregion. The controller generates the screen image based on the contents of this memory. This technique is simple to use. Moreover, writingmillions of bytes to the graphics memory is faster thanissuingmillions of I/O instructions. But the ease of writing to a memory-mappedI/O controller is offset bya disadvantage. Because a common type of software fault is a write through anincorrect pointer to anunintendedregionof memory, a memory-mappeddevice register is vulnerable to accidentalmodification.  An I/O port typicallyconsists of four registers, called the (1) status, (2) control, (3) data-in, and(4) data-out registers. Registers maybe one to four bytes in size, and may typically include (a subset of) the following four. o The data-in register is read by the host to get input. o The data-out register is written by the host to send output. o The status register contains bits that canbe readbythe host. These bits indicate states, suchas whether the current commandhas completed, whether byte is available to be read from the data -in register, and whether a device error has occurred. o The control register can be writtenbythe host to start a commandor to change the mode of a device. For instance, a certainbit in the control register of a serial port chooses between full-duplex and half-duplex communication, another bit enables parity checking, a thirdbit sets the wordlengthto 7 or 8 bits, and other bits select one of the speeds supported by the serial po rt. Polling  The complete protocol for interactionbetweenthe host anda controller canbe intricate, but the basic handshaking notion is simple. We explainhandshakingwith an example. We assume that 2 bits are used to coordinate the producer-consumer relationship between the controller andthe host. The controller indicates its state through the busy bit in the status register (set means 1, clear means 0). The controller sets the busybit whenit is busyworkingandclears the busybit when it is readyto accept the next command. The host signals its wishes via the command-readybit inthe command register. The host sets the command-ready bit when a command is available for the controller to execute. For this example, the host writes output through a port, coordinating with the controller byhandshaking as follows: o The host repeatedly reads the busy bit until that bit becomes clear. o The host sets the write bit in the command register and writes a byte into the data-out register. o The host sets the command-ready bit. o When the controller notices that the command-ready bit is set, it sets the busy bit. o The controller reads the commandregister andseesthe write command. It reads the data-out register to get the byte and does the I/O to the device. o The controller clears the command-readybit, clears the error bit inthe status register to indicate that the device I/O succeeded, and clears the busy bit to indicate that it is finished. This loop is repeated for each byte.  In step1, the host is busy-waiting or polling: It is in a loop, readingthe status register over and over until the busybit becomes clear. If the controller anddevice are fast, this methodis a reasonable one. But if the wait maybe long, the host shouldprobablyswitch to another task. How, then, does the host knowwhenthe controller hasbecome idle?For some devices, the host must service the device quickly, or data will
  • 3. 3 I/O Systems (Galvin Notes,9th Ed.) be lost. For instance, whendata are streaming in ona serialport or from a keyboard, the small buffer on the controller wil l overflow and data will be lost if the host waits too long before returning to read the bytes.  In manycomputer architectures, three CPU-instructioncycles are sufficient to poll a device: read a device register, logical-and to extract a status bit, and branch if not zero. Clearly, the basic pollingoperationis efficient. But polling becomes inefficient when it is attempted repeatedlyyet rarelyfinds a device to be readyfor service, while other useful CPU processing remains undone. Insuchinsta nces, it may be more efficient to arrange for the hardware controller to notifythe CPU whenthe device becomes readyfor service, rather tha n to require the CPU to poll repeatedly for an I/O completion. The hardware mechanism that enables to notify the CPU is calle d an interrupt. Interrupts  The basic interrupt mechanism works as follows. The CPU hardware has a wire called the interrupt-request line that the CPU senses after executingeveryinstruction. Whenthe CPU detects that a controller has asserteda signal on the interrupt request line, the CPU performs a state save and jumps to the interrupt-handler routine at a fixed address in memory. The interrupt handler determines the cause of the interrupt, performs the necessaryprocessing, performs a state restore, and executes a return from interrupt instruction to return the CPU to the execution state prior to the interrupt. We say that the device controllers raisesaninterrupt byassertinga signalon the interrupt request line, the CPU catches the interrupt and dispatches it to the interrupt handler, and the handler clears the interrupt by servicing the device. Figure 13.3 summarizes the interrupt-driven I/O cycle.  This basic interrupt mechanismenables the CPU to respond to an asynchronous even, as whena device controller becomes ready for service. In a modern operating system, however, we need more sophisticated interrupt handling features. o We needthe ability to defer interrupt handling during critical processing. o We need an efficient way to dispatch to the proper interrupt handler for a device without first poling all the devices to see which one raised the interrupt. o We need multilevel interrupts, so that the operating systemcan distinguish between high-and low-priority interrupts and can respond with the appropriate degree of urgency In modern computer hardware, these three features are provided by the CPU and by the interrupt-controller hardware.  Most CPUs have two interrupt request lines. One is the nonmaskable interrupt, whichis reservedfor events suchas uncrecoverable memory errors. The secondinterrupt line is maskable:It canbe turnedoff bythe CPU before the executionof critical instructionsequencesthat must not be interrupted. The maskable interrupt is used by device controllers to request service.  The interrupt mechanism accepts an address—a number that selects a specific interrupt-handling routine from a small set. In most architectures, this addressis anoffset ina table called the interrupt vector. This vector contains the memoryaddressesof specializedinterrupt handlers. The purpose of a vectoredinterrupt mechanism is to reduce the need for a single interrupt handler to search all possible sources of interrupts to determine which one needs service. In practice, however, computers have more devices (and, hence, interrupt handlers) than they have address elements inthe interrupt vector. A common wayto solve this problem is to use interrupt chaining, in whicheach element inthe interrupt vector points to the headof a list of interrupt handlers. When an interrupt is raised, the handlers on the corresponding list are called one by one, until one is found that can service the request. This structure is a compromise between the overheadof a huge interrupt table and the inefficiency of dispatching to a single interrupt handler.  Figure 13.4 illustrates the designof the interrupt vector for the Intel Pentium processor. The events from0 to 31, which are nonmaskable, are usedto signal various error conditions. The events from32 to 255, which are maskable, are used for purposes such as device-generated interrupts.  The interrupt mechanism also implements a system of interrupt priority levels. These levels enable the CPU to defer the handling of low-priority interrupts without masking all interrupts andmakesit possible for a high priority interrupt to preempt the execution of a low-priority interrupt.  A modern operating systeminteracts withthe interrupt mechanism in several ways. At boot time, the operating system probes t he hardware buses to determine what devices are present and installs the corresponding interrupt handlers into the interrupt vector.  During I/O, the various device controllers raise interrupts when they are ready for service. These interrupts signify that ou tput has completed, or that input data are available, or that a failure has beendetected. The interrupt mechanism is also used to handle a wide varietyof exceptions, such as dividing by0, accessing a protectedor nonexistent memoryaddress, or attempting to execute a privileged instruction from user mode.
  • 4. 4 I/O Systems (Galvin Notes,9th Ed.)  An operatingsystemhas other good uses for an efficient hardware and software mechanismthat saves a small amount of processor state and then callsa privileged routine inthe kernel. For example, manyoperatingsystems use the interrupt mechanism for virtua l memory paging. A page fault is an exceptionthat raises an interrupt. The interrupt suspends the current process andjumps to the page-fault handler in the kernel. This handler saves the state of the process, moves the process to the wait queue, performs page -cache management, schedules anI/O operationto fetch the page, schedules another process to resume execution, and then returns from the interrupt.  An operatingsystemhas other good uses for an efficient hardware and software mechanismthat saves a small amount of process or state and then callsa privileged routine inthe kernel. For example, manyoperatingsystems use the interrupt mechanism for virtua l memory paging. A page fault is an exceptionthat raises an interrupt. The interrupt suspends the current process andjumps to the page-fault handler in the kernel. This handler saves the state of the process, moves the process to the wait queue, performs page -cache management, schedules anI/O operationto fetch the page, schedules another process to resume execution, and then returns from the interrupt.  Another example is foundinthe implementationof system calls. Usually, a program uses library calls to issue system calls. The library routines checkthe arguments givenbythe application, build a data structure to conveythe arguments to the kernel, and then execute a specialinstruction calleda software interrupt, or trap. This instructionhas anoperandthat identifies the desired kernel service. When a process executesthe trapinstruction, the interrupt hardware saves the state ofthe user code, switches to kernel mode, and dispatches to the kernel routine that implements the requestedservice. The trapis givena relativelylowinterrupt prioritycomparedwith those assigned to device interrupts—executinga system call onbehalf ofanapplicationis less urgent than servicing a device controller before its FIFO queue overflows and loses data.  Interrupts canalsobe usedto manage the flow of control withinthe kernel. For example, consider one example of the process ing required to complete a diskread. One stepis to copydata fromkernel space to the user buffer. Thiscopying is time consuming but no t urgent—it should not block other high-priorityinterrupt handling. Another stepis to start the next pending I/O for that disk drive. This step has higher priority. Ifthe disks are to be used efficiently, we needto start the next I/O as soonas the previous one completes. Conse quently, a pair of interrupt handlers implements the kernel code that completes a diskread. The high-priorityhandler records the I/O status, clears the device interrupt, starts the next pending I/O, andraises a low-priorityinterrupt to complete the work. Later, when the CPU is not occupied with high prioritywork, the low-priorityinterrupt willbe dispatched. The corresponding handler completes the user-level I/O by copying data from kernel buffers to the application space and then calling the scheduler to place the application on the ready queue.  A threadedkernel architecture is well suitedto implement multiple interrupt priorities and to enforce the precedence of interrupt handling over backgroundprocessing in kernel andapplicationroutines. We illustrate this point withthe Solaris kernel. InSolaris, interrupt handlers are executedas kernel threads. A range of high prioritiesis reservedfor these threads. These priorities give interrupt handlers precedence over application code andkernel housekeepingandimplement the priorityrelationships among interrupt handlers. The priorities cause the Solaris threadscheduler to preempt low priorityinterrupt handlers in favor of higher-priority ones, and the threaded implementation enables multiprocessor hardware to run several interrupt handlers concurrently. We describe the interrupt architecture of Windows XP and UNIX in Chapter 19 and Appendix A, respectively.  In summary, interrupts are used throughout modern operating systems to handle asynchronous events and to trap to supervisor-mode routines inthe kernel. To enable the most urgent workto be done first, modern computers use a system of interrupt priorities. Device controllers, hardware faults, andsystemcallsall raise interrupts to trigger kernelroutines. Because interrupts are used s o heavily for time- sensitive processing, efficient interrupt handling is required for good system performance. Directory Memory Access  For a device that does large transfers, such as a diskdrive, it seems wasteful to use anexpensive general-purpose processor to watch status bits andto feed data into a controller register one byte at a time—a process termed programmed I/O (PIO). Many computers avoid burdening the mainCPU with PIO byoffloadingsome ofthis work to a special -purpose processor called a direct-memory-access (DMA) controller.  To initiate a DMA transfer, the host writes a DMA commandblock into memory. This block contains a pointer to the source of a transfer, a pointer to the destinationof the transfer, anda count of the number of bytes to be transferred. The CPU writes the address of this command block to the DMA controller, thengoes onwithother work. The DMA controller proceeds to operate the memory bus directly, pl acing addresses onthe bus to perform transfers without the helpof the mainCPU. A simple DMA controller is a standardcomponent inall modern computers, from smartphones to mainframes.  Handshaking between the DMA controller and the device controller is performed via a pair of wires called DMA-request and DMA- acknowledge. The device controller places a signal onthe DMA-request wire when a wordof data is available for transfer. Thissignal causes the DMA controller to seize the memorybus, place the desired address on the memory-address wires, and place a signal on the DMA- acknowledge wire. Whenthe device controller receives the DMA-acknowledge signal, it transfers the word ofdata to memoryand removes the DMA-request signal.  When the entire transfer is finished, the DMA controller interrupts the CPU. This process is depictedinFigure 13.5. When the DMA controller seizes the memory bus, the CPU is momentarily prevented from accessing mainmemory, althoughit can still access data items in its primaryandsecondary caches. Although this cycle stealing can slow down the CPU computation, offloadingthe data-transfer work to a DMA controller generally improves the total system performance.  Some computer architectures use physical memoryaddresses for DMA, but others perform direct virtual memory access (DVMA), using virtual addresses that undergotranslation to physical addresses. DVMA can perform a transfer betweentwo memory-mappeddevices without the intervention of the CPU or the use of main memory.  On protected-mode kernels, the operating system generally prevents processes fromissuingdevice commands directly. Thisdiscipline protects data fromaccess-control violations andalso protects the system from
  • 5. 5 I/O Systems (Galvin Notes,9th Ed.) erroneous use of device controllers that could cause a system crash. Instead, the operating system exports functions that a sufficiently privilegedprocess canuse to access low-level operations onthe underlying hardware. On kernels without memoryprotection, processescan access device controllers directly. Thisdirect accesscanbe usedto achieve highperformance, since it can avoid kernel commun ication, context switches, andlayers of kernelsoftware. Unfortunately, it interferes withsystemsecurityand stability. The trendingeneral-purpose operatingsystems is to protect memoryanddevices so that the system can try to guard against erroneous or malicious applica tions. I/O Hardware Summary  Although the hardware aspects ofI/O are complex whenconsidered at the level of detail of electronics-hardware design, the concepts that we have just described are sufficient to enable us to understand manyI/O features of operating systems. Let’s review the mai n concepts: • A bus • A controller • An I/O port andits registers • The handshaking relationship between the host and a device controller • The executionof this handshakingina pollingloop or via interrupts • The offloading of this work to a DMA controller for large transfers  We gave a basic example of the handshakingthat takes place betweena device controller and the host earlier in this section. In reality, the wide varietyof available devicesposes a problem for operating-system implementers. Eachkindof device has its own set of capabilities, control-bit definitions, andprotocols for interacting withthe host—andtheyare alldifferent. How canthe operating system be designed so that we canattach newdevicesto the computer without rewriting the operating system? Andwhenthe devices varysowidely, h ow can the operating system give a convenient, uniform I/O interface to applications? We address those questions next. APPLICATIONI/O INTERFACE Continuing from the last line ofthe previous section, in this section, we discuss structuring techniquesandinterfacesfor the operating system that enable I/O devicesto be treatedina standard, uniformway. We explain, for instance, how an applicationcanopena file on a diskwithout knowing what kind of diskit is andhownew disks and other devices can be added to a computer without disruption of the operating system.  Like other complex software-engineeringproblems, the approach here involves abstraction, encapsulation, and software layering. Specifically, we canabstract awaythe detaileddifferences in I/O devices byidentifyinga few general kinds. Each general kind is accessed througha standardized set of functions —an interface. The differencesare encapsulatedin kernel modules called device drivers that internallyare custom-tailoredto specific devices but that export one of the standard interfaces. Figure 13.6 illustrates how the I/O-related portions of the kernel are structured in software layers.  The purpose of the device-driver layer is to hide the differences amongdevice controllers fromthe I/O subsystem of the kernel, muchas the I/O system callsencapsulate the behaviour of devices in a few generic classes that hide hardware differences fromapplications. Making the I/O subsystem independent of the hardware simplifies the job of the operating-system developer. It also benefits the hardware manufacturers. Theyeither designnew devices to be compatible withan existing host controller interface (such as SATA), or they write device drivers to interface the new hardware to popular operatingsystems. Thus, we canattach new peripherals to a computer without waiting for the operating-system vendor to develop support code.  Unfortunatelyfor device-hardware manufacturers, eachtype of operating systemhas its ownstandards for the device -driver interface. A given device may ship with multiple device drivers —for instance, drivers for Windows, Linux, AIX, and Mac OS X.  Devices varyon manydimensions, as illustrated in Figure 13.7. : o Character-stream or block. A character-stream device transfers bytes one byone, whereas a block device transfers a block of bytes as a unit. o Sequential or random access. A sequential device transfers data in a fixed order determined by the device, whereas the user of a random-accessdevice caninstruct the device to seek to any of the available data storage locations. o Synchronous or asynchronous. A synchronous device performs data transfers withpredictable response times, incoordinationwith other aspects of the system. An as ynchronous device exhibits irregular or unpredictable response times not coordinated with other computer events. o Sharable or dedicated. A sharable device canbe usedconcurrently by several processes or threads; a dedicated device cannot. o Speed of operation. Device speeds range from a few bytes per second to a few gigabytes per second. o Read–write, read only, or write only. Some devices perform both input andoutput, but others support only one data transfer direction.  For the purpose of applicationaccess, manyof these differences are hiddenbythe operating system, andthe devices are groupedintoa few conventionaltypes. The resulting styles of device access have beenfoundto be useful and broadlyapplicable. Although the e xact system calls maydiffer acrossoperatingsystems, the device categories are fairly standard. The major access conventions include block I/O, character-streamI/O, memory-mappedfile access, andnetwork sockets. Operatingsystems alsoprovide specialsystem callsto accessa few
  • 6. 6 I/O Systems (Galvin Notes,9th Ed.) additional devices, suchas a time-of-dayclock anda timer. Some operating systems provide a set ofsystemcallsfor graphicaldisplay, video, and audio devices.  Most operatingsystems alsohave an escape (or back door) that transparentlypasses arbitrarycommands fromanapplication to a device driver. In UNIX, this system call is ioctl() (for “I/O control”). The ioctl() system call enables anapplication to access anyfunctionality that can be implemented byanydevice driver, without the needto invent a new system call. The ioctl() systemcall has three arguments. The first is a file descriptor that connects the applicationto the driver byreferring to a hardware device managedbythat driver. The secondis aninteger that selects one of the commands implemented inthe driver. The thirdis a pointer to anarbitrarydata structure inmemorythat enablesthe application and driver to communicate any necessary control information or data. Block and Character Devices  Block devices are accesseda blockat a time, andare indicated bya "b"as the first character ina long listing on UNIX sys tems. Operations supported include read(), write(), and seek().  Raw I/O and Direct I/O: Accessingblocks ona hard drive directly(without going throughthe filesystem structure) is calledraw I/O, and can speedup certainoperations bybypassing the bufferingandlocking normally conducted by the OS. (It then becomes the applica tion's responsibilityto manage those issues.) A new alternative is direct I/O, which uses the normal filesystem access, but whichdisables buffering and locking operations.  Memory-mapped file I/O can be layeredontop ofblock-device drivers. Rather thanreading in the entire file, it is mapped to a range of memoryaddresses, andthen paged into memoryas neededusing the virtual memory system. Access to the file is then acco mplished through normal memoryaccesses, rather thanthroughread()and write() systemcalls. This approach is commonly used for execu table program code. Because the transfers are handled bythe same mechanism as that used for demand-pagedvirtual memory access, memory- mappedI/O is efficient. Memorymapping is alsoconvenient for programmers—accessto a memory-mapped file is as simple as readingfrom and writing to memory.  Character devices are accessedone byte at a time, andare indicatedbya "c" inUNIXlonglistings. Supported operations include get() and put(), with more advanced functionality such as reading an entire line supported by higher-level library routines. Network Devices  Because network access is inherentlydifferent from local diskaccess, most systems provide a separate interface for network devices. One common andpopular interface is the socket interface, which acts like a cable or pipeline connectingtwo networked entities. Data canbe put into the socket at one end, andreadout sequentiallyat the other end. Sockets are normallyfull-duplex, allowing for bi-directional data transfer. The select() system call allows servers (or other applications) to identifysockets which have data waiting, without having to poll all available sockets. (To support the implementation of servers, the socket interface alsoprovides a functioncalled select() that manages a set of sockets. A call to select() returns informationabout whichsockets have a packet waiting to be receivedandwhich sockets have room to accept a packet to be sent. The use of select() eliminatesthe polling andbusywaiting that wouldotherwise be necessary for network I/O.) Clocks and Timers Most computers have hardware clocks andtimers that provide three basic functions:• Give the current time. • Give the elapsed time. • Set a timer to trigger operation X at time T.  These functions are used heavilybythe operatingsystem, as well as bytime-sensitive applications. Unfortunately, the system calls that implement these functions are not standardized across operating systems.  The hardware to measure elapsed time and to trigger operations is called a programmable interval timer. It can be set to wait a certain amount of time andthengenerate an interrupt, and it canbe set to do thisonce or to repeat the process to generate periodic interrupts. The scheduler uses thismechanismto generate an interrupt that will preempt a process at the endof its time slice. The disk I/O subsystem uses it to invoke the periodic flushingof dirtycache buffers to disk, andthe network subsystem usesit to cancel operations tha t are proceeding too slowly because of network congestion or failures.  The operating systemmayalsoprovide an interface for user processes to use timers. The operatingsystemcansupport more timer requests than the number of timer hardware channelsbysimulatingvirtual clocks. To doso, the kernel (or the timer device driver) maintains a list of interrupts wantedbyits ownroutinesandbyuser requests, sorted in earliest-time-first order. It sets the timer for the earliest time. When the timer interrupts, the kernel signals the requester and reloads the timer with the next earliest time.  In most computers, the hardware clockis constructedfrom a high-frequencycounter. Insome computers, the value of this counter can be read from a device register, inwhichcase the counter canbe considered a high-resolution clock. Although this clock does not generate interrupts, it offers accurate measurements of time intervals.  (Site): A programmable interrupt timer, PIT can be used to trigger operations and to measure elapsed time. It can be set to trigger an interrupt at a specific future time, or to trigger interrupts periodically on a regular basis. o The scheduler uses a PIT to trigger interrupts for ending time slice s. o The disk system may use a PIT to schedule periodic maintenance cleanup, such as flushing buffers to disk. o Networks use PITto abort or repeat operations that are takingtoo long to complete. I.e. resending packets ifanacknowledgement is not received before the timer goes off. o More timers than actuallyexist can be simulatedbymaintaining anorderedlist of timer events, andsetting the physicaltimer to go off when the next scheduled event should occur.  On most systems the system clock is implementedbycountinginterrupts generated bythe PIT. Unfortunatelythis is limitedin its resolution to the interrupt frequencyof the PIT, and maybe subject to some drift over time. An alternate approachis to provide direct accessto a high frequency hardware counter, which provides much higher resolution and accuracy, but which does not support interrupts.
  • 7. 7 I/O Systems (Galvin Notes,9th Ed.) Blocking and Non-blocking I/O (Book: Nonblocking and Asynchronous I/O)  With blocking I/O a process is movedto the wait queue when an I/O request is made, and movedbackto the readyqueue whenthe request completes, allowing other processes to run in the meantime.  With non-blocking I/O the I/O request returns immediately, whether the requestedI/Ooperation has (completely ) occurred or not. This allows the process to check for available data without getting hungcompletelyifit is not there. (The regular non-blocking I/O, as compared to the asynchronous I/O, returns immediatelywith whatever results are available, but does not complete the operation and notify the process later.) One approachfor programmers to implement non-blocking I/O is to have a multi-threadedapplication, in which one thread makes blocking I/O calls (sayto reada keyboardor mouse), while other threads continue to update the screen or perform other tasks.  A subtle variation ofthe non-blockingI/O is the asynchronous I/O, inwhichthe I/O request returns immediately allowing the process to continue onwith other tasks, and thenthe process is notified (via changing a processvariable, or a software interrupt, or a callback function) when the I/O operation has completed and the data is available for use. Book  Another aspect ofthe system-callinterface relates to the choice betweenblocking I/O and nonblockingI/O. When an application issues a blocking system call, the executionof the applicationis suspended. The application is movedfrom the operating system’s run queue to a wait queue. After the systemcallcompletes, the application is movedback to the runqueue, where it is eligible to resume execution. When it resumes execution, it will receive the valuesreturnedbythe system call. The physical actions performed by I/O devices a re generally asynchronous—theytake a varying or unpredictable amount of time. Nevertheless, most operating systems use blockingsystem callsfor the application interface, because blocking application code is easier to understand than nonblocking application code.  Some user-level processesneed nonblocking I/O. One example is a user interface that receives keyboardandmouse input while processing and displaying data on the screen. Another example is a videoapplication that reads frames from a file on disk while simulta neously decompressing anddisplayingthe output on the display. One way an application writer can overlap execution with I/O is to write a multithreadedapplication. Some threads canperform blockingsystemcalls, while others continue executing. Some operating systems provide nonblocking I/O system calls. A nonblocking call does not halt the executionof the application for an extended time. Instead, it returns quickly, witha returnvalue that indicates how many bytes were transferred.  An alternative to a nonblocking system call is an asynchronous systemcall. An asynchronous call returns immediately, without waiting for the I/O to complete. The application continues to execute its code. The completionof the I/O at some future time is communicatedto the application, either through the setting of some variable inthe address space of the application or through the triggeringof a signal or software interrupt or a call-back routine that is executedoutside the linear control flowof the application. The difference between nonblocking andasynchronous system calls is that a nonblocking read() returns immediately with whatever data are available—the full number of bytes requested, fewer, or none at all. An asynchronous read() call requests a transfer that will be performed in its entirety but will complete at some future time. These two I/O methods are shown in Figure 13.8.  A good example ofnonblocking behavior is the select() system call for networksockets. This system call takesanargument that specifies a maximum waitingtime. Bysettingit to 0, anapplicationcanpoll for networkactivitywithout blocking. But using select() introduces extra overhead, because the select() call onlychecks whether I/O is possible. For a data transfer, select() must be followed bysome kindof read() or write() command. KERNEL I/O SUBSYSTEM  Kernels provide manyservicesrelatedto I/O. Several services—scheduling, buffering, caching, spooling, device reservation, and error handling—are providedbythe kernel’s I/O subsystem and build onthe hardware anddevice driver infrastructure. The I/O subsystem is also responsible for protecting itself from errant processes and malicious users. I/O Scheduling  To schedule a set of I/O requests means to determine a good order inwhichto execute them. The order in which applica tions issue systemcalls rarelyis the best choice. Scheduling canimprove overall system performance, can share device access fairly amo ng processes, andcan reduce the average waiting time for I/O to complete.  Operating-system developers implement scheduling by maintaining await queue of requests for each device. When an applicationissues a blocking I/O systemcall, the request is placed on the queue for that device. The I/O scheduler rearranges the order of the queue to improve the overall system effici ency and the average response time experienced by applications. The operatingsystemmayalsotryto be fair, sothat no one application receives especiallypoor service, or it maygive priority service for delay-sensitive requests. For instance, requests from the virtual memorysubsystem maytake priorityover application requests. Several schedulingalgorithms for diskI/O are detailed in Section 10.4.  When a kernel supports asynchronous I/O, it must be able to keeptrackof manyI/O requests at the same time. For this purpose, the operatingsystemmight attachthe wait queue to a device-status table. The kernel manages this table, whichcontains anentry for each
  • 8. 8 I/O Systems (Galvin Notes,9th Ed.) I/O device, as shownin Figure 13.9. Each table entryindicates the device’s type, address, a ndstate (not functioning, idle, or busy). If the device is busy with a request, the type of request and other parameters will be stored in the table entry for that device.  Scheduling I/O operations is one wayinwhichthe I/Osubsystem improves the effici ency of the computer. Another way is by using storage space in main memory or on disk via buffering, caching, and spooling. Buffering  A buffer is a memoryarea that stores data beingtransferredbetweentwo devices or between a device and an application. Buffering is done for three reasons. One reason is to cope with a speed mismatch between the producer and consumer of a data stream.  Suppose, for example, that a file is being receivedvia modemfor storage on the harddisk. The modemis abou t a thousand times slower than the hard disk. Soa buffer is created inmain memoryto accumulate the bytes receivedfrom the modem. Whenanentire buffer of data has arrived, the buffer can be writtento diskina single operation. Since the diskwrite is not instantaneous and the modem still needs a place to store additional incoming data, twobuffers are used. After the modemfills the first buffer, the disk write is requ ested. The modem then starts to fillthe secondbuffer while the first buffer is writtento disk. Bythe time the modem has filledthe secondbuffer, the diskwrite from the first one should have completed, so the modem canswitchbackto the first buffer while the diskwritesthe second o ne. Thisdouble buffering decouplesthe producer of data fromthe consumer, thus relaxing timing requirements betweenthem. The need for this decoupling is illustrated in Figure 13.10, whichlists the enormous differences in device speeds for typical computer hardware.  A seconduse of bufferingis to provide adaptations for devices that have different data-transfer sizes. Such disparities are especially common in computer networking, where buffers are usedwidelyfor fragmentation and reassemblyof messages. At the sendingside, a large message is fragmented into small networkpackets. The packets are sent over the network, and the receiving side places themina reassembly buffer to form an image of the source data.  A third use of bufferingis to support copysemantics for application I/O. For example, whenanapplicationmakesa request for a disk write (i.e., call the write() systemcall, the data is copied from the user's memory area into a kernel buffer. Now the application can change their copyof the data, but the data which eventuallygets written out to diskis the version ofthe data at the time the write request was made. Copying of data betweenkernel buffers andapplicationdata space is commoninoperating systems, despite the overhead that this operationintroduces, because of the clean semantics. The same effect canbe obtained more efficiently by clever use of virtual memory mapping and copy-on-write page protection. Caching  A cache is a regionof fast memorythat holds copies ofdata. Access to the cachedcopyis more efficient than access to the original. For instance, the instructions of the currentlyrunningprocessare storedondisk, cached in physical memory, and copied again i n the CPU’s secondaryandprimarycaches. The difference betweena buffer anda cache is that a buffer mayholdthe onlyexisting copy of a data item, whereas a cache, by definition, holds a copy on faster storage of an item that resides elsewhere.  Cachingandbuffering are distinct functions, but sometimes a regionof memorycan be used for bothpurpo ses. For instance, to preserve copysemantics andto enable efficient schedulingof diskI/O, the operatingsystem uses buffers inmain memory to hold disk data. These buffers are also used as a cache, to improve the I/O efficiencyfor files that are sharedbyapplications or that are being written and reread rapidly. When the kernel receives a file I/O request, the kernel first accesses the buffer cache to see whether that region o fthe file is already available inmainmemory. If it is, a physicaldiskI/O canbe avoidedor deferred. Also, disk writes are accumulated in the buffer cache for several seconds, so that large transfers are gatheredto allowefficient write schedules. This strategy of delaying writes to improve I/O efficiency is discussed, in the context of remote file access, in Section 17.9.2. Spooling and Device Reservation  A spool is a buffer that holds output for a device, suchas a printer, that cannot accept interleaved data streams. Although a printer canserve onlyone jobat a time, several applications maywishto print their output concurrently, without having their output mixed together. The operatingsystemsolves thisproblem byinterceptingall output to the printer. Eachapplication’s output is spooled to a sep arate disk file. When anapplicationfinishes printing, the spooling system queues the correspondingspool file for output to the printer. The spoolingsystem copies the queuedspool files to the printer one at a time. In some operating systems, spooling is managedbya system daemon process. In others, it is handled byanin-kernel thread. Ineither case, the operatingsystem providesa control interface that enables users and system administrators to displaythe queue, remove unwantedjobs before those jobs print, suspend printing while the printer is serviced, and soon.  Some devices, suchas tape drives andprinters, cannot usefullymultiplex the I/Orequests of multiple concurrent applications. Spooling is one wayoperating systems can coordinate concurrent output. Another wayto deal withconcurrent device access is to provide explicit facilitiesfor coordination. Some operatingsystems provide support for exclusive device access, other operating systems enforce a limit of one openfile handle to sucha device. Manyoperating systems provide functions that enable processes to coordinate exclusive access among themselves.
  • 9. 9 I/O Systems (Galvin Notes,9th Ed.) Error Handling  Error Handling I/O requests canfailfor manyreasons, either transient (buffers overflow)or permanent (disk crash). I/O req uests usually return an error bit (or more)indicating the problem. UNIXsystems also set the global variable errno to one of a hun dred or so well-defined values to indicate the specific error that has occurred. (See errno.h for a complete listing, or manerrno.)Some devices, suchas SCSI devices, are capable ofproviding muchmore detailedinformationabout errors, andevenkeep an on-boarderror logthat can be requested by the host (For instance, a failure of a SCSI device is reported by the SCSI protocol in three levels of detail...). I/O Protection  To prevent users fromperforming illegal I/O,we define all I/O instructions to be privileged instructions. Thus, users cannot issue I/O instructions directly;theymust doit throughthe operatingsystem. To do I/O, a user program executes a system call to requ est that the operatingsystemperformI/O onits behalf. The operating system, executing inmonitor mode, checks that the request is valid and, if it is, does the I/O requested. The operating system then returns to the user.  In addition, anymemory-mapped and I/O port memorylocations must be protectedfrom user access by the memory-protection system. Note that a kernel cannot simplydenyall user access. Most graphics games andvideo editing andplayback software need direct access to memory-mappedgraphics controller memoryto speedthe performance of the graphics, for example. The kernel might in this case provide a lockingmechanismto allow a sectionof graphics memory(representing a window on screen) to be allocated to one process at a time. Kernel Data Structures  The kernelmaintains a number of important data structures pertaining to the I/O system, suchas the open file table (fromSection12.1, 9th Ed). These structures are object-oriented, and flexible to allow access to a wide varietyof I/O devices through a common interface. (See Figure 13.12 below.) Windows NT carries the object-orientation one step further, implementingI/O as a message-passingsystemfrom the source through various intermediaries to the device. Kernel I/O Subsystem Summary  In summary, the I/O subsystemcoordinates an extensive collection of services that are available to applications andto other parts of the kernel. The I/O subsystem supervises these procedures: • Management of the name space for filesanddevices • Access control to files and devices • Operationcontrol (for example, a modem cannot seek()) • File-system space allocation • Device allocation • Buffering, caching, andspooling • I/O scheduling • Device-status monitoring, error handling, andfailure recovery • Device-driver configurationandinitialization The upper levelsof the I/O subsystem access devices via the uniform interface providedbythe device drivers. TRANSFORMING I/O REQUESTS TO HARDWARE OPERATIONS  Earlier, we describedthe handshakingbetweena device driver and a device controller, but we did not explain how the operating system connects an application request to a set of network wires or to a specific disk sector.  Consider, for example, reading a file from disk. The applicationrefers to the data bya file name. Withina disk, the file s ystemmaps from the file name throughthe file-systemdirectoriesto obtain the space allocation ofthe file. For instance, inMS-DOS, the name maps to a number that indicatesanentryin the file-accesstable, andthat table entrytells which disk blocks are allocatedto the file. InUNIX, the name maps to an inode number, andthe corresponding inode contains the space-allocation information. But how is the connectionmade from the file name to the disk controller (the hardware port address or the memory-mapped controller registers)?  One methodis that usedbyMS-DOS, a relativelysimple operating system. The first part of anMS-DOSfile name, preceding the colon, is a string that identifiesa specific hardware device. For example, C:is the first part of everyfile name onthe primaryhard disk. The fact that C: represents the primaryhard diskis built into the operating system; C:is mappedto a specific port address througha device table. Because of the colon separator, the device name space is separate from the file-system name space. This separation makes it easyfor the operating system to associate extra functionality with each device.  If, instead, the device name space is incorporated inthe regular file-system name space, as it is in UNIX, the normal file -system name services are provided automatically. If the file systemprovides ownershipandaccess control to all file names, thendevices have owners and access control. Since files are stored ondevices, suchaninterface provides access to the I/O system at two levels. Names can be used to access the devices themselves or to access the files stored on the devices.  UNIXrepresents device names in the regular file-systemname space. Unlike an MS-DOS filename, which has a colonseparator, a UNIX path name has noclear separation ofthe device portion. In fact, nopart of the pathname is the name of a device. UNIX has a mount table that associates prefixes of pathnames withspecific device names. To resolve a pathname, UNIXlooks up the name in the mount table to find the longest matching prefix;the corresponding entryin the mount table gives the device name. This device name also has the form of a
  • 10. 10 I/O Systems (Galvin Notes,9th Ed.) name inthe file-systemname space. WhenUNIXlooks upthis name inthe file-system directorystructures, it finds not aninode number but a<major, minor>device number. The major device number identifies a device driver that should be calledto handle I/O to this device. The minor device number is passedto the device driver to index into a device table. The corresponding device-table entrygives the port address or the memory-mapped address of the device controller.  Modern operatingsystems gainsignificant flexibility from the multiple stages of lookuptables inthe pathbetween a request and a physical device controller. The mechanisms that pass requests betweenapplications and drivers are general. Thus, we can introduce new devices and drivers intoa computer without recompiling the kernel. Infact, some operating systems have the abilityto load device drivers on demand. At boot time, the systemfirst probes the hardware buses to determine what devices are present. It thenloads inthe necessarydrivers, either immediately or when first required by an I/O request.  We next describe the typical life cycle ofa blocking read request, as depictedinFigure 13.13. The figure suggests that an I/O operationrequiresa great manysteps that together consume a tremendous number of CPU cycles. 1. A process issues a blocking read()systemcallto a file descriptor of a file that has beenopenedpreviously. 2. The system-callcode inthe kernel checks the parameters for correctness. In the case of input, if the data are alreadyavailable in the buffer cache, the data are returnedto the process, and the I/O request is completed. 3. Otherwise, a physical I/O must be performed. The processis removed fromthe run queue andis placed onthe wait queue for the device, andthe I/O request is scheduled. Eventually, the I/O subsystem sends the request to the device driver. Depending onthe operatingsystem, the request is sent via a subroutine call or anin-kernelmessage. 4. The device driver allocates kernel buffer space to receive the data andschedules the I/O. Eventually, the driver sends commands to the device controller bywriting intothe device- control registers. 5. The device controller operates the device hardware to perform the data transfer. 6. The driver maypoll for status anddata, or it mayhave set up a DMA transfer into kernel memory. We assume that the transfer is managedbya DMA controller, which generates an interrupt whenthe transfer completes. 7. The correct interrupt handler receives the interrupt via the interrupt vector table, stores anynecessarydata, signals the device driver, and returns from the interrupt. 8. The device driver receives the signal, determines which I/O request has completed, determines the request’s status, andsignals the kernel I/O subsystemthat the request has beencompleted. 9. The kernel transfers data or returncodesto the address space ofthe requesting process andmoves the process fromthe wait q ueue back to the readyqueue. 10. Moving the process to the readyqueue unblocks the process. Whenthe scheduler assigns the processto the CPU, the process resumes executionat the completion ofthe systemcall. PERFORMANCE  I/O is a major factor insystemperformance. It placesheavydemands onthe CPU to execute device-driver code and to schedule processes fairlyand efficientlyas theyblock andunblock. The resulting context switches stress the CPU andits hardware caches. I/O also exposes any inefficiencies in the interrupt-handling mechanisms inthe kernel. Inaddition, I/O loads downthe memorybus duringdata copies between controllers and physicalmemoryandagainduring copiesbetweenkernel buffers andapplicationdata space. Coping gracefullywi thall these demands is one of the major concerns of a computer architect.  Although modern computers canhandle manythousands of interrupts per second, interrupt handling is a relatively expensive task. Each interrupt causesthe systemto performa state change, to execute the interrupt handler, andthen to restore state. Programmed I/O can be more efficient thaninterrupt-drivenI/O, if the number of cycles spent in busywaiting is not excessive. An I/O completiontypicallyunblocks a process, leading to the full overhead of a context switch.  (Refer the Network Traffic case in “Assorted Content” to better consolidate what you have read).  ****(To quote from Wiki): Memory-mapped I/O (not to be confused withmemory-mapped file I/O)uses the same addressbus to address both memoryandI/O devices – the memoryand registers ofthe I/O devices are mappedto (associatedwith) address val ues. In memory- mappedI/O, the CPU instructions used to access the memorycan also be used for accessing devices. Each I/O device monitors the CPU's address bus andresponds to anyCPU access of anaddress assigned to that device, connectingthe data bus to the desireddevice's hardware register.  ***Readthe port-mappedI/O (PMIO) (whichis also calledisolatedI/O)vs Memory-mapped I/O (MMIO)content from Wiki. These two are complementary (similar).
  • 11. 11 I/O Systems (Galvin Notes,9th Ed.)  Other systems use separate front-endprocessors for terminal I/O to reduce the interrupt burden onthe mainCPU. For instance, a terminal concentrator can multiplex the traffic fromhundreds of remote terminals into one port on a large computer. An I/O channel is a dedicated, special-purpose CPU found in mainframes and inother high-endsystems. The jobof a channel is to offloadI/O work from the mainCPU. The idea is that the channels keepthe data flowingsmoothly, while the mainCPU remains free to processthe data. Like the device controllers and DMA controllers found insmaller computers, a channel can process more general and sophisticatedprograms, so channelscanbe tuned for particular workloads.  We can employ several principles to improve the efficiency of I/O: • Reduce the number of context switches. • Reduce the number of times that data must be copied in memory while passing between device and application. • Reduce the frequency of interrupts by using large transfers, smart controllers, and polling (if busy waiting can be minimized). • Increase concurrency by using DMA-knowledgeable controllers or channels to offload simple data copying from the CPU. • Move processingprimitives into hardware, to allowtheir operationin device controllers to be concurrent with CPU and bus operation. • Balance CPU, memorysubsystem, bus, and I/O performance, because an overload in any one area will cause idleness in others.  I/O devices varygreatlyincomplexity. For instance, a mouse is simple. The mouse movements andbuttonclicks are converted into numeric values that are passed fromhardware, throughthe mousedevice driver, to the application. Bycontrast, the functionality provided by the Windows disk device driver is complex. It not onlymanages individual disks but also implements RAID arrays (Section 10.7). To do so, it converts an application’s reador write request intoa coordinated set of disk I/O operations. Moreover, it implements sophis ticated error- handling and data-recovery algorithms and takes many steps to optimize disk performance.  Where should the I/O functionalitybe implemented—inthe device hardware, inthe device driver, or inapplication software?Sometimeswe observe the progression depicted in Figure 13.16. o Initially, we implement experimentalI/O algorithms at the application level, because applicationcode is flexible and application bugs are unlikelyto cause system crashes. Furthermore, bydevelopingcode at the applicationlevel, we avoidthe need to reb oot or reload device drivers after everychange to the code. An application-level implementationcan be inefficient, however, because of the overheadof context switches andbecause the application cannot take advantage of internal kernel data structures andkernel functionality(suchas efficient in-kernelmessaging, threading, and locking). o When an application-level algorithmhas demonstratedits worth, we mayreimplement it inthe kernel. Thiscanimprove performance, but the development effort is more challenging, because anoperating-system kernelis a large, complex software system. Moreover, an in-kernel implementationmust be thoroughlydebuggedto avoiddata corruptionandsystemcrashes. o The highest performance maybe obtained througha specialized implementationinhardware, either in the device or inthe controller. The disadvantages of a hardware implementation include the difficultyandexpense of making further improvements or of fixingbugs, the increased development time (months rather thandays), andthe decreasedflexibility. For instance, a hardware RAID controller maynot provide anymeans for the kernel to influence the order or location ofindividualblockreads and writes, even if the kernel has special informationabout the workloadthat wouldenable it to improve the I/O performance. SUMMARY  The basic hardware elements involvedinI/O are buses, device controllers, andthe devices themselves. The work of moving data between devices andmainmemoryis performed bythe CPU as programmedI/O or is offloadedto a DMA controller. The kernel module that controls a device is a device driver. The system-callinterface providedto applications is designed to handle several basic categories of hardware, includingblock devices, character devices, memory-mappedfiles, network sockets, and programmedinterval timers. The system calls usually block the processes that issue them, but nonblocking andasynchronous calls are used bythe kernel itself andbyapplications that must not sleep while waiting for an I/O operation to complete.  The kernel’s I/O subsystem provides numerous services. Among these are I/O scheduling, buffering, caching, spooling, device reservation, and error handling. Another service, name translation, makes the connections betweenhardware devices andthe symbolic file names used byapplications. It involves several levelsof mappingthat translate from character-string names, to specific device drivers and device addresses, and thento physical addresses of I/O ports or bus controllers. Thismapping mayoccur withinthe file-system name space, as it does in UNIX, or in a separate device name space, as it does in MS-DOS.  I/O system callsare costlyinterms of CPU consumption because of the many layers of software between a physical device and an application. These layers implyoverhead fromseveral sources:context switching to cross the kernel’s protection boundary, s ignal and interrupt handling to service the I/O devices, and the load on the CPU and memory system to copy data between kernel buffers and application space.
  • 12. 12 I/O Systems (Galvin Notes,9th Ed.) AssortedContent  Network traffic canalsocause a high context-switch rate. Consider, for instance, a remote login from one machine to another. Each character typed on the local machine must be transportedto the remote machine. On the local machine, the character is typed; a keyboard interrupt is generated;andthe character is passedthroughthe interrupt handler to the device driver, to the kernel, and then to the user process. The user process issues a network I/O system call to send the character to the remote machine. The character then flows into the local kernel, through the network layers that construct a network packet, andintothe network device driver. The network device driver transfers the packet to the network controller, whichsends the character andgeneratesaninterrupt. The interrupt is passed back upthroughthe kernelto cause the network I/O system call to complete. Now, the remote system’s networkhardware receives the packet, and an interrupt is generated. The character is unpackedfrom the network protocols and is given to the appropriate network daemon. The networkdaemon identifies which remote login sessionis involved and passes the packet to the appropriate subdaemon for that session. Throughout this flow, there are context switches and state switches(Figure 13.15). Usually, the receiver echoes the character back to the sender;that approach doubles the work. To eliminate the context switches involved in movingeach character between daemons and the kernel, the Solarisdevelopers reimplemented the telnet daemon using in-kernel threads. Sun estimatedthat this improvement increased the maximum number of network logins from a few hundred to a few thousand on a large server.