Sunteți pe pagina 1din 111

STUDENT SMANUAL TOACCOMPANY OPERATING SYSTEM CONCEPTS SEVENTH EDITION ABRAHAMSILBERSCHATZ Yale University PETERBAERGALVIN CorporateTechnologies GREG GAGNE

WestminsterCollege

Preface This volumeisastudent s manual forthe Seventh Editionof Operating System Concepts, by Abraham Silberschatz, Peter Baer Galvin, and Greg Gagne. It consistsof answerstotheexercisesintheparenttext. Althoughwehave triedtoproduceastudent s manual that willaidallof theusersof ourbook as much as possible,therecan alwaysbe improvements (improved answers, additional questions, sample test questions,programming projects, alternative orders of presentation of the material, additional referen ces, and so on). We invite you, both instructors and students, to help us improve this manual. If you have better solutions to the exercises or other items that would be of use with Operating System Concepts,weinviteyouto send themtousforconsiderationin latereditionsofthismanual.Allcontributionswill, of course,beproperlycreditedtotheir contributor. Internet electronic mailshouldbe addressedto os-book@cs.yale.edu. Physicalmailmaybe senttoAviSilberschatz,YaleUniversity,Departmentof Computer Science,51Prospect Street,P.O.box 208285, NewHaven,CT06520, USA. A. S. P.B.G G. G.

Contents Chapter Introduction ................................................. 1 Chapter Operating-System Structures ................................5 Chapter Processes .................................................... 9 Chapter Threads .....................................................11 Chapter CPU Scheduling ............................................13 Chapter Process Synchronization ....................................17 Chapter Deadlocks ..................................................21 Chapter Memory Management ...................................... 25 Chapter Virtual Memory ............................................ 29 Chapter File-Systems Interface......................................35 Chapter File-Systems Implementation ..............................39 Chapter Mass Storage Structure .....................................43 Chapter I/O Systems ................................................51 Chapter Protection .................................................. 55 Chapter Security ....................................................57 Chapter Distributed

System Structures ............................. 59 Chapter Distributed File Systems ...................................63 Chapter Distributed Coordination ..................................65 Chapter Real-Time Systems .........................................67 Chapter Multimedia Systems .......................................69 Chapter The Linux System ..........................................71 Chapter Windows XP ...............................................79 Chapter Influential Operating Systems .............................83

Introduction 1CHAPTER Exercises 1.1 What arethe threemainpurposesof anoperating system? Answer: Toprovide an environmentforacomputerusertoexecuteprograms oncomputerhardwareinaconvenientand efficientmanner. To allocate the separate resources of the computer as needed to solvetheproblemgiven.The allocationprocessshouldbeasfair and efficient aspossible. Asa controlprogramit servestwomajor functions:(1)supervision of the execution of user programs to preventerrors andimproper useofthecomputer,and(2)management ofthe operationand control of I/O devices. 1.2 Whatarethemaindifferencesbetween operating systemsfor mainframe computers and personal computers? Answer: Generally,operating systemsfor batch systemshavesimpler requirements than forpersonalcomputers.Batch systemsdonot have to be concerned with interacting with a user as much as a personal computer.Asaresult,anoperating system foraPC mustbe concerned withresponse time foraninteractive user.Batch systemsdonot have suchrequirements.A pure batch system also mayhavenot to handle time sharing, whereasanoperating system must switch rapidlybetween differentjobs. 1.3 Listthefourstepsthatarenecessarytorunaprogramona completely dedicated machine. Answer:

Chapter 1 Introduction a. Reserve machine time. b. Manually loadprogramintomemory. c. Load starting address and begin execution. d. Monitorand control executionofprogramfromconsole. 1.4 Wehavestressedtheneedforanoperating systemtomakeefficient use of the computing hardware. When is it appropriate for the operating system to forsakethisprinciple andto waste resources? Whyissuch a system not really wasteful? Answer: Single-user systems should maximize use of the system for the user. A GUI might waste CPU cycles, but it optimizes the user s interactionwiththe system. 1.5 Whatisthemaindifficultythataprogrammermustovercomein writing an operating system for a real-time environment? Answer: Themaindifficultyis keepingthe operating system within the fixed time constraints of a real-time system. If the system does not complete a task in a certain time frame, it may cause a breakdown oftheentire systemitisrunning.Thereforewhen writinganoperating systemforareal-time system,the writermustbesurethathisscheduling schemesdon t allowresponsetimetoexceed thetimeconstraint. 1.6 Consider thevariousdefinitionsof operating system.Consider whether theoperating system should includeapplications such asWebbrowsers andmailprograms.Argueboththatitshouldandthatit shouldnot,and support your answer. Answer: Point.Applications suchaswebbrowsersandemailtoolsare performing an increasingly importantroleinmoderndesktop computer systems.To fulfill thisrole,theyshouldbeincorporatedaspartof the operating system. By doing so, they can provide better performance and better integration with the rest of the system. In addition, these importantapplications canhavethe same look-and-feel as theoperating system software. Counterpoint.The fundamentalroleofthe operating systemisto manage systemresourcessuchasthe CPU,memory, I/O devices,etc.Inaddition, it sroleistorun software applications such as webbrowsersand emailapplications.Byincorporatingsuch applicationsintotheoperating system,weburdenthe operating systemwithadditional functionality. Suchaburdenmayresultintheoperating system performingaless-thansatisfactoryjobat managing systemresources.In addition,weincrease the size of the operating system thereby increasing the likelihood of system crashes and security violations. 1.7 Howdoesthe distinctionbetween kernel mode andusermodefunction as a rudimentary form of protection (security) system? Answer: The distinction between kernel mode and user mode providesarudimentaryformofprot ectioninthe

following manner.Certain instructions could be executed only when the CPU is in kernel mode. Similarly,hardwaredevicescouldbe accessedonlywhentheprogram is executinginkernel mode. Control overwheninterruptscouldbeen

Exercises abledordisabledisalsopossibleonlywhenthe CPUisin kernel mode. Consequently, the CPU has very limited capability when executing in user mode,thereby enforcingprotection of critical resources. 1.8 Whichofthe following instructions shouldbe privileged? a. Set value of timer. b. Read the clock. c. Clear memory. d. Issue a trap instruction. e. Turnoffinterrupts. f. Modify entriesindevice-statustable. g. Switch from user to kernel mode. h. Access I/O device. Answer: Thefollowing operations needtobe privileged:Setvalueof timer,clearmemory, turnoffinterrupts, modify entriesindevice-status table, access I/O device.Therestcanbeperformedin user mode. 1.9 Some earlycomputersprotectedthe operating systemby placingitin amemorypartition that couldnotbe modifiedby eitherthe userjob or theoperating system itself.Describetwo difficultiesthatyou think could arise with such a scheme. Answer: Thedatarequiredbythe operating system(passwords,access controls,accounting information, andsoon) wouldhavetobestored in or passed through unprotected memory and thus be accessible to unauthorized users. 1.10 Some CPUsprovide formorethantwo modesof operation.Whatare twopossibleusesofthese multiple modes? Answer: Although most systemsonlydistinguish between user and kernel modes, some CPUs have supported multiple modes. Multiple modes could be used to provide a finer-grained security policy. For example,ratherthan distinguishingbetweenjust userandkernelmode, youcould distinguishbetween differenttypesof user mode.Perhaps usersbelongingtothesamegroupcouldexecute eachother scode.The machine would go into a specified mode when one of these users was running code. When the machine was in this mode, a member of the groupcouldruncodebelongingto anyoneelseinthegroup. Another possibility would be to provide different distinctions within kernelcode. For example,aspecificmodecouldallow USB devicedrivers to run. This would mean that USB devices could be serviced without havingto switchto kernelmode,therebyessentially allowing USB device driverstoruninaquasi-user/kernel mode. 1.11 Timers couldbeusedtocompute thecurrent time.Provideashort descriptionofhow this couldbeaccomplished. Answer: Aprogramcouldusethefollowingapproachto computethe currenttimeusingtimerinterrupts.Theprogramcouldsetatimerfor

Chapter 1 Introduction some timeinthefutureandgoto sleep.Whenitisawakenedby the interrupt,it couldupdateits localstate,whichitis usingtokeep track ofthenumberofinterruptsithasreceivedthus far.Itcouldthenrepeat thisprocessofcontinually setting timerinterruptsand updatingitslocal statewhenthe interrupts areactually raised. 1.12 Is theInternet a LAN ora WAN? Answer: The Internetisa WAN as thevarious computersare located at geographically differentplacesand areconnectedby long-distance network links.

OperatingSystem Structures 2CHAPTER Exercises 2.1 Whatis thepurposeof system calls? Answer: Systemcalls allowuser-levelprocessestorequest servicesof the operating system. 2.2 What are the five major activities of an operating system in regard to process management? Answer: a. The creation and deletion of both user and system processes b. The suspension and resumption of processes c. Theprovisionof mechanisms forprocess synchronization d. Theprovisionof mechanisms forprocess communication e. Theprovisionof mechanisms fordeadlockhandling 2.3 Whatarethethreemajor activitiesofan operating systeminregardto memory management? Answer: a. Keep track of which partsof memoryarecurrentlybeing used andby whom. b. Decidewhichprocessesaretobeloadedintomemorywhenmemory space becomes available. c. Allocate anddeallocate memory spaceasneeded. 2.4 Whatarethethreemajor activitiesofan operating systeminregardto secondary-storage management? Answer:

Chapter 2 Operating-System Structures Free-space management. Storage allocation. Disk scheduling. 2.5 What is the purpose of the command interpreter? Why is it usually separatefrom thekernel? Answer: Itreadscommandsfromthe user orfromafileof commands andexecutesthem, usuallyby turningthemintoone or more system calls.Itisusually notpartofthekernelsincethe command interpreter is subjecttochanges. 2.6 What system calls havetobe executedbyacommand interpreterorshell in ordertostartanewprocess? Answer: In Unix systems,a fork system call followedbyan exec system callneedtobe performedtostartanewprocess.The fork call clones the currently executing process, while the exec call overlays a new process basedona differentexecutableover thecallingprocess. 2.7 Whatis thepurposeof systemprograms? Answer: System programs can be thought of as bundles of useful system calls.Theyprovide basicfunctionalitytousers so that usersdo not needtowritetheir ownprogramstosolvecommonproblems. 2.8 Whatisthemainadvantageofthelayered approachto system design? What arethe disadvantagesof using thelayered approach? Answer: As in all cases of modular design, designing an operating systeminamodularwayhas several advantages.The systemis easier to debug and modify because changes affect only limited sections of the system rather than touching all sections of the operating system. Informationiskeptonlywhereitis neededandisaccessibleonly within adefined andrestricted area,soany bugsaffectingthatdatamustbe limited to a specific module or layer. 2.9 Listfiveservicesprovidedby anoperating system.Explainhoweach provides conveniencetothe users. Explainalsoinwhich casesitwould be impossiblefor user-levelprogramstoprovidethese services. Answer: a. Program execution.The operating system loadsthe contents (or sections)of a fileintomemoryandbegins itsexecution.A userlevelprogramcouldnotbet rustedtoproperly allocate CPU time.

b. I/O operations.Disks, tapes, serial lines,and otherdevicesmust becommunicatedwithat a verylow level.The userneed only specifythe deviceand the operationtoperformonit,whilethe system converts that request into device-or controller-specific commands. User-levelprogramscannotbetrustedtoaccessonly devicestheyshouldhaveaccessto andtoaccess themonly when they are otherwise unused. c. File-system manipulation.Therearemanydetailsin filecreation, deletion,allocation,and naming that usersshouldnothavetoperform. Blocksofdiskspace areusedbyfilesand mustbe tracked.

Exercises Deleting a file requires removing the name file information and freeing theallocatedblocks.Protectionsmustalsobecheckedto assureproperfileaccess. Userprogramscouldneitherensureadherencetoprotectionmetho ds norbetrustedto allocateonlyfree blocks anddeallocate blocks on filedeletion. d. Communications. Message passing between systems requires messagestobeturnedintopacketsof information, senttothenetwork controller, transmitted across a communications medium, andreassembledbythe destination system.Packetorderingand data correction must take place. Again, user programs might not coordinate access to the network device, or they might receive packetsdestinedfor otherprocesses. e. Error detection.Error detectionoccursatboththehardwareand software levels.Atthehardwarelevel,all data transfersmustbe inspectedtoensurethatdatahavenotbeen corruptedintransit. All data on media must be checked to be sure they have not changed since they were written to the media. At the software level,media mustbecheckedfor dataconsistency; forinstance, whetherthenumberofallocatedandunallocatedblocksofstorage matchthe totalnumberonthedevice.There,errorsarefrequently process-independent (for instance, the corruption of data on a disk),sothere mustbeaglobalprogram(the operating system) that handlesall typesof errors. Also,byhavingerrorsprocessed bytheoperating system,processesneednotcontaincodetocatch andcorrect allthe errors possibleona system. 2.10 Whatis thepurposeof system calls? Answer: Systemcalls allowuser-levelprocessestorequest servicesof the operating system. 2.11 What are the main advantages of the microkernel approach to system design? Answer: Benefits typically include the following (a) adding a new servicedoesnotrequiremodifying thekernel, (b)itismoresecureas more operations aredoneinusermodethaninkernelmode, and(c) a simpler kernel design and functionality typically results in a more reliable operating system. 2.12 Whydosome systemsstoretheoperating systeminfirmware,andothers on disk? Answer: Forcertain devices, such as handheld PDAsand cellulartelephones, adiskwithafilesystemmaybenotbe availableforthedevice. In this situation, the operating system must be stored in firmware. 2.13 Howcoulda systembe designedto allowa choiceof operating systems to bootfrom?Whatwouldthebootstrapprogram needtodo? Answer: Consider a system that would like to run both Windows

XP andthree differentdistributionsof Linux(e.g.,RedHat, Debian,and Mandrake).Each operatingsystemwillbestoredondisk.Duringsystem boot-up,aspecialprogram(whichwewill callthe boot manager)will determinewhich operating systemto boot into.Thismeans that rather

Chapter 2 Operating-System Structures initially bootingtoanoperating system,the boot managerwill firstrun during system startup. It is this boot manager that is responsible for determiningwhich systemto bootinto.Typically boot managers must be storedat certainlocationsoftheharddisktoberecognizedduring system startup. Boot managers oftenprovide theuserwithaselectionof systemstobootinto;boot managersarealsotypically designedtoboot intoadefault operating systemif no choiceis selectedby theuser.

Processes 3CHAPTER Exercises 3.1 Palm OS provides no means of concurrent processing. Discuss three major complications that concurrent processing adds to an operating system. Answer: a. A method of time sharing must be implemented to allow each of several processes to have access to the system. This method involvesthepreemptionofprocessesthatdonotvoluntarily give up the CPU(byusinga system call, forinstance) andthe kernel beingreentrant(somorethanoneprocessmaybeexecuting kernel code concurrently). b. Processesand systemresourcesmusthaveprotections andmust beprotectedfromeachother.Anygivenprocessmustbe limited in the amount of memory it can use and the operations it can performondevices likedisks. c. Care mustbe takeninthe kerneltopreventdeadlocksbetween processes, soprocesses aren t waitingfor each other sallocated resources. 3.2 TheSun UltraSPARC processor has multipleregister sets.Describethe actions of a context switch if the new context is already loaded into oneoftheregister sets.Whatelsemusthappenifthe newcontextisin memory rather than in a register set and all the register sets are in use? Answer: The CPUcurrent-register-setpointerischangedtopointtothe setcontainingthenewcontext,which takesvery littletime.Ifthecontext isin memory,oneof thecontextsinaregister setmustbechosenandbe movedto memory,andthenewcontextmustbeloadedfrommemory

Chapter 3 Processes into theset.Thisprocess takesa littlemoretimethanonsystemswith onesetofregisters, dependingonhowareplacement victimis selected. 3.3 Whenaprocess createsa newprocess usingthe fork() operation, which ofthefollowingstateissharedbetweentheparentprocessandthechild process? a. Stack b. Heap c. Shared memory segments Answer: Only theshared memorysegmentsare sharedbetween the parent process andthe newly forked child process. Copies of the stack andthe heap aremadefor thenewly createdprocess. 3.4 Again considering the RPC mechanism, consider the exactly once semantic. Doesthe algorithmforimplementingthissemanticexecutecorrectlyevenifthe ACK messagebacktotheclientislostduetoanetwork problem? Describethesequenceofmessagesandwhether "exactlyonce" is still preserved. Answer: The exactly once semantics ensurethat a remore procedure willbeexecuted exactlyonceandonly once.Thegeneralalgorithmfor ensuring this combines an acknowledgment (ACK)schemecombined with timestamps (or some other incremental counter that allows the serverto distinguishbetween duplicatemessages). Thegeneral strategyisforthe clienttosendthe RPCtotheserveralong withatimestamp.The client will also starta timeoutclock.The client willthen waitforoneoftwooccurrences:(1)itwillreceivean ACKfrom the server indicatingthat the remoteprocedure wasperformed,or(2) it will time out.If theclient timesout,it assumes theserver wasunable toperformtheremoteproceduresothe client invokesthe RPC asecond time,sendingalater timestamp. Theclient maynotreceivethe ACK for oneoftworeasons:(1)the original RPCwasneverreceivedbytheserver, or (2) the RPC was correctly received andperformed bythe server butthe ACK waslost.In situation(1),the useofACKsallows theserver ultimatelytoreceiveand performthe RPC.Insituation(2),theserverwill receivea duplicate RPC andit will usethe timestamptoidentifyit asa duplicatesoasnotto performthe RPCasecondtime.Itis importantto notethattheservermustsendasecond ACKbacktotheclientto inform theclient theRPC hasbeen performed. 3.5 Assume thatadistributed systemis susceptibletoserver failure.What mechanisms wouldberequiredtoguarantee the exactly once semantics for execution of RPCs? Answer: The server should keep track in stable storage (such as a disk log) information regarding what RPC operations were received, whether they were successfully performed, and the results associated

withtheoperations.Whenaservercrashtakesplaceanda RPC message isreceived,the server cancheck whetherthe RPChadbeenpreviously performed and therefore guarantee exactly once semanctics for the execution of RPCs.

Threads 4CHAPTER Exercises 4.1 Providetwoprogramming examplesin whichmultithreadingprovides betterperformance thanasingle-threaded solution. Answer: (1)AWebserverthat services eachrequestinaseparatethread. 2) (A parallelized application such as matrix multiplication where (different partsofthe matrix maybeworkedoninparallel.(3)An(interactive GUIprogramsuchasadebuggerwhereathreadisused(to monitor user input, another thread represents the running (application, and a thirdthreadmonitorsperformance. 4.2 What aretwo differencesbetween user-levelthreadsand kernel-level threads? Underwhatcircumstancesis onetypebetterthanthe other? Answer: (1)User-levelthreadsareunknownbythekernel,whereasthe kernelis awareofkernelthreads.(2)On systemsusing eitherM:1orM:N mapping,userthreadsarescheduledbythethreadlibraryandthekernel scheduleskernelthreads.(3)Kernelthreadsneednotbeassociatedwith aprocesswhereas everyuserthreadbelongstoaprocess. Kernelthreads aregenerallymoreexpensivetomaintainthanuserthreadsasthey must berepresentedwitha kernel data structure. 4.3 Describetheactions takenbya kerneltocontextswitchbetween kernellevel threads. Answer: Contextswitchingbetween kernelthreadstypicallyrequires savingthevalueofthe CPUregistersfromthethreadbeingswitchedout andrestoring the CPUregistersofthe newthreadbeing scheduled. 4.4 Whatresourcesare usedwhenathreadiscreated?Howdotheydiffer from thoseusedwhenaprocessiscreated? Answer: Because a thread is smaller than a process, thread creation typically uses fewerresourcesthanprocesscreation.Creating aprocess

Chapter 4 Threads requiresallocatingaprocess controlblock (PCB),aratherlargedata structure. The PCB includes a memory map, list of open files, and environment variables. Allocating andmanagingthe memory mapistypically themosttime-consumingactivity.Creatingeitherauserorkernelthread involves allocatingasmalldatastructuretoholdaregisterset,stack,and priority. 4.5 Assume an operating system maps user-level threadstothe kernel usingthe many-to-manymodel andthemappingisdonethrough LWPs. Furthermore, the system allows developerstocreatereal-time threads. Isit necessarytobindareal-timethreadtoan LWP?Explain. Answer: Yes.Timingiscrucialtoreal-time applications.Ifathreadis markedasreal-timebutis notboundtoan LWP,thethreadmayhave towaittobe attachedtoan LWP before running.Considerif areal-time threadisrunning(isattachedtoan LWP)andthenproceedstoblock(i.e. must perform I/O,hasbeenpreemptedby ahigher-priorityreal-time thread,iswaiting fora mutual exclusionlock, etc.)While thereal-time threadis blocked,the LWP itwasattachedtohasbeen assignedtoanother thread.Whenthereal-timethreadhas been scheduledtorun again,it must first wait to be attached to an LWP.Bybinding an LWP to a realtimethreadyou areensuringthethreadwillbeabletorunwithminimal delay onceitis scheduled. 4.6 APthreadprogramthatperformsthe summation function wasprovided in Section4.3.1.Rewrite thisprograminJava. Answer: PleaserefertothesupportingWebsiteforsourcecodesolution.

CPU Scheduling 5CHAPTER Exercises 5.1 ACPU schedulingalgorithm determinesanorderfortheexecutionofits scheduledprocesses. Given n processestobescheduled on oneprocessor, howmanypossibledifferent schedulesare there? Giveaformulain terms of n. Answer: n! (n factorial = n n 1 n 2 ... 2 1). 5.2 Define thedifferencebetween preemptiveand nonpreemptivescheduling. Answer: Preemptive scheduling allows a process to be interrupted in the midst of its execution, taking the CPU away and allocating it to anotherprocess. Nonpreemptivescheduling ensuresthataprocess relinquishes control of the CPU only when it finishes with its current CPU burst. 5.3 Suppose thatthefollowingprocesses arriveforexecutionatthetimes indicated. Eachprocesswillrunthe listedamountoftime.In answering thequestions,use nonpreemptiveschedulingand base alldecisions on theinformation youhaveatthe time thedecisionmustbemade. Process ArrivalTime BurstTime P1 0.0 8 P2 0.4 4 P3 1.0 1 a. Whatistheaverageturnaroundtimefor theseprocesseswiththe FCFS scheduling algorithm?

Chapter 5 CPU Scheduling b. Whatistheaverageturnaroundtimefortheseprocesseswiththe SJF scheduling algorithm? c. The SJF algorithmissupposedtoimprove performance, butnotice that we chosetorunprocess P1 at time0because we didnot know that twoshorterprocesseswould arrive soon.Compute what the averageturnaroundtimewillbeifthe CPUisleftidleforthe first1 unitandthen SJF schedulingisused. Rememberthatprocesses P1 and P2 arewaiting during this idle time,sotheir waitingtimemay increase. This algorithm could be known as future-knowledge scheduling. Answer: a. 10.53 b. 9.53 c. 6.86 Rememberthat turnaroundtimeis finishingtimeminusarrivaltime,so youhavetosubtractthe arrivaltimesto computethe turnaround times. FCFSis11if youforgettosubtractarrivaltime. 5.4 What advantageisthereinhavingdifferenttime-quantumsizes on different levels of a multilevel queueing system? Answer: Processes that need more frequent servicing, for instance, interactiveprocessessuchaseditors,canbeinaqueue withasmall time quantum.Processeswithnoneedforfrequentservicingcanbeinaqueue withalargerquantum,requiringfewercontext switchesto completethe processing,and thus making moreefficient useofthe computer. 5.5 Many CPU-scheduling algorithms are parameterized. For example, the RR algorithmrequiresa parametertoindicatethe time slice. Multilevel feedback queues requireparameters todefinethenumberofqueues, the scheduling algorithms for each queue, the criteria used to move processesbetween queues,and so on. These algorithms are thus really sets of algorithms (for example, the setof RR algorithmsforalltime slices,andsoon).Onesetof algorithms mayincludeanother(forexample,the FCFS algorithmisthe RR algorithm with an infinite time quantum).What(if any)relation holdsbetweenthe following pairs of sets of algorithms? a. Priority and SJF b. Multilevel feedbackqueues and FCFS c. Priority and FCFS d. RR and SJF Answer:

a. Theshortestjob hasthe highestpriority. b. Thelowestlevelof MLFQis FCFS.

Exercises 15 c. FCFS givesthehighest prioritytothejobhavingbeenin existence thelongest. d. None. 5.6 Suppose that a scheduling algorithm (at the level of short-term CPU scheduling) favors thoseprocesses thathaveusedthe leastprocessor timeintherecentpast.Whywill this algorithmfavor I/O-boundprograms and yet not permanently starve CPU-bound programs? Answer: It will favorthe I/O-boundprograms becauseoftherelatively short CPU burst request by them; however, the CPU-bound programs will notstarvebecause the I/O-boundprograms willrelinquishthe CPU relativelyoften todotheir I/O. 5.7 Distinguishbetween PCS and SCS scheduling. Answer: PCS scheduling is done local to the process. It is how the thread library schedulesthreads onto available LWPs. SCS schedulingis thesituation wherethe operating system scheduleskernelthreads.On systemsusing either many-to-oneormany-to-many,thetwo scheduling modelsarefundamentallydifferent.On systemsusing one-to-one, PCS and SCS arethe same. 5.8 Assume an operating system maps user-level threadstothe kernel using themany-to-manymodelwherethe mappingisdone throughthe use ofLWPs. Furthermore,the system allowsprogramdeveloperstocreate real-timethreads.Isit necessaryto bindareal-timethreadtoan LWP? Answer: Yes, otherwise a user thread may have to compete for an available LWP prior to being actually scheduled. By binding the user threadtoan LWP,thereisno latencywhile waitingforan available LWP; thereal-time userthreadcanbescheduled immediately.

Process Synchronization 6CHAPTER Exercises 6.1 In Section6.4 we mentionedthatdisablinginterruptsfrequentlycould affect the system s clock. Explain why it could and how such effects couldbe minimized. Answer: The system clockisupdatedat everyclock interrupt.Ifinterrupts were disabled particularlyforalongperiodof time itis possible the system clock could easily lose the correct time. The systemclockis also used forschedulingpurposes. Forexample,the time quantumforaprocessis expressedasanumberofclockticks.At every clockinterrupt,the schedulerdeterminesif the time quantumfor the currentlyrunningprocesshas expired.Ifclockinterruptsweredisabled, thescheduler couldnot accurately assign time quantums.Thiseffectcan be minimizedbydisablingclock interrupts foronly veryshort periods. 6.2 The Cigarette-Smokers Problem.Consider a system with three smoker processesand one agent process. Each smoker continuouslyrollsacigarette andthensmokesit. Buttorolland smokea cigarette,the smoker needs threeingredients:tobacco,paper,and matches.Oneofthe smokerprocesseshas paper, anotherhas tobacco,and thethird hasmatches.The agent has an infinite supply of all three materials. The agent places twoofthe ingredientsonthe table. Thesmokerwho hastheremaining ingredient then makes and smokes a cigarette, signaling the agent on completion.The agentthenputsout anothertwoof thethree ingredients, and thecyclerepeats.Writeaprogramto synchronize theagent andthe smokersusing Java synchronization. Answer: PleaserefertothesupportingWebsiteforsourcecodesolution. 6.3 GivethereasonswhySolaris,Windows XP,andLinuximplement multiplelocking mechanisms.Describethe circumstancesunder whichthey

Chapter 6 Process Synchronization use spinlocks, mutexes, semaphores, adaptive mutexes, and condition variables.In each case,explainwhythe mechanismisneeded. Answer: These operating systems provide different locking mechanisms depending on the application developers needs. Spinlocks are useful formultiprocessor systemswhereathreadcanruninabusy-loop (forashortperiodoftime) ratherthanincurringtheoverheadofbeing putina sleep queue. Mutexesare useful forlockingresources. Solaris2 uses adaptive mutexes, meaningthatthe mutexisimplemented witha spin lock on multiprocessor machines. Semaphores and condition variablesare more appropriatetoolsfor synchronization whenaresource must be held for a long period of time, since spinning is inefficient for a long duration. 6.4 Explainthe differences,in termsof cost, amongthe threestorage types volatile,nonvolatile,and stable. Answer: Volatile storagereferstomainandcachememoryandis very fast.However,volatile storagecannotsurvive system crashesorpoweringdownthe system.Nonvolatile storagesurvives system crashesand powered-down systems. Disks and tapes are examples of nonvolatile storage. Recently, USB devices usingerasable program read-only memory (EPROM)haveappearedprovidingnonvolatile storage. Stable storagereferstostorage that technically can never belostasthereare redundant backup copiesof thedata(usually on disk). 6.5 Explain the purpose of the checkpoint mechanism. How often should checkpointsbeperformed?Describehow thefrequencyofcheckpoints affects: Systemperformancewhennofailure occurs The timeit takestorecoverfromasystemcrash The timeit takestorecoverfromadiskcrash Answer: A checkpoint log record indicates that a log record and its modifieddatahas been writtentostablestorage andthatthe transaction neednottoberedoneincaseofasystemcrash. Obviously,themoreoften checkpointsare performed,theless likelyitisthat redundant updates will havetobe performedduringtherecoveryprocess. System performancewhennofailure occurs Ifnofailuresoccur, the system must incurthe costof performing checkpointsthatare essentially unnecessary.Inthissituation,performingcheckpoints less often will lead to better system performance. The timeit takestorecoverfroma system crash Theexistenceofa checkpointrecordmeansthatanoperation will nothavetobe redone during system recovery. In this situation, the more often checkpointswereperformed,the fastertherecoverytimeisfroma system crash. The timeit takestorecoverfromadiskcrash The existenceof a checkpointrecordmeansthatanoperation will nothavetobe redone during system recovery. In this situation, the more often

Exercises 19 checkpointswereperformed,the fastertherecoverytimeisfroma disk crash. 6.6 Explainthe conceptoftransaction atomicity. Answer: A transaction is a series of read and write operations upon some data followedbya commitoperation.Ifthe seriesof operationsin atransaction cannotbecompleted,the transactionmustbeabortedand theoperationsthatdid take placemustberolledback.Itis important that theseriesof operationsina transaction appear as oneindivisible operationtoensurethe integrityofthe data beingupdated.Otherwise, data couldbecompromisedif operationsfrom two(or more)different transactions were intermixed. 6.7 Show that some schedules are possible under the two-phase locking protocol butnot possibleunder thetimestampprotocol,and vice versa. Answer: Aschedulethatisallowedinthe two-phaselockingprotocol butnotin thetimestampprotocol is: step T0 T1 Precedence 1 lock-S(A) 2 read(A) 3 lock-X(B) 4 write(B) 5 unlock(B) 6 lock-S(B) 7 read(B) T1 . T0 8 unlock(A) 9 unlock(B) This scheduleis notallowedinthe timestampprotocolbecauseat step 7, theW-timestampof B is 1. A schedule that is allowed in the timestamp protocol but not in the two-phaselockingprotocol is: step T0 T1 T2 1 write(A) 2 write(A) 3 write(A) 4 write(B) 5 write(B) This schedule cannothavelockinstructionsaddedtomakeitlegal under two-phaselockingprotocol because T1 must unlock( A)between steps2 and3, and must lock(B)between steps4and5. 6.8 The wait() statementinall Javaprogramexampleswas partofa while

loop. Explain why you would always need to use a while statement when using wait() and whyyou would never use an if statement. Answer: Thisisan importantissuetoemphasize!Javaonlyprovides anonymousnotification you cannotnotifya certainthreadthata cer

Chapter 6 Process Synchronization tain conditionistrue. Whenathreadisnotified,itisitsresponsibility to re-check the condition that it is waiting for. If a thread did not recheckthe condition, it mighthavereceivedthenotificationwithoutthe conditionhavingbeen met.

7CHAPTER7CHAPTER Deadlocks Exercises 7.1 List three examples of deadlocks that are not related to a computersystem environment. Answer: Two cars crossing a single-lane bridge from opposite directions. Aperson goingdowna ladderwhile anotherpersonisclimbingup theladder. Two trains travelingtowardeachother on thesametrack. Two carpenters whomustpound nails.Thereisasinglehammer anda single bucketof nails.Deadlockoccursif onecarpenter has thehammerand theother carpenterhas thenails. 7.2 Suppose thata systemisinan unsafe state. Show thatitis possiblefor theprocessestocompletetheir executionwithout entering adeadlock state. Answer: An unsafe statemay notnecessarily leadto deadlock,itjust meansthatwecannotguarantee thatdeadlock will notoccur. Thus,it is possiblethata systemin an unsafe statemay still allowallprocesses to complete withoutdeadlockoccurring.Considerthe situationwhere a systemhas12resources allocatedamongprocesses P0, P1,and P2.The resourcesare allocatedaccordingtothe following policy: Max Current Need P0 10 5 5 P1 4 2 2 P2 9 3 6

Chapter 7 Deadlocks for (inti=0;i <n; i++) { // first find a thread that can finish for (intj=0;j <n; j++) { if (!finish[j]) { boolean temp = true; for (intk=0;k <m; k++) { if (need[j][k] > work[k]) temp = false; } if (temp) { // if this thread can finish finish[j]

= true; for (intx=0;x <m; x++) work[x] += work[j][x]; } } } } Figure 7.1 Banker s algorithm safety algorithm. Currently there are two resources available. This system is in an unsafe stateasprocess P1couldcomplete,therebyfreeing atotalof four resources.Butwecannotguarantee thatprocesses P0 and P2 can complete. However,itispossiblethataprocessmayreleaseresourcesbefore requestinganyfurther.For example,process P2 couldreleasearesource, therebyincreasingthetotalnumberofresourcestofive.This allowsprocess P0to complete,which wouldfreea totalof nineresources,thereby allowing process P2 to complete as well. 7.3 Provethatthe safety algorithmpresentedinSection7.5.3 requires an order of m n2 operations. Answer: Figure7.1providesJavacodethatimplement thesafetyalgorithmof thebanker salgorithm (the complete implementationof thebanker s algorithmisavailablewiththe source code download). As canbeseen,the nested outerloops bothof whichloopthrough n times provide the n2 performance.Withintheseouter loopsaretwo sequential innerloopswhichloop m times. Thebig-ohofthisalgorithm is therefore O(m n2). 7.4 Consider a computer system that runs 5,000 jobs per month with no deadlock-prevention or deadlock-avoidance scheme.Deadlocks occur abouttwicepermonth,andtheoperatormustterminateandrerun about 10jobsperdeadlock.Eachjobisworth about$2(in CPU time),andthe

jobs terminated tendtobe abouthalf-donewhenthey are aborted. A systems programmer has estimated that a deadlock-avoidance algorithm(likethe banker s algorithm) couldbeinstalledinthe system withanincreaseintheaverageexecutiontimeperjobofabout10percent. Sincethe machinecurrentlyhas30-percentidletime,all5,000jobsper monthcould stillbe run, although turnaround time wouldincreaseby about20percent on average.

Exercises 23 a. What are the arguments for installing the deadlock-avoidance algorithm? b. Whataretheargumentsagainst installingthedeadlock-avoidance algorithm? Answer: An argument forinstallingdeadlockavoidancein the system isthatwecouldensuredeadlockwouldneveroccur.In addition,despite theincreaseinturnaroundtime, all5,000 jobs couldstill run. An argument against installing deadlock avoidance software is that deadlocksoccurinfrequentlyand theycost littlewhentheydooccur. 7.5 Canasystemdetectthatsomeofitsprocessesarestarving?Ifyou answer yes, explainhowit can.Ifyouanswer no, explainhow the system candealwiththe starvationproblem. Answer: Starvationisadifficulttopicto defineasitmaymeandifferent thingsfordifferent systems.Forthe purposesof this question,wewill define starvationasthesituationwhereby aprocessmustwaitbeyond a reasonableperiod oftime perhapsindefinitely before receiving a requested resource. One way of detecting starvation would be to first identifyaperiodoftime T thatisconsideredunreasonable. Whena processrequestsaresource,atimerisstarted.Iftheelapsedtimeexceeds T,thenthe processis consideredtobe starved. One strategy for dealing with starvation would be to adopt a policy whereresources areassigned onlytotheprocessthathasbeenwaiting thelongest.For example, if process Pa hasbeen waitinglongerforresource X than process Pb ,the requestfromprocess Pb wouldbedeferred untilprocess Pa srequesthasbeen satisfied. Anotherstrategywouldbe less strict than what wasjustmentioned.In this scenario,aresourcemightbegrantedtoaprocessthathaswaitedless than anotherprocess,providingthatthe otherprocessis notstarving. However, if another process is considered to be starving, its request wouldbesatisfiedfirst. 7.6 Consider thefollowingresource-allocation policy.Requests andreleases forresources areallowed at anytime.If arequestforresourcescannot be satisfiedbecausetheresourcesarenotavailable,thenwecheck any processesthatareblocked, waitingforresources.Iftheyhavethedesired resources,thentheseresourcesaretakenawayfromthemandare given totherequestingprocess.The vectorof resources forwhichtheprocess is waitingisincreasedto includetheresourcesthatweretaken away. For example, consider a system with three resource types and the vector Available initialized to (4,2,2). If process P0 asks for(2,2,1),itgets

them.If P1 asks for(1,0,1),itgetsthem. Then,if P0 asks for(0,0,1),it is blocked(resource notavailable).If P2 nowasks for(2,0,0),itgetsthe availableone(1,0,0)and onethatwas allocatedto P0(since P0isblocked). P0 s Allocation vectorgoesdownto(1,2,1) andits Need vectorgoesupto (1,0,1). a. Candeadlockoccur?Ifyouanswer yes ,giveanexample.Ifyou answer no, specify which necessary condition cannot occur. b. Canindefinite blocking occur?Explainyouranswer.

Chapter 7 Deadlocks Answer: a. Deadlock cannotoccurbecausepreemptionexists. b. Yes.Aprocessmayneveracquirealltheresourcesitneedsifthey are continuouslypreemptedby a series of requests such asthose of process C. 7.7 Suppose that youhavecoded thedeadlock-avoidancesafetyalgorithm and nowhavebeen askedtoimplementthedeadlock-detectionalgorithm. Canyoudosoby simply usingthe safety algorithm codeand redefining Ma xi = Waitingi + Allocationi ,where Waitingi is a vector specifying the resources process i is waitingfor, and Allocationi is as definedinSection 7.5? Explainyouranswer. Answer: Yes. The Max vector represents the maximum request a process may make.Whencalculating thesafety algorithm we usethe Need matrix, which represents Max Allocation.Another waytothinkof thisis Max = Need + Allocation.Accordingtothe question,the Waiting matrix fulfills a role similartothe Need matrix,therefore Max = Waiting + Allocation. 7.8 Is it possible to have a deadlock involving only one single process? Explainyour answer. Answer: No.Thisfollows directlyfrom thehold-and-wait condition.

Memory Management 8CHAPTER Exercises 8.1 Name twodifferences between logicaland physical addresses. Answer: Alogical addressdoesnotrefertoanactualexistingaddress; rather,itreferstoan abstractaddressin an abstract addressspace.Contrastthiswitha physicaladdressthatreferstoanactualphysicaladdress in memory.Alogical addressisgeneratedbythe CPUandistranslated intoaphysicaladdressbythe memory management unit(MMU).Therefore, physicaladdressesare generatedbythe MMU. 8.2 Considera systemin whichaprogramcanbe separatedintotwo parts: code and data. The CPU knows whether it wants an instruction (instructionfetch) ordata(data fetch orstore).Therefore,twobase limit register pairsareprovided:one forinstructions and onefor data.The instruction base limit register pair is automatically read-only, so programscanbe shared amongdifferent users. Discussthe advantagesand disadvantages ofthis scheme. Answer: Themajor advantageof thisschemeisthatitisaneffective mechanismfor code anddatasharing.For example, only onecopyofan editororacompilerneedstobekeptinmemory, andthiscodecanbe sharedby allprocesses needingaccess to theeditororcompilercode. Anotheradvantageisprotectionof code againsterroneous modification. The only disadvantage is that the code and data must be separated, whichisusually adheredtoina compiler-generatedcode. 8.3 Whyare page sizesalwayspowersof2? Answer: Recall that pagingis implementedbybreakingupanaddress intoapageandoffsetnumber.Itismostefficienttobreak theaddress into X page bits and Y offset bits, rather than perform arithmetic on theaddresstocalculatethepagenumberandoffset.Because eachbit

Chapter 8 Memory Management positionrepresentsapowerof2,splittinganaddressbetweenbitsresults inapagesizethatisa powerof2. 8.4 Consider a logical address space of eight pages of 1024 words each, mappedontoa physicalmemoryof32frames. a. Howmanybitsare thereinthe logicaladdress? b. Howmanybitsarethereinthephysical address? Answer: a. Logicaladdress:13bits b. Physical address: 15 bits 8.5 Whatistheeffectof allowing twoentriesinapagetableto pointtothe same page frameinmemory? Explainhow thiseffect couldbeusedto decreasetheamountoftimeneededtocopyalarge amountof memory from oneplaceto another. Whateffect wouldupdatingsomebyteonthe onepagehaveonthe otherpage? Answer: By allowing twoentriesinapagetableto pointtothe same page frameinmemory,userscansharecodeanddata.Ifthecodeisreentrant, much memory spacecanbe savedthroughthe shared useoflarge programs such as text editors, compilers,and database systems. Copying large amounts of memory could be effected by having different page tables pointtothe same memory location. However, sharing of nonreentrant code or data means that any user having accesstothecodecanmodifyitandthesemodifications would bereflectedintheother user s copy. 8.6 Describeamechanismbywhichone segmentcouldbelongtotheaddress spaceoftwo differentprocesses. Answer: Sincesegment tables area collection ofbase limitregisters, segmentscanbesharedwhenentriesinthesegmenttableoftwodifferent jobs pointtothe same physicallocation. Thetwo segmenttablesmust have identicalbasepointers,andtheshared segment numbermustbe thesameinthe twoprocesses. 8.7 Sharingsegmentsamongprocesseswithoutrequiringthe same segment numberis possibleina dynamically linkedsegmentation system. a. Defineasystemthatallowsstaticlinkingandsharingofsegments withoutrequiring that thesegment numbersbethe same. b. Describeapagingschemethatallows pagestobesharedwithout requiringthatthe page numbersbethe same. Answer: Both of theseproblemsreducetoa programbeing able to referencebothits owncodeand itsdatawithout knowingthe segmentor page number associated with theaddress. MULTICS solved thisproblem

by associating four registers with each process. One register had the addressofthe currentprogram segment, anotherhadabaseaddressfor thestack,anotherhada base addressfortheglobaldata,andsoon.The ideaisthat allreferenceshavetobeindirectthrougharegisterthatmaps tothecurrent segmentorpagenumber.By changing theseregisters,the

Exercises 27 same code canexecute fordifferentprocesseswithout thesamepageor segment numbers. 8.8 Inthe IBM/370,memoryprotectionisprovidedthroughtheuseof keys. Akeyisa4-bit quantity.Each2Kblockof memoryhasakey(thestorage key) associated with it. The CPU also hasa key(theprotectionkey) associated with it. A store operation is allowed only if both keys are equal, orif eitheris zero.Whichofthefollowingmemory-management schemes could be used successfully with this hardware? a. Bare machine b. Single-user system c. Multiprogramming withafixed numberofprocesses d. Multiprogramming withavariablenumberofprocesses e. Paging f. Segmentation Answer: a. Protection notnecessary,set systemkeyto0. b. Set systemkeyto0whenin supervisor mode. c. Region sizesmustbefixedinincrementsof2kbytes,allocatekey with memory blocks. d. Same as above. e. Frame sizes must be in increments of 2k bytes, allocate key with pages. f. Segmentsizes mustbein incrementsof2k bytes, allocatekeywith segments.

Virtual Memory 9CHAPTER Exercises 9.1 Under what circumstances do page faults occur? Describe the actions takenbythe operating system whenapagefault occurs. Answer: Apagefault occurswhenan accesstoapagethathasnotbeen broughtintomainmemorytakes place. Theoperating system verifies thememoryaccess, abortingtheprogramifitis invalid.Ifitisvalid,a free frameislocatedand I/O isrequestedtoreadtheneeded pageinto thefreeframe.UponcompletionofI/O,theprocesstable andpagetable areupdated andthe instructionisrestarted. 9.2 Assume that you have a page-reference string for a process with m frames (initially all empty). The page-reference string has length p; n distinct page numbersoccurinit. Answer thesequestions forany pagereplacementalgo rithms: a. Whatisalower boundonthe numberof page faults? b. Whatis an upperbound on thenumberofpagefaults? Answer: a. n b. p 9.3 Which of the following programming techniques and structures are good fora demand-pagedenvironment?Which are notgood ?Explainyour answers. a. Stack b. Hashed symboltable

Chapter 9 Virtual Memory c. Sequential search d. Binary search e. Pure code f. Vector operations g. Indirection Answer: a. Stack good. b. Hashed symboltable not good. c. Sequential search good. d. Binary search not good. e. Pure code good. f. Vector operations good. g. Indirection notgood. 9.4 Consider the following page-replacement algorithms. Rank these algorithms on a five-point scale from bad to perfect according to theirpage-faultrate. SeparatethosealgorithmsthatsufferfromBelady s anomalyfromthose thatdo not. a. LRU replacement b. FIFO replacement c. Optimal replacement d. Second-chance replacement Answer: Rank Algorithm SufferfromBelady sanomaly 1 Optimal no 2 LRU no 3 Second-chance yes 4 FIFO yes 9.5 When virtualmemoryisimplementedinacomputingsystem,thereare certaincosts associatedwith thetechniqueand certainbenefits.Listthe costsandthebenefits.Isitpossibleforthecoststo exceedthebenefits? Ifitis,whatmeasurescanbe takentoensurethatthisdoesnothappen? Answer: Thecosts areadditional hardwareandsloweraccess time.The benefitsare good utilizationofmemoryand larger logicaladdressspace than physical address space. 9.6 An operating system supports a paged virtual memory, using a central processorwitha cycletimeof1 microsecond.It costsanadditional1 microsecondtoaccessapageother than thecurrent one. Pageshave 1000

Exercises 31 words,andthepaging deviceisadrumthatrotatesat3000revolutions per minute and transfers 1 million words per second. The following statisticalmeasurementswereobtainedfromthe system: 1percentofallinstructions executed accesseda page otherthanthe currentpage. Ofthe instructions that accessedanother page,80percent accesseda page alreadyinmemory. Whena newpagewasrequired,thereplaced page wasmodified50 percentofthe time. Calculatetheeffectiveinstructiontimeonthis system,assumingthatthe systemisrunning oneprocessonlyandthattheprocessorisidleduring drum transfers. Answer: effectiveaccess time = 0.99 (1 sec+0.008 (2 sec) +0.002 (10,000 sec+1,000 sec) +0.001 (10,000 sec+1,000 sec) = (0.99+0.016+22.0+11.0) sec = 34.0 sec 9.7 Consider thetwo-dimensional array A: int A[][] = new int[100][100]; where A[0][0] isat location200,inapaged memory systemwith pages of size 200. A small process is in page 0 (locations 0 to 199) for manipulating thematrix;thus, everyinstruction fetch willbefrom page 0. Forthreepage frames,howmanypage faultsaregeneratedbythefollowing array-initializationloops, using LRUreplacement, andassuming page frame1hastheprocessinit,andtheothertwoareinitiallyempty? a.

for (int j = 0; j < 100; j++) for (int i = 0; i < 100; i++) A[i][j] = 0; b. for (int i = 0; i < 100; i++) for (int j = 0; j < 100; j++) A[i][j] = 0; Answer: a. 50 b. 5,000 9.8 Consider thefollowing pagereferencestring: 1, 2, 3, 4, 2, 1, 5, 6, 2, 1, 2, 3, 7, 6, 3, 2, 1, 2, 3, 6.

32 Chapter 9 Virtual Memory Howmanypagefaultswould occurfor thefollowingreplacementalgorithms, assuming one, two, three, four, five, six, or seven frames? Remember allframesare initially empty, so your first unique pageswill all costonefaulteach. LRU replacement FIFO replacement Optimal replacement Answer: Number of frames LRU FIFO Optimal 1 20 20 20 2 18 18 15 3 15 16 11 4 10 14 8 5 810 7 6 710 7 7 777 9.9 Suppose that youwanttouseapagingalgorithm thatrequiresareference bit(such as second-chancereplacement or working-setmodel),but thehardwaredoesnotprovideone.Sketchhow youcould simulatea referencebit evenif onewerenotprovidedbythehardware, or explain whyitisnot possibletodoso.Ifitis possible, calculatewhatthe cost wouldbe. Answer: You can use the valid/invalid bit supported in hardware to simulatethereferencebit. Initiallysetthebittoinvalid.Onfirstreference atrap to the operating system is generated. The operating system will seta softwarebitto1andresetthevalid/invalidbittovalid. 9.10 Youhavedevisedanewpage-replacementalgorithmthat youthinkmay beoptimal.In somecontortedtestcases,Belady sanomalyoccurs.Isthe newalgorithm optimal? Explainyouranswer. Answer: No. An optimal algorithm will not suffer from Belady s anomaly because by definition an optimal algorithm replaces the page that will notbeusedfor thelongest time.Belady sanomaly occurs whenapage-replacement algorithm evictsa pagethatwillbeneeded intheimmediatefuture.An optimalalgorithm wouldnot have selected such apage. 9.11 Segmentation is similartopagingbut uses variable-sized pages. Define two segment-replacement algorithms based on FIFO and LRU pagereplacement schemes.Rememberthat since segmentsarenotthesame size,the segmentthatischosentobereplacedmay notbebig enough to leaveenoughconsecutivelocationsfortheneeded segment.Consider strategies for systems where segments cannot be relocated, and those for systems where they can.

Answer:

Exercises 33 a. FIFO.Findthe first segmentlarge enoughto accommodate theincoming segment.Ifrelocationis notpossibleand no onesegment is large enough, select a combination of segments whose memories are contiguous, which are closest to the first of the list and which can accommodate the new segment. If relocation is possible,rearrangethe memorysothatthefirst N segments large enoughforthe incoming segmentarecontiguousin memory.Add anyleftover spacetothefree-space listinbothcases. b. LRU. Select the segment that has not been used for the longest periodoftimeandthatislarge enough,addinganyleftoverspace to the free space list. If no one segment is large enough, select a combination of the oldest segments that are contiguous in memory(ifrelocationisnot available) andthatare largeenough. If relocation is available, rearrange the oldest N segments to be contiguousin memory andreplace thosewiththe newsegment. 9.12 Considerademand-pagedcomputer system wherethedegreeof multiprogrammingis currentlyfixedatfour. The system wasrecentlymeasured todetermine utilization of CPU andthe paging disk. Theresults areoneof thefollowing alternatives.Foreach case,whatishappening? Canthedegree of multiprogramming be increasedtoincreasethe CPU utilization?Is thepaginghelping? a. CPU utilization13percent;diskutilization97percent b. CPU utilization87percent;diskutilization3percent c. CPU utilization13percent;diskutilization3percent Answer: a. Thrashingisoccurring. b. CPU utilizationissufficiently high to leavethingsalone,and increase degree of multiprogramming. c. Increase thedegreeof multiprogramming. 9.13 We have an operating system for a machine that uses base and limit registers, but we have modified the machine to provide a page table. Canthe page tablesbe setuptosimulatebaseand limitregisters? How cantheybe, orwhy cantheynotbe? Answer: Thepagetablecanbesetupto simulatebaseandlimitregisters provided that the memory is allocated in fixed-size segments. In this way, thebaseof a segmentcanbe enteredintothe page tableand the valid/invalid bitusedtoindicatethatportionof thesegment asresident inthememory.Therewillbe someproblemwithinternalfragmentation.

File-System Interface 10CHAPTER Exercises 10.1 Some systemsautomatically deletealluserfileswhena userlogsoffor ajob terminates,unlessthe user explicitlyrequeststhattheybe kept; other systems keep all files unless the user explicitly deletes them. Discusstherelative meritsof each approach. Answer: Deleting allfilesnot specifically savedby theuserhas the advantage of minimizing the file space needed for each user by not savingunwantedor unnecessaryfiles.Savingallfilesunlessspecifically deletedismoresecurefor theuserinthatitisnot possibletolosefiles inadvertentlyby forgetting to save them. 10.2 Whydosome systemskeeptrackofthetypeofafile,while othersleave ittotheuserorsimplydonot implementmultiplefile types? Which system is better? Answer: Some systemsallowdifferent fileoperationsbased on the typeofthefile(forinstance,an asciifile canbereadasastream whilea database filecanbereadviaanindextoablock). Other systemsleave such interpretationofafile sdatatotheprocessandprovidenohelpin accessing thedata. Themethodthatis better depends on the needs of theprocessesonthe system,and thedemands theusers placeonthe operating system.Ifasystemruns mostly database applications,itmay be more efficient for the operating system to implement a databasetype file and provide operations, rather than making each program implementthe same thing(possiblyindifferent ways). Forgeneralpurpose systemsit maybe bettertoonlyimplement basicfile typesto keep the operating system size smaller and allow maximum freedom to theprocessesonthe system.

Chapter 10 File-System Interface 10.3 Similarly, some systemssupport many typesof structuresforafile s data, while others simply support a stream of bytes. What are the advantages anddisadvantages? Answer: An advantage of having the system support different file structuresis that thesupport comes fromthe system;individual applicationsarenotr equiredtoprovidethe support.Inaddition,if the systemprovidesthesupportfordifferent filestructures,it canimplement the support presumably more efficiently than an application. Thedisadvantageofhavingthe systemprovidesupportfordefinedfile typesisthatitincreases thesizeofthe system.Inaddition,applications thatmayrequiredifferentfile typesotherthanwhatisprovidedbythe system may not be able to run on such systems. An alternativestrategyisfor theoperating systemtodefine no support forfile structuresandinsteadtreatallfilesasaseriesofbytes.Thisis theapproach takenby UNIX systems.Theadvantageof this approach isthatit simplifiestheoperatingsystemsupportforfilesystems,asthe system no longer hastoprovide thestructure fordifferent filetypes. Furthermore,it allows applicationsto define filestructures, therebyalleviatingth e situationwherea systemmaynotprovidea filedefinition required for a specific application. 10.4 Couldyou simulateamultileveldirectorystructurewithasingle-level directorystructurein whicharbitrarilylong namescanbe used?Ifyour answerisyes,explainhowyoucandoso,and contrastthisschemewith the multilevel directory scheme. If your answer is no, explain what prevents your simulation s success. How would your answer change if file names were limited to seven characters? Answer: If arbitrarily long names can be used then it is possible to simulateamultileveldirectorystructure.Thiscanbedone,for example, byusingthe character . to indicatetheendofasubdirectory.Thus,for example, the name jim.java.F1 specifies that F1 is a file in subdirectory java whichinturnisintherootdirectory jim. Iffilenameswere limitedto sevencharacters,thentheabovescheme couldnotbe utilizedandthus,ingeneral,theansweris no.The nextbest approach in this situation would be to use a specific file as a symbol table(directory) to map arbitrarily long names (such asjim.java.F1) into shorterarbitrary names(such as XX00743), which are then used for actual file access. 10.5 Explainthe purposeofthe open() and close() operations. Answer: The open()

operationinforms thesystem that thenamed fileis abouttobecome active. The close() operationinforms the system that thenamed fileis no longerin active usebythe userwhoissuedtheclose operation. 10.6 Give an exampleof anapplicationinwhich datainafile shouldbe accessedinthe following order: a. Sequentially

Exercises b. Randomly Answer: a. Printthe content ofthe file. b. Print the content of record i. This record can be found using hashingorindex techniques. 10.7 In some systems,asubdirectorycanbereadandwrittenby anauthorizeduser, justasordinary files canbe. a. Describe theprotectionproblemsthatcould arise. b. Suggestaschemefor dealingwitheachoftheprotectionproblems you named in part a. Answer: a. Onepieceof informationkeptinadirectoryentryisfilelocation. Ifausercould modify this location,thenhecould access other filesdefeatingthe access-protection scheme. b. Do not allow the user to directly write onto the subdirectory. Rather,provide system operationstodo so. 10.8 Considera system that supports 5000 users. Suppose that youwantto allow 4990 of these users to be able to access one file. a. How would you specify this protection scheme in UNIX? b. Couldyou suggest anotherprotectionschemethatcanbe used moreeffectivelyforthis purposethanthe schemeprovidedby UNIX? Answer: a. There are two methods for achievingthis: 1. Create an access control list with the names of all 4990 users. 2. Putthese 4990 usersinonegroupand setthegroupaccess accordingly. This scheme cannotalwaysbeimplemented sinceusergroupsarerestrictedby the system. b. Theuniversalaccessto filesappliestoall usersunlesstheir name appearsinthe access-control listwithdifferent access permission. With this scheme you simply put the names of the remainingten usersinthe access control listbut with no access privilegesallowed. 10.9

Researchershavesuggestedthat,insteadofhavingan accesslistassociatedwitheach file(specifying whichusers canaccessthefile,andhow), we should have a user control list associatedwith each user (specifying whichfilesa user canaccess,andhow). Discusstherelativemeritsof thesetwo schemes. Answer:

Chapter 10 File-System Interface File control list.Since theaccess controlinformationis concentrated in onesingleplace,itiseasiertochangeaccess controlinformation andthis requiresless space. User control list.Thisrequireslessoverheadwhen opening afile.

File-System Implementation 11CHAPTER Exercises 11.1 Consider a file currently consisting of 100 blocks. Assume that the filecontrol block(andthe indexblock,inthe caseof indexedallocation) isalreadyin memory.Calculate howmanydisk I/O operations arerequiredforcontiguous, linked, andindexed (single-level)allocation strategies,if, forone block, thefollowing conditions hold.Inthe contiguous-allocation case,assumethatthereisnoroomtogrowinthe beginning,but thereisroomtogrowin theend.Assumethatthe block informationtobe addedis storedin memory. a. Theblockisaddedatthebeginning. b. Theblockis addedinthe middle. c. Theblockis addedatthe end. d. Theblockisremovedfromthebeginning. e. Theblockisremovedfromthemiddle. f. Theblockisremovedfrom theend. Answer: Contiguous Linked Indexed a. 201 11 b. 101 521 c.1 31 d. 198 10 e. 98 520 f. 0 1000

Chapter 11 File-System Implementation 11.2 What problems could occur if a system allowed a file system to be mountedsimultaneouslyat morethanone location? Answer: Therewouldbe multiple pathstothe same file, whichcould confuseusers or encourage mistakes(deleting afile with onepath deletesthe fileinall theother paths). 11.3 Whymustthebitmapforfile allocationbekepton mass storage, rather than in main memory? Answer: In case of system crash(memory failure)the free-space list wouldnotbe lostasit wouldbeifthebitmaphadbeen storedin main memory. 11.4 Consider a system that supports the strategies of contiguous, linked, andindexedallocation.Whatcriteriashouldbeusedindecidingwhich strategy is best utilized for a particular file? Answer: Contiguous iffileis usually accessed sequentially,iffileis relatively small. Linked iffile is large and usually accessed sequentially. Indexed iffile is large and usually accessed randomly. 11.5 Oneproblemwith contiguous allocationisthattheusermustpreallocate enough spacefor each file.If thefilegrowstobelargerthanthe spaceallocatedforit,special actions mustbetaken.One solutionto this problem is to define a file structure consisting of an initial contiguousar ea( of aspecifiedsize).Ifthis areaisfilled, theoperating system automatically definesanoverflowareathatis linkedtothe initialcontiguousar ea. Iftheoverflowareaisfilled,anotheroverflowarea is allocated. Comparethisimplementationof a filewiththe standard contiguous and linkedimplementations. Answer: This methodrequires more overhead thenthestandardcontiguousallocation. It requireslessoverhead than thestandardlinked allocation. 11.6 Howdocacheshelpimprove performance?Whydo systemsnot use more or larger caches if they are so useful? Answer: Cachesallowcomponentsofdifferingspeedstocommunicate moreefficientlyby storingdatafromthe slower device,temporarily, inafasterdevice (thecache).Cachesare,almostbydefinition,more expensivethanthedevicetheyarecachingfor,so increasingthenumber or sizeof caches wouldincrease system cost. 11.7 Whyisitadvantageousfortheuserforan operating systemto dynamically allocate itsinternaltables? What arethe penaltiestothe operating

system fordoing so? Answer: Dynamictablesallowmoreflexibilityinsystem usegrowth tables arenever exceeded,avoidingartificial use limits.Unfortunately, kernel structures and code are more complicated, so there is more potentialforbugs.Theuseofoneresourcecantakeawaymore system resources(bygrowingtoaccommodate therequests) than with static tables.

Exercises 41 11.8 Explainhowthe VFSlayerallowsan operatingsystemeasilyto support multiple types offile systems. Answer: VFS introducesalayerof indirectioninthe filesystem implementation. In many ways,itis similartoobject-orientedprogramming techniques.Systemcallscanbemadegenerically (independent of file systemtype).Eachfile systemtypeprovidesitsfunctioncallsanddata structures to the VFS layer.Asystem call is translated into theproper specificfunctions forthe targetfile systematthe VFS layer. Thecalling programhas no file-system-specific code,and theupperlevelsof the system call structures likewiseare file system-independent.The translationatthe VFS layerturnsthesegenericcallsintofile-system-specific operations.

Mass Storage Structure 12CHAPTER Exercises 12.1 Theaccelerating seek describedinExercise 12.3istypicalof hard-disk drives.Bycontrast, floppydisks (and many harddisks manufactured before the mid-1980s) typically seek at a fixed rate. Suppose that the diskin Exercise 12.3hasaconstant-rate seek rather thanaconstantacceleration seek,sothe seek timeisoftheform t = x + yL,where t is thetimeinmilliseconds and L is theseek distance.Suppose that the timeto seektoan adjacent cylinderis1millisecond,as before,andis 0.5 milliseconds for each additional cylinder. a. Write an equation for this seek time as a function of the seek distance. b. Usingthe seek-timefunctionfromparta,calculate thetotal seek time foreachof the schedulesinExercise 12.2.Is your answer thesameasitwas forExercise 12.3(c)? c. Whatisthepercentagespeedupofthefastestschedule over FCFS in this case? Answer: a. t = 0.95 + 0.05L b. FCFS 362.60; SSTF 95.80; SCAN 497.95; LOOK 174.50; C-SCAN 500.15; (and C-LOOK 176.70). SSTF is still the winner, and LOOK is the runner-up. c. (362.60 95.80)/362.60 = 0.74Thepercentagespeedupof SSTF over FCFSis74%,withrespecttotheseek time.Ifweincludethe overheadofrotational latencyand data transfer,the percentage speedup will be less.

Chapter 12 Mass-Storage Structure 12.2 Is disk scheduling, otherthan FCFS scheduling, usefulinasingle-user environment? Explainyouranswer. Answer: Inasingle-userenvironment,the I/O queueusuallyisempty. Requestsgenerally arrivefromasingleprocess forone blockorfora sequenceofconsecutiveblocks.Inthesecases, FCFSis an economical method of disk scheduling. But LOOK is nearly as easy to program andwill give much betterperformance when multipleprocesses are performing concurrent I/O,suchaswhenaWebbrowserretrieves data in thebackground while theoperating systemis paging andanother applicationisactiveinthe foreground. 12.3 Explainwhy SSTF schedulingtendstofavormiddlecylinders overthe innermost and outermost cylinders. Answer: The center of the disk is the location having the smallest averagedistancetoallothertracks.Thusthediskheadtendsto move awayfromtheedgesofthedisk.Hereis anotherwayto thinkofit.The currentlocationof the head dividesthe cylinders into twogroups.If theheadisnotinthecenterofthe diskand anewrequest arrives,the newrequestis more likelytobeinthegroupthatincludesthe center of thedisk; thus,the headis more likelytomoveinthatdirection. 12.4 Whyisrotationallatency usually notconsideredindiskscheduling? How would you modify SSTF, SCAN,and C-SCAN to include latency optimization? Answer: Most disksdo notexporttheirrotational position information to thehost. Evenif they did, thetimefor this informationtoreach the schedulerwouldbe subjecttoimprecisionandthe time consumedby thescheduleris variable,sotherotational position informationwould become incorrect. Further, thediskrequestsare usually givenin terms of logicalblock numbers,andthe mapping between logicalblocksand physicallocationsis verycomplex. 12.5 Howwoulduseofa RAMdiskaffectyour selectionofadisk-scheduling algorithm? What factors would you need to consider? Do the same considerationsapplytohard-disk scheduling,giventhatthefilesystem storesrecently used blocksinabuffercachein main memory? Answer: Disk scheduling attempts to reduce the overhead time of disk head positioning. Since a RAM disk has uniform access times, schedulingislargely unnecessary. The comparison between RAM disk and the main memory disk-cache has no implications for hard-disk schedulingbecause we schedule only thebuffercache misses, notthe requests that find theirdatainmainmemory. 12.6 Whyisitimportantto balancefile system I/O amongthedisksand controllers on a system in a multitasking environment? Answer: Asystem canperformonlyatthespeedofitsslowest bottleneck. Disks or diskcontrollers arefrequentlythebottleneckinmodern

systemsastheir individual performancecannotkeepup with thatof the CPU and system bus.Bybalancing I/O amongdisks andcontrollers, neither an individual disk nor a controller is overwhelmed, so that bottleneckis avoided.

Exercises 45 12.7 Whatarethe tradeoffsinvolvedinrereadingcodepagesfromthefile system versususing swap spacetostore them? Answer: Ifcodepagesarestoredinswap space,theycanbetransferred more quicklytomainmemory(becauseswapspace allocationis tuned forfasterperformance than generalfile system allocation). Usingswap spacecanrequirestartup timeifthepagesarecopiedthereatprocess invocation rather than just beingpaged outtoswapspace on demand. Also,moreswapspace mustbe allocatedifitisusedfor both codeand data pages. 12.8 Is thereany waytoimplement trulystablestorage?Explain your answer. Answer: Trulystablestoragewouldnever lose data.The fundamental techniquefor stable storageistomaintainmultiplecopiesofthe data, so thatif onecopyisdestroyed,someother copyis still availablefor use. Butfor anyscheme, we canimaginealarge enough disaster that all copies aredestroyed. 12.9 Theterm fast wide SCSI-II denotesa SCSIbusthatoperatesatadata rateof20 megabytesper second whenit movesapacketofbytesbetweenthehostandadevice. Supposethatafastwide SCSI-II disk drive spinsat7200 RPM,hasasectorsizeof512 bytes, andholds 160 sectors pertrack. a. Estimate thesustained transfer rateofthis driveinmegabytes per second. b. Suppose that thedrive has 7000 cylinders,20tracksper cylinder, aheadswitchtime(from oneplattertoanother)of0.5 millisecond, andanadjacentcylinderseek timeof2 milliseconds.Use this additional informationtogiveanaccurate estimateof the sustainedtransfer ratefor ahugetransfer. c. Supposethattheaverageseektimeforthedriveis8milliseconds. Estimate the I/Osper second andtheeffectivetransferratefor arandom-access workload thatreadsindividualsectors thatare scattered acrossthe disk. d. Calculatethe random-access I/Osper second andtransferrate forI/O sizesof4kilobytes,8kilobytes, and64kilobytes. e. Ifmultiplerequestsareinthequeue,aschedulingalgorithmsuch as SCANshouldbeabletoreducetheaverageseek distance.Suppose thatarandom-access workloadisreading8-kilobyte pages, the average queue length is 10, and the scheduling algorithm reducesthe averageseek timeto3 milliseconds.Now calculate theI/Osper second andtheeffectivetransferrateofthedrive. Answer: a. Thediskspins 120 timesper second,and each spin transfersa

trackof80 KB.Thus,thesustained transfer rate canbeapproximated as 9600 KB/s.

Chapter 12 Mass-Storage Structure b. Supposethat100 cylindersisahugetransfer.Thetransferrateis totalbytes dividedbytotal time.Bytes:100cyl*20 trk/cyl*80 KB/trk,i.e., 160,000 KB.Time:rotation time+track switch time+ cylinderswitchtime. Rotation timeis 2000 trks/120 trks per sec, i.e., 16.667s.Trackswitchtimeis19switch percyl*100cyl*0.5 ms,i.e.,950ms.Cylinderswitchtimeis99 *2 ms,i.e.,198 ms. Thus,the totaltimeis 16.667+0.950+0.198, i.e., 17.815 s.(We areignoringany initialseekandrotationallatency,whichmight addabout12mstotheschedule, i.e. 0.1%.) Thusthetransferrate is 8981.2 KB/s.Theoverheadof trackand cylinderswitchingis about6.5%. c. Thetimeper transferis8mstoseek+4.167ms averagerotational latency+ 0.052 ms (calculatedfrom1/(120 trk per second* 160 sector per trk)) to rotate one sector past the disk head during reading.We calculatethe transfersper second as 1/(0.012219), i.e., 81.8. Since each transfer is 0.5 KB, the transfer rate is 40.9 KB/s. d. Weignoretrackandcylindercrossingsfor simplicity.Forreadsof size4 KB,8KB,and64 KB,the corresponding I/Ospersecondare calculatedfromtheseek,rotationallatency,androtational transfertimeasinthepreviou sitem, giving(respectively) 1/(0.0126), 1/(0.013),and 1/(0.019).Thusweget 79.4, 76.9, and 52.6transfers persecond,respectively.Transfer ratesareobtainedfrom4, 8, and64times these I/O rates, giving 318 KB/s, 615 KB/s,and 3366 KB/s, respectively. e. From 1/(3+4.167+0.83) we obtain 125 I/Ospersecond.From8 KB per I/O we obtain 1000 KB/s. 12.10 More than onediskdrive canbeattachedtoa SCSI bus.In particular, afastwide SCSI-II bus(seeExercise 12.9) canbeconnected to at most 15 disk drives.Recallthatthisbushasabandwidthof20 megabytes persecond.Atanytime,only onepacketcanbe transferredonthebus between some disk sinternalcache andthehost.However,a diskcan be moving itsdiskarm while some otherdiskistransferringapacket onthebus.Also,adiskcanbe transferring data betweenitsmagnetic platters andits internal cachewhile some otherdiskistransferringa packet on thebus.Considering thetransferrates that youcalculated forthe variousworkloadsin Exercise 12.9, discusshow many disks can be usedeffectivelybyone fastwide SCSI-II bus. Answer: For8 KBrandomI/Osonalightlyloadeddisk,wheretherandom access timeis calculatedtobe about13 ms(seeExercise 12.9),theeffective transfer rateis about615 MB/s.Inthiscase,15 disks wouldhavean aggregatetransferrateoflessthan10 MB/s,which shouldnotsaturate thebus.For64 KB randomreadstoa lightly loaded disk,thetransfer rateis about3.4 MB/s,sofiveorfewerdiskdriveswouldsaturatethe

bus. For 8 KBreadswitha largeenoughqueue toreduce theaverage seekto3 ms, thetransferrateisabout1 MB/s,sothe busbandwidth maybeadequatetoaccommodate15 disks.

Exercises 47 12.11 Remapping of bad blocks by sector sparing or sector slipping could influence performance. Supposethatthedrivein Exercise 12.9hasa totalof100badsectorsat random locationsandthateachbadsectoris mapped toa sparethatislocated onadifferent track, butwithinthe same cylinder. Estimate thenumberof I/Osper second andtheeffective transfer rateforarandom-access workload consistingof 8-kilobyte reads, withaqueue lengthof1(thatis,the choiceof schedulingalgorithmisnotafactor) . Whatistheeffectofabad sectoron performance? Answer: Since the disk holds 22,400,000 sectors, the probability of requesting oneofthe 100remappedsectorsis verysmall.An example ofaworst-case eventisthat weattempttoread,say,an8 KB page,but onesectorfromthe middleisdefective andhasbeenremappedtothe worstpossiblelocationonanother trackinthatcylinder.In this case, thetimefortheretrievalcouldbe8mstoseek,plustwo trackswitches and two full rotational latencies. It is likely that a modern controller wouldreadalltherequestedgood sectorsfromtheoriginaltrackbefore switchingtothe sparetracktoretrievetheremappedsectorand thus wouldincur only onetrack switch androtationallatency.Sothe time would be 8 ms seek + 4.17 ms average rotational latency + 0.05 ms trackswitch+ 8.3msrotationallatency+0.83msreadtime(8 KBis16 sectors,1/10ofatrackrotation).Thus,thetimeto servicethisrequest wouldbe 21.8ms, giving an I/O rateof 45.9requestsper second and an effective bandwidth of 367 KB/s. For a severely time-constrained applicationthismight matter, butthe overallimpactinthe weighted averageof100remappedsectors and 22.4milliongood sectorsisnil. 12.12 Inadiskjukebox,whatwouldbe theeffectofhavingmoreopenfiles than thenumberofdrivesin thejukebox? Answer: Twobad outcomes couldresult. Onepossibilityisstarvation oftheapplicationsthatissueblockingI/Ostotapesthatarenot mounted indrives.Another possibilityisthrashing,asthejukeboxiscommanded to switchtapes after every I/O operation. 12.13 Ifmagneticharddisks eventuallyhavethesamecostpergigabyteasdo tapes,will tapesbecomeobsolete, orwillthey stillbeneeded?Explain your answer. Answer: Tapes are easily removable, so they are useful for off-site backupsand forbulktransferofdata(by sendingcartridges).Asa rule, a magnetic harddisk is not a removable medium. 12.14 Itis sometimessaidthattapeisa sequential-access medium,whereas magnetic disk is a random-access medium. In fact, the suitability of astorage device forrandomaccess dependsonthe transfer size.The term streaming transfer rate denotes the data rate for a transfer that is underway, excluding the effect of access latency. By contrast, the effective transfer

rate istheratiooftotalbytespertotal seconds, including overhead time such as the access latency. Supposethat,inacomputer,the level-2cachehas an access latency of8 nanoseconds anda streamingtransferrateof800 megabytesper second,the main memory hasanaccess latencyof60nanoseconds and astreaming transfer rateof80 megabytesper second,the magnetic disk

Chapter 12 Mass-Storage Structure hasanaccess latencyof15millisecondandastreaming transfer rateof 5megabytes persecond, anda tape drivehas an access latencyof60 secondsand astreamingtransfer rateof2 megabytesperseconds. a. Randomaccesscausestheeffective transfer rateofadeviceto decrease,becausenodataaretransferred duringtheaccess time. For the disk described, what is the effective transfer rate if an averageaccessis followedby astreamingtransferof512 bytes, 8kilobytes,1megabyte, and16 megabytes? b. The utilization of a device is the the ratio of effective transfer rate to streaming transfer rate. Calculate the utilization of the disk drivefor random access that performs transfersineachof thefoursizes givenin part a. c. Suppose thatautilizationof25percent(orhigher)is considered acceptable.Usingtheperformancefigures given,computethe smallest transfer size fordiskthatgives acceptable utilization. d. Completethefollowing sentence:Adiskisarandom-access device for transfers larger than bytes, and is a sequentialaccessdevice forsmallertransfers. e. Compute the minimum transfer sizes that give acceptable utilizationfor cache, memory,and tape. f. Whenisatapearandom-access device,andwhenisitasequentialaccess device? Answer: a. For 512 bytes, the effective transfer rate is calculated as follows. ETR =transfersize/transfer time. IfXistransfersize,then transfer timeis((X/STR)+latency). Transfer time is 15ms +(512B/5MB per second) = 15.0097ms. Effectivetransferrateistherefore 512B/15.0097ms= 33.12 KB/sec. ETR for 8KB = .47MB/sec. ETR for 1MB = 4.65MB/sec. ETR for 16MB = 4.98MB/sec. b. Utilizationof the device for 512B = 33.12 KB/sec/5MB/sec = .0064 = .64 For 8KB =9.4%. For 1MB = 93%. For 16MB = 99.6%. c. Calculate.25 = ETR/STR,solvingfortransfersizeX. STR = 5MB,so 1.25MB/S = ETR. 1.25MB/S* ((X/5)+.015) = X. .25X+ .01875 =X. X= .025MB.

d. Adiskisarandom-access devicefortransferslargerthanKbytes (whereK > disk blocksize),andisasequential-access devicefor smallertransfers.

Exercises 49 e. Calculate minimum transfer size for acceptable utilization of cache memory: STR = 800MB, ETR = 200, latency =8*10-9. 200 (XMB/800 +8 X10-9)= XMB. .25XMB+1600*10-9 = XMB. X= 2.24 bytes. Calculatefor memory: STR = 80MB, ETR =20,L =60*10-9. 20 (XMB/80 +60*10-9)= XMB. .25XMB+1200*10-9 = XMB. X= 1.68 bytes. Calculatefor tape: STR = 2MB, ETR = .5,L = 60s. .5 (XMB/2 +60) =XMB. .25XMB +30= XMB. X= 40MB. f. It depends upon how it is being used. Assume we are using thetapetorestoreabackup.In this instance,the tape acts asa sequential-access devicewhereweare sequentiallyreadingthe contentsofthetape.As anotherexample,assumeweareusing thetapetoaccessavarietyofrecordsstored onthe tape.Inthis instance, access to the tape is arbitrary and hence considered random. 12.15 Suppose that we agree that 1 kilobyte is 1,024 bytes, 1 megabyte is 1,0242 bytes,and1gigabyteis 1,0243 bytes. Thisprogression continues throughterabytes,petabytes,andexabytes (1,0246).Therearecurrently severalnewproposedscientificprojectsthatplantorecordand storea fewexabytesofdataduringthe nextdecade.Toanswerthe following questions,youwillneedto makeafewreasonable assumptions; state theassumptionsthatyou make. a. Howmanydiskdriveswouldberequiredtohold4exabytesof data? b. Howmanymagnetictapes wouldberequiredtohold4exabytes of data? c. Howmanyoptical tapeswouldberequiredto hold4 exabytes of data (see Exercise 12.21)? d. Howmanyholographic storagecartridgeswouldberequiredto hold4 exabytesofdata(seeExercise 12.20)? e. How many cubic feet of storage space would each option require? Answer: a. Assume that a disk drive holds 10 GB. Then 100 disks hold 1 TB, 100,000 disks hold 1 PB, and 100,000,000 disks hold 1 EB.To store 4 EBwouldrequire about 400 milliondisks.If a magnetic tape holds40 GB,only100 milliontapes wouldberequired.If

Chapter 12 Mass-Storage Structure an opticaltapeholds50 timesmoredatathana magnetic tape,2 millionoptical tapeswould suffice.Ifaholographiccartridge can store 180 GB, about 22.2 million cartridges would be required. b. A3.5"diskdriveisabout1"high,4"wide,and6" deep.Infeet, thisis1/12by1/3by1/2,or1/72cubic feet.Packeddensely, the 400 milliondisks wouldoccupy 5.6millioncubic feet.If we allowa factorof twofor airspace andspace forpower supplies, therequiredcapacityisabout11 millioncubic feet. c. A1/2"tapecartridgeis about1"highand 4.5" square.The volume is about 1/85 cubic feet. For 100 million magnetic tapes packed densely, thevolumeisabout 1.2millioncubic feet.For2 millionoptical tapes, thevolumeis 23,400 cubicfeet. d. A CD-ROM is 4.75" in diameter and about 1/16" thick. If we assume thataholostore diskis storedina library slot thatis5" square and1/8"wide, we calculatethe volumeof 22.2million diskstobe about 40,000 cubicfeet.

I/O Systems 13CHAPTER Exercises 13.1 Statethree advantagesof placingfunctionalityina device controller, rather thanin thekernel. Statethree disadvantages. Answer: Threeadvantages: Bugs areless likelytocause an operating system crash Performance can be improved by utilizing dedicated hardware and hard-codedalgorithms Thekernelissimplifiedbymovingalgorithms outofit Threedisadvantages:Bugsarehardertofix anewfirmware version or newhardwareis needed Improvingalgorithms likewiserequireahardwareupdateratherthan justakernel ordevice-driver update Embeddedalgorithmscould conflictwithapplication s useofthe device, causingdecreasedperformance. 13.2 Theexampleof handshakinginSection13.2used2bits:a busybit anda command-ready bit.Isit possibletoimplement this handshakingwith only1bit?Ifitis, describe theprotocol.Ifitis not, explainwhy1bitis insufficient. Answer: It is possible, using the following algorithm. Let s assume we simply usethe busy-bit(or thecommand-ready bit; this answer is thesameregardless).Whenthe bitisoff,the controllerisidle. The host writestodata-outandsetsthebittosignalthatanoperationis ready(theequivalent of setting thecommand-ready bit).Whenthe controlleris finished,it clearsthe busy bit. Thehosttheninitiates the next operation. This solutionrequires that boththehostand thecontrollerhaveread andwrite access to thesamebit,which cancomplicatecircuitry and increase thecostofthe controller.

Chapter 13 I/O Systems 13.3 Whymighta system useinterrupt-driven I/O to manageasingleserial port,but polling I/Oto manageafront-endprocessor,suchasaterminal concentrator? Answer: Polling can be more efficient than interrupt-driven I/O.This isthecasewhentheI/O isfrequentandofshort duration.Eventhough asingleserialportwill perform I/O relativelyinfrequentlyandshould thususeinterrupts,acollectionofserialportssuchasthoseinaterminal concentrator canproducealotof short I/Ooperations,and interrupting foreachone couldcreatea heavyloadonthe system.A well-timed pollingloop couldalleviatethatloadwithout wastingmanyresources throughlooping with no I/O needed. 13.4 Pollingforan I/O completion canwastealarge numberof CPUcycles iftheprocessoriteratesa busy-waitingloop many timesbeforethe I/O completes.Butifthe I/Odeviceisreadyfor service,pollingcanbemuch moreefficient thanis catchinganddispatchingan interrupt.Describe ahybridstrategythatcombinespolling, sleeping, andinterruptsfor I/O device service. Foreachofthese threestrategies(purepolling, pure interrupts,hybrid),describea computingenvironmentin whichthat strategy is more efficient than is either of the others. Answer: Ahybridapproach couldswitchbetween pollingand interruptsdependingonthelengthofth eI/ Ooperationwait.For example, we couldpollandloopNtimes,andifthedeviceis stillbusyatN+1, we couldset an interruptand sleep.Thisapproach wouldavoid long busy-waitingcycles. This method wouldbebestfor verylongor very shortbusytimes.It wouldbe inefficientit the I/O completesatN+T (whereTisa smallnumberof cycles) duetothe overheadof polling plus settingup andcatchinginterrupts. Pure pollingisbestwith veryshort wait times. Interrupts arebestwith knownlong waittimes. 13.5 Howdoes DMA increase system concurrency? Howdoesit complicate hardwaredesign? Answer: DMA increases system concurrency by allowing the CPU to performtasks while the DMA system transfersdatavia the system andmemorybuses. Hardwaredesigniscomplicated becausethe DMA controller must be integrated into the system, and the system must allowthe DMA controllertobea busmaster. Cyclestealingmay also be necessary to allow the CPU and DMA controller to share use of the memory bus. 13.6 Whyisitimportant to scaleup system busand device speedsasthe CPU speed increases? Answer: Considera system whichperforms 50% I/O and 50% computes. Doublingthe CPU performanceonthis system wouldincrease total system performanceby only 50%.Doublingbothsystem aspects wouldincreaseperformanceby 100%.Generally,itisimportanttoremove

the current system bottleneck, and to increase overall system performance, rather than blindlyincreasingtheperformance ofindividual system components. 13.7 Distinguishbetweena STREAMS driverand aSTREAMS module.

Exercises Answer: TheSTREAMS driver controlsaphysicaldevice that couldbe involved in a STREAMS operation. The STREAMS module modifies the flow ofdatabetween thehead(the userinterface)andthedriver.

Protection 14CHAPTER Exercises 14.1 What arethe main differencesbetween capability lists andaccess lists? Answer: Anaccesslistisalistforeachobject consistingofthedomains withanonemptysetof access rights forthatobject.A capability listis a listof objects andthe operations allowedonthose objectsfor each domain. 14.2 A Burroughs B7000/B6000 MCP file can be tagged as sensitive data. When such a file is deleted, its storage area is overwritten by some random bits.For what purposewould suchaschemebeuseful? Answer: This wouldbeusefulasanextra security measuresothatthe oldcontentof memory cannotbeaccessed,either intentionally orby accident,by anotherprogram. Thisis especially usefulforany highly classifiedinformation. 14.3 Inaring-protection system,level0has thegreatestaccess to objects, andlevel n (greater than zero)has feweraccess rights.The access rights ofaprogramataparticularlevelintheringstructureareconsideredas asetof capabilities. Whatis therelationshipbetween thecapabilities of adomain atlevel j and a domain at level i to an object (for j > i)? Answer: Dj is a subset of Di . 14.4 TheRC4000 system(andothersystems)have definedatreeofprocesses (calledaprocesstree) suchthatallthedescendantsofaprocessaregiven resources(objects) andaccessrightsby their ancestors only. Thus,a descendant cannever have theabilitytodoanythingthatits ancestors cannotdo.Therootofthetreeisthe operating system, whichhasthe abilitytodoanything. Assumethesetof access rights wasrepresented by an access matrix, A. A(x,y)definesthe access rights of processx to

Chapter 14 Protection object y.If x isadescendantof z,whatistherelationship betweenA(x,y) and A(z,y)for an arbitrary objecty? Answer: A(x,y)is a subset of A(z,y). 14.5 Whatprotectionproblems mayariseifashared stackis used forparameterpassing? Answer: Thecontentsof the stackcouldbe compromisedby other process(es)sharing the stack. 14.6 Consider a computing environment where a unique numberis associated with eachprocessand each objectin the system.Suppose that we allow a processwith number n to access an object with number m only if n > m.Whattypeofprotectionstructuredo we have? Answer: Hierarchical structure. 14.7 Consideracomputing environment whereaprocessis giventheprivilege of accessing an object only n times. Suggestaschemefor implementingthispolicy. Answer: Addaninteger counterwiththe capability. 14.8 Ifallthe access rightstoanobjectaredeleted,theobject cannolonger be accessed.Atthis point,theobject shouldalsobedeleted,andthe spaceitoccupies shouldbereturnedtothe system.Suggestanefficient implementation of this scheme. Answer: Reference counts. 14.9 Whyisitdifficulttoprotecta systemin whichusers areallowedtodo their own I/O? Answer: In earlierchaptersweidentifiedadistinctionbetween kernel and user mode where kernel mode is used for carrying out privileged operations such as I/O.One reason why I/O must be performed in kernel mode is that I/O requires accessing the hardware and proper access to the hardware is necessary for system integrity. If we allow userstoperformtheirown I/O,wecannotguarantee system integrity. 14.10 Capability lists are usually kept within the address space of the user. Howdoesthe system ensure that theusercannotmodifythe contents of the list? Answer: A capability list is considered a protected object and is accessedonlyindirectlybythe user.The operating system ensuresthe

user cannotaccess thecapability listdirectly.

15CHAPTER15CHAPTER Security No Exercises

Distributed System Structures 16CHAPTER Exercises 16.1 MostWANsemployonlya partially connected topology.Whyis this so? Answer: Cost. A fully connected network requires a link between everynodeinthenetwork.Fora WAN,thismaybe toocostlyascommunication links between physically distanthosts maybeexpensive. 16.2 Under what circumstances is a token-passing network more effective than an Ethernet network? Answer: Atokenringis veryeffectiveunderhighsustained load,as no collisions canoccurand each slot maybeusedtocarryamessage, providing high throughput. A token ring is less effective when the loadislight(tokenprocessingtakeslongerthanbus access,soanyone packet cantakelongertoreach itsdestination)orsporadic. 16.3 Whywoulditbeabad ideaforgatewaystopassbroadcast packets betweennetworks?Whatwouldbethe advantagesof doingso? Answer: Allbroadcastswouldbepropagatedtoallnetworks, causing a lot of network traffic. If broadcast traffic were limited to important data (and very little of it), then broadcast propagation would save gateways from having to run special software to watch for this data (such as network routinginformation) and rebroadcastit. 16.4 Discuss the advantages and disadvantages of caching name translationsfor computerslocatedinremote domains. Answer: Thereisa performanceadvantageto cachingnametranslationsfor computerslocatedinremote domains:repeatedresolutionof thesamenamefromdifferent computerslocatedinthelocaldomain couldbeperformed locallywithoutrequiring aremotenamelookup operation.Thedisadvantageisthattherecouldbeinconsistenciesinthe

Chapter 16 Distributed System Structures name translationswhenupdatesaremadeinthemappingof namesto IP addresses.Theseconsistencyproblemscouldbesolvedbyinvalidating translations, which would require state to be managed regarding which computers are caching a certain translation and also would requirea numberof invalidationmessages,orby usingleaseswhereby thecaching entity invalidatesatranslation afteracertainperiodoftime. Thelatterapproachrequiresless stateandno invalidationmessagesbut mightsufferfromtemporary inconsistencies. 16.5 Whatarethe advantagesanddisadvantagesofusingcircuit switching? Forwhatkindsof applicationsis circuitswitchingaviablestrategy? Answer: Circuit switching guarantees that the network resources requiredfora transferarereservedbeforethetransmissiontakesplace. This ensuresthatpackets will notbedroppedand theirdeliverywould satisfy quality of service requirements. The disadvantage of circuit switchingisthatit requiresaround-trip message to set-up thereservations and it also might overprovision resources, thereby resulting in suboptimal use of the resources. Circuit switching is a viable strategy for applications that have constant demands regarding network resources and would require the resources for long periods of time, therebyamortizingthe initialoverheads. 16.6 Whataretwo formidableproblemsthat designersmustsolvetoimplement a network-transparent system? Answer: Onesuchissueismakingall theprocessors andstorage devicesseem transparent acrossthenetwork.Inotherwords,the distributed system should appear as a centralized system to users. The Andrew file system and NFSprovidethisfeature:thedistributedfile system appearstothe userasasinglefile systembutinrealityit may bedistributed acrossa network. Anotherissueconcernsthe mobilityof users.Wewanttoallowusers to connect to the system rather thantoaspecific machine(although inrealitytheymaybe loggingintoaspecific machinesomewherein thedistributed system). 16.7 Processmigrationwithinaheterogeneousnetworkisusually impossible, given thedifferencesin architecturesand operating systems. Describe a method for process migration across different architectures running: a. The same operating system b. Different operating systems Answer: Forthe same operating system,process migrationisrelativelystraightforward, asthestateoftheprocessneedstomigratefrom oneprocessortoanother.Thisinvolves movingtheaddressspace,state ofthe CPUregisters,andopenfilesfromthe source systemtothedestination. However,itisimportantthat identicalcopiesofthe operating system are running on the different systems to ensure compatibility.

If the operating system are the same, but perhaps different versions arerunning on theseparate systems, then migratingprocessesmustbe

Exercises 61 sureto followprogramming guidelinesthatareconsistentbetweenthe differentversionsofthe operatingsystem. Java appletsprovideaniceexampleofprocessmigrationbetween different operating systems.To hide differencesinthe underlying system, the migrated process (i.e., a Java applet) runs on a virtual machine rather thanaspecific operating system. Allthatisrequiredisfor the virtualmachinetoberunningonthe systemtheprocess migratesto. 16.8 To buildarobustdistributed system,you must know what kindsof failures can occur. a. List threepossibletypesof failureinadistributed system. b. Specify which of the entries in your list also are applicable to a centralized system. Answer: Three common failures in a distributed system include: (1)network linkfailure,(2) host failure,(3) storage mediumfailure. Both(2)and(3)are failuresthatcould also occurina centralized system, whereas a network link failure can occur only in a networkeddistributed system. 16.9 Isit always crucialtoknowthatthemessageyouhavesenthasarrived at its destination safely? If your answer is yes, explain why. If your answer is no, give appropriate examples. Answer: No.Manystatus-gatheringprogramsworkfromthe assumptionthatpacketsmaynotbereceived bythedestination system.These programs generally broadcast apacket and assume that at least some other systems on their network will receive the information. For instance, a daemon on each system mightbroadcast the system s load averageand numberof users.Thisinformationmightbe used forprocess migration target selection. Another example is a program that determinesifaremotesiteisbothrunningandaccessibleoverthenetwork. Ifit sendsaquery andgetsnoreplyit knowsthe system cannot currentlybe reached. 16.10 Presentanalgorithm forreconstructinga logicalringafteraprocessin the ringfails. Answer: Typically distributed systemsemploya coordinatorprocess thatperforms functionsneededby otherprocessesinthe system.This wouldinclude enforcingmutualexclusionand in this caseofaring replacing alosttoken. Aschemesimilartothe ring algorithmpresentedin Section 18.6.2can be used.The algorithmisasfollows: The ring algorithm assumesthatthe links areunidirectionaland that

processessendtheir messagestothe neighbor on theirright.The main data structureusedbythe algorithmisthe active list,alistthatcontains the priority numbers of all active processes in the system when the algorithm ends; each process maintains its own active list. a. If process Pi detectsa coordinatorfailure,itcreatesanew active listthatisinitially empty.It then sendsa message elect(i)toits right neighbor, and adds the number i to its active list.

Chapter 16 Distributed System Structures b. If Pi receives a message elect(j)from the process on the left, it mustrespondinoneof threeways: 1. If this is the first elect messageithasseenor sent, Pi creates anew active listwiththenumbers i and j. It thensendsthe message elect(i), followedbythe message elect(j). 2. If i =j,thatis,themessagereceived doesnot contain Pi s number, then Pi adds j to its active list and forwards the message to its right neighbor. 3. If i = j,thatis, Pi receives the message elect(i), then the active listfor Pi nowcontainsthe numbersofall theactive processes in the system. Process Pi can now determine the largest number in the active list to identify the new coordinatorprocess. 16.11 Consideradistributed systemwithtwosites,AandB.Considerwhether siteA can distinguishamong thefollowing: a. Bgoesdown. b. The linkbetweenA andBgoesdown. c. B is extremely overloaded and its response time is 100 times longer than normal. What implications does your answerhave forrecoveryindistributed systems? Answer: OnetechniquewouldbeforBto periodicallysenda I-am-up messagetoAindicatingitisstill alive.IfAdoesnotreceivean I-amup message,it can assume eitherB or thenetwork link is down. Note that an I-am-up messagedoesnotallowAto distinguishbetween eachtypeof failure.OnetechniquethatallowsAbettertodetermine if the network is down is to send an Are-you-up messagetoB using an alternateroute.Ifit receivesareply,it can determinethatindeedthe

network linkisdownand thatBisup. If we assume thatAknows Bisup andisreachable(viathe I-amup mechanism) andthatAhassomevalue N that indicates a normal response time,Acouldmonitor theresponsetimefromBandcompare values to N,allowingAtodetermineifBisoverloaded ornot. Theimplicationsof bothof thesetechniques arethatA couldchoose anotherhost sayC inthe systemifBiseitherdown, unreachable, or overloaded.

Distributed File Systems 17CHAPTER No Exercises

Distributed Coordination 18CHAPTER No Exercises

Real-time Systems 19CHAPTER No Exercises

Multimedia Systems 20CHAPTER No Exercises

The Linux System 21CHAPTER Exercises 21.1 Dynamically loadable kernel modulesgiveflexibilitywhendriversare addedtoa system,butdothey have disadvantagestoo? Underwhat circumstanceswouldakernelbecompiledintoasingle binary file,and when woulditbebettertokeepit split into modules? Explainyour answer. Answer: Thereare twoprincipal drawbackswiththe useofmodules. The first is size: module management consumes unpageable kernel memory, and a basic kernel with a number of modules loaded will consume more memory than an equivalent kernel with the drivers compiled into the kernel image itself. This can be a very significant issue on machines with limited physical memory. Theseconddrawbackisthatmodules canincreasethe complexity ofthekernelbootstrapprocess.Itishardtoloadupasetof modules from diskifthedriverneededtoaccessthat disk itselfamodulethat needstobeloaded.Asaresult, managingthekernelbootstrapwith modulescanrequireextra work on thepartof the administrator: the modulesrequiredtobootstrapneedtobeplacedintoaramdisk image that is loaded alongside the initial kernel image when the system is initialized. In certain cases it is better to use a modular kernel, and in other casesitisbettertouseakernelwithits devicedriversprelinked.Where minimizing thesizeofthe kernelis important, thechoicewill depend onhowoftenthevarious device driversare used.If they areinconstant use, then modules are unsuitable. This is especially true where drivers are needed for the boot process itself. On the other hand, if some driversare notalwaysneeded,thenthe module mechanismal

Chapter 21 The Linux System lows thosedriverstobeloadedand unloaded on demand,potentially offeringanet savinginphysical memory. Wherea kernelistobebuiltthat mustbe usableonalarge variety of very different machines, then building it with modules is clearly preferabletousing asinglekernelwith dozensofunnecessarydrivers consumingmemory. Thisis particularly thecasefor commercially distributed kernels,wheresupporting thewidest varietyofhardwarein thesimplestmannerpossibleisapriority. However, if a kernel is being built for a single machine whose configurationisknownin advance, then compilingand usingmodules maysimplybeanunnecessary complexity.Incases likethis,theuseof modulesmay wellbeamatteroftaste. 21.2 Multithreading isacommonlyusedprogramming technique. Describe threedifferent ways thatthreadscouldbe implemented. Explainhow thesewayscompareto theLinux clone mechanism. When might each alternative mechanism be better or worse than using clones? Answer: Thread implementations can be broadly classified into two groups:kernel-basedthreadsanduser-modethreads. User-modethread packagesrely on some kernel support theymayrequiretimer interrupt facilities,forexample buttheschedulingbetweenthreadsisnot performedbythe kernelbutbysome libraryof user-modecode. Multiplethreadsinsuchan implementationappeartotheoperatingsystem asasingleexecution context. Whenthemultithreadedprocessisrunning, itdecidesforitselfwhichofitsthreadsto execute,usingnon-local jumpstoswitchbetweenthreadsaccording toits ownpreemptiveor non-preemptive scheduling rules. Alternatively,theoperating system kernelmayprovide supportfor threadsitself.Inthis case,thethreadsmaybe implementedasseparate processesthathappentoshareacompleteorpartial commonaddress space, or they may be implemented as separate execution contexts withinasingleprocess.Whicheverwaythethreadsareorganized,they appear as fully independent execution contexts to the application. Hybrid implementations are also possible, where a large number of threadsare made availabletothe applicationusingasmallernumber ofkernelthreads. Runnableuserthreadsarerunbythefirstavailable kernel thread. In Linux, threads are implemented within the kernel by a clone mechanismthat createsanewprocesswithinthe same virtualaddress spaceastheparentprocess. Unlikesomekernel-basedthreadpackages, theLinux kernel doesnot makeanydistinctionbetweenthreadsand processes:athreadissimplyaprocessthatdid notcreateanewvirtual addressspace whenit wasinitialized. Themainadvantageof implementingthreadsinthe kernel rather

thaninauser-mode library arethat: kernel-threaded systems can take advantage ofmultiple processors if they are available; and ifonethreadblocksinakernelserviceroutine (forexample,a system call or page fault), other threads are still able to run.

Exercises 73 Alesseradvantageis theabilitytoassign differentsecurityattributes to each thread. User-modeimplementationsdo nothavetheseadvantages.Because such implementationsrun entirelywithinasinglekernelexecution context, onlyonethreadcaneverberunningatonce,evenif multipleCPUs areavailable. Forthe samereason,if one thread entersa system call, no otherthreads canrun untilthat system call completes.Asaresult, onethreaddoingablockingdiskreadwillholdup everythreadinthe application. However,user-mode implementationsdohavetheir own advantages.The mostobviousisperformance:invoking the kernel s ownschedulerto switchbetweenthreadsinvolves enteringanewprotectiondomainasthe CPUswitchestokernelmode,whereasswitching betweenthreadsinusermodecanbeachieved simplybysavingand restoring the main CPU registers. User-mode threads may also consume less system memory:most UNIX systemswillreserveatleasta full page fora kernel stackfor each kernel thread,and this stackmay notbepageable. Thehybridapproach,implementingmultipleuserthreads overa smallernumberofkernelthreads,allowsabalancebetweenthesetradeoffstobeachieved. Thekernelthreadswill allowmultiplethreadsto be in blocking kernel calls at once and will permit running on multiple CPUs, and user-mode thread switching can occur within each kernel thread to perform lightweight threading without the overheads of having too many kernel threads. The downside of this approach is complexity:givingcontrol over thetradeoff complicates thethread library s user interface. 21.3 TheLinux kernel does notallowpagingoutof kernel memory.What effect does thisrestrictionhaveonthe kernel s design?Whatare two advantages andtwo disadvantagesofthisdesigndecision? Answer: Theprimary impactof disallowing pagingof kernel memory in Linuxisthatthe non-preemptabilityofthe kernelispreserved.Any processtaking a page fault,whetherinkernel orinusermode, risks beingrescheduledwhiletherequireddataispagedinfrom disk. Becausethekernelcanrelyo nnotbeing rescheduled during accesstoits primarydatastructures, lockingrequirementstoprotect theintegrity of thosedatastructuresare verygreatly simplified.Althoughdesign simplicity is a benefit in itself, it also provides an important performanceadva ntage on uniprocessormachinesdue to thefactthatitis notnecessarytodo additional lockingonmostinternaldatastructures. Thereareanumberofdisadvantages tothelack ofpageablekernel memory,however.Firstof all,it imposesconstraints ontheamount of memorythatthekernel can use.Itisunreasonabletokeep verylarge data structuresin non-pageable memory,since thatrepresents physical memory that absolutely cannotbeusedfor anythingelse.Thishas two impacts: firstofall,thekernelmustprune back manyofitsinternaldata structures manually,insteadof beingabletorelyona single virtualmemory mechanism to keep physical memory usage under control. Second,itmakesit infeasibleto implementcertain features thatrequire

large amounts of virtual memory in the kernel, such as the /tmp

Chapter 21 The Linux System filesystem (a fast virtual-memory-based file system found on some UNIX systems). Note that thecomplexityof managingpagefaultswhile running kernelcodeisnot anissuehere.TheLinux kernelcodeisalreadyable to deal with page faults:it needstobeabletodealwith system calls whose arguments reference user memory that may be paged out to disk. 21.4 What arethree advantages of dynamic(shared) linkage of libraries comparedto static linkage?Whataretwocaseswherestatic linkageis preferable? Answer: The primary advantages of shared libraries are that they reduce thememoryand disk spaceusedbyasystem,and they enhance maintainability. When shared libraries are being used by all running programs, thereisonlyone instanceof each system libraryroutineondisk,and at mostoneinstanceinphysicalmemory.Whenthelibraryin question is one used by many applications and programs, then the disk and memory savingscanbe quitesubstantial.Inaddition,the startuptime forrunning newprogramscanbereduced, sincemanyofthe common functionsneededbythatprogramare likelytobealready loadedinto physical memory. Maintainabilityisalsoa majoradvantageof dynamic linkage over static.If allrunningprograms usea shared libraryto access their system libraryroutines,thenupgrading thoseroutines, eithertoaddnew functionalityortofixbugs, canbedonesimplybyreplacing that shared library.Thereisno needtorecompileorrelinkany applications; any programs loaded afterthe upgradeiscompletewill automatically pick upthenew versionsofthe libraries. Thereareotheradvantagestoo.Aprogram that uses shared libraries canoftenbe adaptedfor specificpurposessimplyby replacing oneor more of its libraries, or even (if the system allows it, and most UNIXs including Linux do) adding a new one at run time. For example, a debugging library canbesubstitutedforanormal onetotraceaproblem in an application. Shared libraries also allowprogram binaries to be linked against commercial, proprietary library code without actually includinganyof thatcodeintheprogram s finalexecutablefile.Thisis importantbecauseonmost UNIX systems,manyofthestandardshared libraries areproprietary,and licensing issues maypreventincluding thatcodein executablefilestobe distributedtothirdparties. In someplaces,however,staticlinkageisappropriate.Oneexampleis inrescue environments for system administrators.Ifasystem administrator makesamistakewhile installinganynew libraries,orifhardware developsproblems,itis quitepossiblefortheexisting sharedlibraries to become corrupt. As a result, often a basic set of rescue utilities are linked statically, so that there is an opportunity to correct the fault

withouthavingtorelyonthe shared libraries functioningcorrectly. Thereare also performanceadvantagesthatsometimes make static linkagepreferablein specialcases.Forastart,dynamic linkage does increase thestartup time foraprogram, as the linking must nowbe

Exercises 75 doneatruntimeratherthanatcompile time.Dynamic linkage canalso sometimesincreasethe maximumworking setsizeof aprogram(the totalnumberofphysicalpagesofmemoryrequiredtoruntheprogram). Inashared library,the user hasnocontrol over whereinthe library binary file the various functions reside. Since most functions do not preciselyfillafullpageorpagesofthe library,loadingafunctionwill usuallyresultinloadinginpartsofthesurrounding functions, too.With static linkage,absolutelynofunctions that arenotreferenced (directly or indirectly)bythe applicationneedtobe loaded into memory. Otherissues surroundingstatic linkage includeeaseofdistribution: it is easier to distribute an executable file with static linkage than with dynamic linkageifthedistributorisnotcertain whethertherecipient will have thecorrect libraries installedinadvance.There mayalsobe commercial restrictions against redistributing some binaries as shared libraries. For example, the license for the UNIX Motif graphical environment allowsbinaries usingMotiftobe distributedfreelyaslong as they are statically linked, but the shared libraries may not be used without a license. 21.5 Comparetheuseofnetworkingsocketswiththeuseofshared memory asamechanismforcommunicatingdatabetweenprocessesona single computer.Whataretheadvantagesofeachmethod?When mighteach be preferred? Answer: Usingnetwork socketsratherthanshared memoryfor local communication hasa numberofadvantages.The mainadvantageis that thesocketprogramming interfacefeaturesa rich setof synchronizationfeatures. Aprocess caneasily determinewhennew data has arrived onasocket connection, howmuchdataispresent,and who sent it.Processescan blockuntil newdataarrives onasocket, or they canrequestthatasignalbedeliveredwhen data arrives.A socket also manages separate connections. A process with a socket open for receive can accept multiple connections to that socket and will be told when newprocessestry to connect or when oldprocessesdrop their connections. Shared memory offers none of these features. There is no way foraprocesstodeterminewhetheranotherprocesshas delivered or changed data in shared memory other than by going to look at the contents of that memory. It is impossible for a process to block and requestawakeupwhenshared memoryis delivered,andthereisno standardmechanismfor otherprocessestoestablisha shared memory linkto an existingprocess. However,shared memoryhastheadvantagethatitis verymuch faster than socket communicationsinmanycases. Whendataissent over a socket, it is typically copied from memory to memory multiple times.Shared memory updatesrequireno datacopies:if oneprocess updatesa data structureinsharedmemory,that updateis immediately visibletoall otherprocessessharing that memory.Sending orreceiving data overasocketrequiresthata kernel system servicecallbemade to initiate thetransfer, butshared memorycommunication canbeperformed entirely in user mode with no transfer of control required.

Chapter 21 The Linux System Socketcommunicationis typicallypreferredwhenconnectionmanagementisimportant orwhenthereisarequirementto synchronize thesenderand receiver.For example, serverprocesseswill usually establish a listening socketto which clients can connect when theywant to usethat service.Oncethe socketis established,individualrequests are also sent using the socket, so that the server can easily determine when a new request arrives and who it arrived from. In somecases,however,sharedmemoryispreferred.Sharedmemory is often a better solution when either large amounts of data are to be transferred orwhentwoprocesses need random access toalarge commondataset.Inthiscase,however,thecommunicatingprocesses may still need an extra mechanism in addition to shared memory to achieve synchronizationbetweenthemselves.TheXWindowSystem,a graphicaldisplayenvironmentfor UNIX,isagood exampleofthis: most graphicrequestsare sent over sockets,but shared memoryisoffered as an additional transportinspecial caseswhere largebitmaps areto be displayedonthe screen.Inthiscase,arequestto displaythe bitmap will stillbe sent overthesocket,butthe bulk dataofthebitmapitself will be sent via shared memory. 21.6 UNIX systems used to use disk-layout optimizations based on the rotation position of disk data,but modern implementations, including Linux, simply optimizeforsequentialdataaccess.Whydotheydoso? Of what hardware characteristicsdoessequentialaccess take advantage? Whyisrotational optimizationnolongersouseful? Answer: The performance characteristics of disk hardware have changed substantially in recent years. In particular, many enhancementshavebeeni ntroduced toincreasethemaximumbandwidththat can be achieved on a disk. In a modern system, there can be a long pipelinebetweentheoperatingsystemandthe disk sread-writehead. Adisk I/O requesthasto passthroughthe computer s localdiskcontroller, overbuslogictothediskdrive itself,andthen internallytothe disk, wherethereis likelytobeacomplexcontrollerthatcan cachedata accesses and potentially optimize the order of I/O requests. Becauseofthiscomplexity, thetimetaken forone I/O requesttobe acknowledged andforthenextrequesttobe generatedand received bythediskcan farexceedtheamountoftimebetween onedisksector passingundertheread-writeheadandthenextsectorheader arriving. In order to be able efficiently to read multiple sectors at once, disks will employareadaheadcache.Whileonesectorisbeingpassedback tothehostcomputer,thediskwillbebusyreadingthe next sectorsin anticipationofarequesttoread them.Ifreadrequestsstart arrivingin an orderthatbreaksthisreadahead pipeline,performance willdrop. Asaresult, performancebenefits substantiallyif theoperating system triestokeep I/O requestsin strict sequential order. Asecondfeatureof modern disksisthattheirgeometrycanbe very complex.Thenumberofsectorspercylindercan vary accordingtothe

position of the cylinder: more data can be squeezed into the longer tracks nearertheedgeofthediskthanatthecenterofthe disk.Foran operating system to optimize therotationalpositionofdataonsuch

Exercises disks,it wouldhavetohavecompleteunderstandingof this geometry, as wellasthetimingcharacteristicsofthediskanditscontroller.In general, onlythedisk sinternallogic candeterminetheoptimalscheduling ofI/Os, andthe disk sgeometryis likelytodefeatanyattemptbythe operating system to perform rotational optimizations.

Windows XP 22CHAPTER Exercises 22.1 What type of operating system is Windows XP? Describe two of its majorfeatures. Answer: A32/64 bitpreemptivemultitasking operating system supportingmultipleusers.( 1)Theabilityautomaticallytorepair application andoperating systemproblems.(2) Betternetworkingand device experience (includingdigitalphotography andvideo). 22.2 ListthedesigngoalsofWindows XP.Describetwoin detail. Answer: Design goalsinclude security,reliability,Windowsand POSIX application compatibility, high performance, extensibility, portability andinternational support.(1) Reliabilitywas perceived asastringent requirement and included extensive driver verification, facilities for catchingprogramming errors in user-level code, and a rigorous certificationproce ss forthird-party drivers, applications, and devices. (2) Achievinghighperformancerequiredexaminationof pastproblemareassuchas I/Operformance, server CPU bottlenecks, andthe scalability of multithreaded and multiprocessor environments. 22.3 DescribethebootingprocessforaWindows XP system. Answer: (1) Asthe hardware powers on,the BIOSbegins executing fromROMandloadsandexecutesthebootstraploaderfromthedisk.(2) The NTLDRprogramisloadedfromtheroot directoryofthe identified system deviceanddetermineswhichboot device containstheoperating system. (3) NTLDR loadsthe HALlibrary,kernel,and systemhive.The system hive indicates the required boot drivers and loads them. (4) Kernel execution begins by initializing the system and creating two processes: the system process containing all internal worker threads, andthe first user-modeinitializationprocess: SMSS.(5) SMSS further

Chapter 22 Windows XP initializes the systemby establishing paging files andloading device drivers.(6) SMSScreatestwoprocesses: WINLOGON,whichbringsup therestofthe system,and CSRSS (theWin32subsystemprocess). 22.4 Describethethree mainarchitecturallayersofWindows XP. Answer: (1) The HAL(HardwareAbstractionLayer)createsoperating system portabilitybyhidinghardwaredifferencesfrom theupper layersoftheoperating system.Administrativedetailsof low-levelfacilitiesareprovid edby HAL interfaces. HALpresentsavirtual-machine interfacethatisusedbythe kernel dispatcher,theexecutiveanddevice drivers. (2)The kernel layerprovidesa foundation forthe executive functionsand user-modesubsystems.Thekernelremainsin memory andisneverpreempted.Itsresponsibilitiesarethread scheduling,interruptand exceptionhandling,low-levelprocessorsynchronization, andpower failurerecovery.(3)Theexecutivelayerprovidesasetof servicesusedbyall subsystems: object manager,virtualmemorymanager, process manager, local procedure call facility, I/O manager, security monitor, plug-and-playmanager, registry, andbooting. 22.5 Whatis thejobof theobjectmanager? Answer: Objectspresentageneric setofkernelmodeinterfacestousermodeprograms. Objects aremanipulatedbytheexecutive-layerobject manager.Thejoboftheobjectmanageristo supervisethe allocation and use of all managed objects. 22.6 What typesof servicesdoestheprocessmanagerprovide?Whatisa localprocedure call? Answer: Theprocess managerprovidesservicesforcreating,deleting, andusingprocesses,threadsand jobs.Theprocessmanager also implements queuing anddelivery of asynchronous procedure calls to threads. The local procedure call (LPC)is a message-passing system. The operating system uses the LPC to pass requests and results betweenclientands erverprocesseswithinasingle machine,in particular between WindowsXP subsystems. 22.7 What aretheresponsibilitiesofthe I/O manager? Answer: The I/O manager is responsible for file systems, device drivers, and network drivers.The I/O managerkeepstrackof which device drivers,filterdrivers, andfile systemsare loaded and manages buffersfor I/O requests.Itfurthermoreassistsinproviding memorymapped file I/O and controls the cache manager for the whole I/O system. 22.8 DoesWindows XPofferany user-modeprocessesthatenableittorun programs developedforother operating systems? Describetwoofthese subsystems.

Answer: Environmentalsubsystemsare user-modeprocesseslayered over thenativeexecutableservicestoenable Windows XP torunprogramsdevelopedforoth er operating systems.(1)AWin32application calledthe virtual DOS machine (VDM)isprovided asauser-modeprocessto run MS-DOS applications. The VDM canexecute oremulateIntel 486 instructions and also provides routines to emulate MS-DOS BIOS

Exercises 81 services andprovidesvirtual driversfor screen,keyboard, and communication ports. (2) Windows-on-windows (WOW32)provideskernel andstubroutinesforWindows3.1 functions. Thestubroutinescallthe appropriate Win32 subroutines, converting the 16-bit addresses into 32-bit addresses. 22.9 WhattypesofnetworkingdoesWindowsXP support?HowdoesWindowsXP implementtransportprotocols? Describetwonetworkingprotocols. Answer: Supportisprovided forbothpeer-to-peer and client-server networking.Transportprotocolsare implementedasdrivers.(1)The TCP/IP packageincludes SNMP, DHCP, WINS,and NetBIOS support. (2) Point-to-point tunnelingprotocolisprovidedtocommunicate between remote-accessmodulesrunningonWindowsXPserversandotherclient systemsconnected over theinternet. Usingthisscheme, multi-protocol virtualprivate networks (VPNs) aresupported overtheinternet. 22.10 Howisthe NTFSnamespaceorganized?Describe. Answer: The NTFS namespaceisorganizedasahierarchyofdirectories whereeachdirectory usesaB+treedatastructureto storeanindexof thefile namesinthatdirectory.Theindexrootofadirectory contains the top level of the B+ tree. Each entry in the directory contains the name andfilereferenceofthe fileaswell astheupdate timestampand file size. 22.11 Howdoes NTFS handledata structures?Howdoes NTFSrecoverfrom a system crash? Whatis guaranteed afterarecoverytakes place? Answer: In NTFS,all file-system data structureupdates areperformed inside transactions.Beforea data structureisaltered,the transaction writesalogrecordcontainingredo andundoinformation.Acommit record iswrittentothe logafteratransactionhassucceeded.Aftera crashthe file system canberestoredtoa consistent statebyprocessing thelogrecords, firstredoingoperationsfor committedtransactionsand undoingoperationsfor transactions that didnot successfully commit. This schemedoes notguarantee that user filecontentsare correct after arecovery,butratherthatthe file-system data structures (file metadata) areundamagedandreflectsomeconsistentstatethat existedbeforethe crash. 22.12 Howdoes Windows XP allocate user memory? Answer: User memorycanbeallocatedaccordingtoseveral schemes: virtualmemory, memory-mappedfiles,heaps, and thread-local storage. 22.13 Describe some of the ways an application can use memory via the Win32 API. Answer: (1) Virtual memory provides several functions that allow an application to reserve and release memory, specifying the virtual addressat whichthememoryisallocated.(2)Afilemaybe memorymappedintoaddressspace, providing ameans fortwoprocesses to share memory. (3) When a Win32 process is initialized, it is created

withadefault heap.Private heapscanbecreatedthatprovideregionsof

Chapter 22 Windows XP reserved addressspaceforapplications.Threadmanagementfunctions areprovidedtoallocateandcontrolthread accessto privateheaps.(4) Athread-localstorage mechanismprovidesa wayfor global andstatic data to work properly in a multithreaded environment. Thread-lock storageallocatesglobalstorage onaper-threadbasis.

Influential Operating Systems 23CHAPTER No Exercises

S-ar putea să vă placă și