Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Lecture Notes on Operating System, Lecture notes of Operating Systems

Lecture notes on Operating System, covering topics such as Introduction to Operating System, Process Management, Process Coordination, Memory Management, Storage Management, and Case Studies. The notes also include references to textbooks and reference books on the subject.

Typology: Lecture notes

2021/2022

Uploaded on 05/11/2023

geek45
geek45 🇺🇸

4.4

(10)

50 documents

1 / 98

Toggle sidebar

Related documents


Partial preview of the text

Download Lecture Notes on Operating System and more Lecture notes Operating Systems in PDF only on Docsity! LECTURE NOTES ON OPERATING SYSTEM SUBJECT CODE: PCCS 4304 (3-0-0) PREPARED BY DR. PRASHANTA KUMAR PATRA COLLEGE OF ENGINEERING AND TECHNOLOGY, BHUBANESWAR PCCS4304 OPERATING SYSTEM (3-0-0) MODULE-I 12 Hours INTRODUCTION TO OPERATING SYSTEM: What is an Operating System? Simple Batch Systems, Multiprogramming and Time Sharing systems. Personal Computer Systems, Parallel Systems, Distributed Systems and Real time Systems. Operating System Structures: Operating System Services, System components, Protection system, Operating System Services, system calls PROCESS MANAGEMENT: Process Concept, Process Scheduling, Operation on Processes, Interprocess communication, Examples of IPC Systems, Multithreading Models, Threading Issues, Process Scheduling Basic concepts, scheduling criteria, scheduling algorithms, Thread Scheduling. MODULE-II 12 Hours PROCESS COORDINATION: Synchronization: The Critical section problem, Peterson’s solution, Synchronization hardware, Semaphores, Classical problems of synchronization, Monitors. Deadlocks: System model, Deadlock Characterization Methods for Handling Deadlocks, Deadlock Prevention, Deadlock avoidance, Deadlock Detection, recovery from Deadlock. MEMORY MANAGEMENT: Memory Management strategies, Logical versus Physical Address space, swapping, contiguous Allocation, Paging, Segmentation. Virtual Memory: Background, Demand paging, performance of Demand paging, Page Replacement, Page Replacement Algorithms. Allocation of frames, Thrashing, Demand Segmentation. MODULE-III 11 Hours STORAGE MANAGEMENT: File System Concept, Access Methods, File System Structure, File System Structure, File System Implementation, Directory implementation, Efficiency and Performance, Recovery, Overview of Mass Storage Structure, Disk Structure, Disk Scheduling, Disk Management, Swap- Space Management, I/O System Overview, I/O Hardware, Application I/O Interface, Kernel I/O Subsystem, Transforming I/O Request to Hardware Operation. CASE STUDIES: The LINUX System, Windows XP, Windows Vista TEXT BOOK: 1. Operating System Concepts – Abraham Silberschatz, Peter Baer Galvin, Greg Gagne, 8 th edition, Wiley-India, 2009. 2. Mordern Operating Systems – Andrew S. Tanenbaum, 3 rd Edition, PHI 3. Operating Systems: A Spiral Approach – Elmasri, Carrick, Levine, TMH Edition REFERENCE BOOK: 1. Operating Systems – Flynn, McHoes, Cengage Learning 2. Operating Systems – Pabitra Pal Choudhury, PHI 3. Operating Systems – William Stallings, Prentice Hall 4. Operating Systems – H.M. Deitel, P. J. Deitel, D. R. Choffnes, 3 rd Edition, Pearson Computer System Organisation  One or more CPUs, device controllers connect through common bus providing access to shared memory  Concurrent execution of CPUs and devices competing for memory cycles  I/O devices and the CPU can execute concurrently  Each device controller is in charge of a particular device type  Each device controller has a local buffer  CPU moves data from/to main memory to/from local buffers  I/O is from the device to local buffer of controller  Device controller informs CPU that it has finished its operation by causing an interrupt  Interrupt transfers control to the interrupt service routine generally, through the interrupt vector, which contains the addresses of all the service routines  Interrupt architecture must save the address of the interrupted instruction  Incoming interrupts are disabled while another interrupt is being processed to prevent a lost interrupt  A trap is a software-generated interrupt caused either by an error or a user request  An operating system is interrupt driven  The operating system preserves the state of the CPU by storing registers and the program counter  Determines which type of interrupt has occurred:  polling  vectored interrupt system  Separate segments of code determine what action should be taken for each type of interrupt I/O Structure  After I/O starts, control returns to user program only upon I/O completion o Wait instruction idles the CPU until the next interrupt o Wait loop (contention for memory access) o At most one I/O request is outstanding at a time, no simultaneous I/O processing  After I/O starts, control returns to user program without waiting for I/O completion o System call – request to the operating system to allow user to wait for I/O completion o Device-status table contains entry for each I/O device indicating its type, address, and state o Operating system indexes into I/O device table to determine device status and to modify table entry to include interrupt Storage Structure  Main memory – only large storage media that the CPU can access directly  Secondary storage – extension of main memory that provides large nonvolatile storage capacity  Magnetic disks – rigid metal or glass platters covered with magnetic recording material Direct Memory Access Structure  Used for high-speed I/O devices able to transmit information at close to memory speeds  Device controller transfers blocks of data from buffer storage directly to main memory without CPU intervention  Only one interrupt is generated per block, rather than the one interrupt per byte Storage Hierarchy  Storage systems organized in hierarchy o Speed o Cost o Volatility o A subset of total jobs in system is kept in memory o One job selected and run via job scheduling o When it has to wait (for I/O for example), OS switches to another job  Timesharing (multitasking) is logical extension in which CPU switches jobs so frequently that users can interact with each job while it is running, creating interactive computing o Response time should be < 1 second o Each user has at least one program executing in memory process o If several jobs ready to run at the same time  CPU scheduling o If processes don’t fit in memory, swapping moves them in and out to run o Virtual memory allows execution of processes not completely in memory  Operating System Operation  Interrupt driven by hardware  Software error or request creates exception or trap o Division by zero, request for operating system service  Other process problems include infinite loop, processes modifying each other or the operating system  Dual-mode operation allows OS to protect itself and other system components o User mode and kernel mode o Mode bit provided by hardware  Provides ability to distinguish when system is running user code or kernel code  Some instructions designated as privileged, only executable in kernel mode  System call changes mode to kernel, return from call resets it to user  Timer to prevent infinite loop / process hogging resources o Set interrupt after specific period o Operating system decrements counter o When counter zero generate an interrupt o Set up before scheduling process to regain control or terminate program that exceeds allotted time OS Services  One set of operating-system services provides functions that are helpful to the user: o User interface - Almost all operating systems have a user interface (UI)  Varies between Command-Line (CLI), Graphics User Interface (GUI), Batch o Program execution - The system must be able to load a program into memory and to run that program, end execution, either normally or abnormally (indicating error) o I/O operations - A running program may require I/O, which may involve a file or an I/O device o File-system manipulation - The file system is of particular interest. Obviously, programs need to read and write files and directories, create and delete them, search them, list file Information, permission management.  One set of operating-system services provides functions that are helpful to the user (Cont): o Communications – Processes may exchange information, on the same computer or between computers over a network  Communications may be via shared memory or through message passing (packets moved by the OS) o Error detection – OS needs to be constantly aware of possible errors  May occur in the CPU and memory hardware, in I/O devices, in user program  For each type of error, OS should take the appropriate action to ensure correct and consistent computing  Debugging facilities can greatly enhance the user’s and programmer’s abilities to efficiently use the system  Another set of OS functions exists for ensuring the efficient operation of the system itself via resource sharing o Resource allocation - When multiple users or multiple jobs running concurrently, resources must be allocated to each of them  Many types of resources - Some (such as CPU cycles, main memory, and file storage) may have special allocation code, others (such as I/O devices) may have general request and release code o Accounting - To keep track of which users use how much and what kinds of computer resources o Protection and security - The owners of information stored in a multiuser or networked computer system may want to control use of that information, concurrent processes should not interfere with each other  Protection involves ensuring that all access to system resources is controlled  Security of the system from outsiders requires user authentication, extends to defending external I/O devices from invalid access attempts  If a system is to be protected and secure, precautions must be instituted throughout it. A chain is only as strong as its weakest link.  Communications  Protection OS Structure n MS-DOS – written to provide the most functionality in the least space l Not divided into modules l Although MS-DOS has some structure, its interfaces and levels of functionality are not well separated Fig: MS Dos structure Layered Approach  The operating system is divided into a number of layers (levels), each built on top of lower layers. The bottom layer (layer 0), is the hardware; the highest (layer N) is the user interface.  With modularity, layers are selected such that each uses functions (operations) and services of only lower-level layers Fig: Layered System Fig: UNIX system structure Micro Kernel Sructure  Moves as much from the kernel into “user” space  Communication takes place between user modules using message passing  Benefits: o Easier to extend a microkernel o Easier to port the operating system to new architectures o More reliable (less code is running in kernel mode) o More secure  Detriments: o Performance overhead of user space to kernel space communication Virtual Machne  A virtual machine takes the layered approach to its logical conclusion. It treats hardware and the operating system kernel as though they were all hardware  A virtual machine provides an interface identical to the underlying bare hardware Fig: PCB Context Switching  When CPU switches to another process, the system must save the state of the old process and load the saved state for the new process via a context switch  Context of a process represented in the PCB  Context-switch time is overhead; the system does no useful work while switching  Time dependent on hardware support Process Scheduling Queues  Job queue – set of all processes in the system  Ready queue – set of all processes residing in main memory, ready and waiting to execute  Device queues – set of processes waiting for an I/O device  Processes migrate among the various queues Fig: Process Scheduling Schedulers  Long-term scheduler (or job scheduler) – selects which processes should be brought into the ready queue  Short-term scheduler (or CPU scheduler) – selects which process should be executed next and allocates CPU  Short-term scheduler is invoked very frequently (milliseconds)  (must be fast)  Long-term scheduler is invoked very infrequently (seconds, minutes)  (may be slow)  The long-term scheduler controls the degree of multiprogramming  Processes can be described as either: o I/O-bound process – spends more time doing I/O than computations, many short CPU bursts o CPU-bound process – spends more time doing computations; few very long CPU bursts Process Creation  Parent process create children processes, which, in turn create other processes, forming a tree of processes  Generally, process identified and managed via a process identifier (pid)  Resource sharing o Parent and children share all resources o Children share subset of parent’s resources o Parent and child share no resources  Execution o Parent and children execute concurrently o Parent waits until children terminate  Address space o Child duplicate of parent o Child has a program loaded into it  UNIX examples o fork system call creates new process o Convenience Producer Consumer Problem  Paradigm for cooperating processes, producer process produces information that is consumed by a consumer process o unbounded-buffer places no practical limit on the size of the buffer o bounded-buffer assumes that there is a fixed buffer size Fig: Producer Process Fig: Consumer Process IPC-Message Passing  Mechanism for processes to communicate and to synchronize their actions  Message system – processes communicate with each other without resorting to shared variables  IPC facility provides two operations: while (true) { /* Produce an item */ while (((in = (in + 1) % BUFFER SIZE count) == out) ; /* do nothing -- no free buffers */ buffer[in] = item; in = (in + 1) % BUFFER SIZE; } while (true) { while (in == out) ; // do nothing -- nothing to consume // remove an item from the buffer item = buffer[out]; out = (out + 1) % BUFFER SIZE; return item; } in = (in + 1) % BUFFER SIZE; } o send(message) – message size fixed or variable o receive(message)  If P and Q wish to communicate, they need to: o establish a communication link between them o exchange messages via send/receive  Implementation of communication link o physical (e.g., shared memory, hardware bus) o logical (e.g., logical properties) Direct Communication  Processes must name each other explicitly: o send (P, message) – send a message to process P o receive(Q, message) – receive a message from process Q  Properties of communication link o Links are established automatically o A link is associated with exactly one pair of communicating processes o Between each pair there exists exactly one link  The link may be unidirectional, but is usually bi-directional Indirect Communication  Messages are directed and received from mailboxes (also referred to as ports) o Each mailbox has a unique id o Processes can communicate only if they share a mailbox  Properties of communication link o Link established only if processes share a common mailbox o A link may be associated with many processes o Each pair of processes may share several communication links o Link may be unidirectional or bi-directional o Operations  create a new mailbox  send and receive messages through mailbox  destroy a mailbox o Primitives are defined as:  send(A, message) – send a message to mailbox A  receive(A, message) – receive a message from mailbox A o Allow a link to be associated with at most two processes o Allow only one process at a time to execute a receive operation o Allow the system to select arbitrarily the receiver. Sender is notified who the receiver was. Synchronisation  Message passing may be either blocking or non-blocking  Blocking is considered synchronous o Blocking send has the sender block until the message is received o Blocking receive has the receiver block until a message is available  Non-blocking is considered asynchronous o Non-blocking send has the sender send the message and continue o Non-blocking receive has the receiver receive a valid message or null Buffering Queue of messages attached to the link; implemented in one of three ways 1. Zero capacity – 0 messages Sender must wait for receiver (rendezvous) 2. Bounded capacity – finite length of n messages Sender must wait if link full  One-to-One o Each user-level thread maps to kernel thread o Examples o Windows NT/XP/2000 o Linux o Solaris 9 and later  Many-to-Many o Allows many user level threads to be mapped to many kernel threads o Allows the operating system to create a sufficient number of kernel threads o Solaris prior to version 9 o Windows NT/2000 with the ThreadFiber package Thread Library  Thread library provides programmer with API for creating and managing threads  Two primary ways of implementing o Library entirely in user space o Kernel-level library supported by the OS Pthreads  May be provided either as user-level or kernel-level  A POSIX standard (IEEE 1003.1c) API for thread creation and synchronization  API specifies behavior of the thread library, implementation is up to development of the library  Common in UNIX operating systems (Solaris, Linux, Mac OS X) Java Threads  Java threads are managed by the JVM  Typically implemented using the threads model provided by underlying OS  Java threads may be created by: o Extending Thread class o Implementing the Runnable interface Threading Issues  Semantics of fork() and exec() system calls  Thread cancellation of target thread o Asynchronous or deferred  Signal handling  Thread pools  Thread-specific data  Scheduler activations Thread Cancellation  Terminating a thread before it has finished  Two general approaches: o Asynchronous cancellation terminates the target thread immediately o Deferred cancellation allows the target thread to periodically check if it should be cancelled Thread Pools  Create a number of threads in a pool where they await work  Advantages: o Usually slightly faster to service a request with an existing thread than create a new thread o Allows the number of threads in the application(s) to be bound to the size of the pool Thread Scheduling  Distinction between user-level and kernel-level threads  Many-to-one and many-to-many models, thread library schedules user-level threads to run on LWP o Known as process-contention scope (PCS) since scheduling competition is within the process  Dispatcher module gives control of the CPU to the process selected by the short- term scheduler; this involves: o switching context o switching to user mode o jumping to the proper location in the user program to restart that program  Dispatch latency – time it takes for the dispatcher to stop one process and start another running CPU Scheduling Criteria  Max CPU utilization  Max throughput  Min turnaround time  Min waiting time  Min response time CPU Scheduling Algorithms A. First Come First Serve Scheduling  Schedule the task first which arrives first  Non preemptive In nature B. Shortest Job First Scheduling  Associate with each process the length of its next CPU burst. Use these lengths to schedule the process with the shortest time  SJF is optimal – gives minimum average waiting time for a given set of processes o The difficulty is knowing the length of the next CPU request Priority Scheduling  A priority number (integer) is associated with each process  The CPU is allocated to the process with the highest priority (smallest integer  highest priority) o Preemptive o nonpreemptive  SJF is a priority scheduling where priority is the predicted next CPU burst time  Problem  Starvation – low priority processes may never execute  Solution  Aging – as time progresses increase the priority of the process Round Robin Scheduling  Each process gets a small unit of CPU time (time quantum), usually 10-100 milliseconds. After this time has elapsed, the process is preempted and added to the end of the ready queue.  If there are n processes in the ready queue and the time quantum is q, then each process gets 1/n of the CPU time in chunks of at most q time units at once. No process waits more than (n-1)q time units.  Performance o q large  FIFO o q small  q must be large with respect to context switch, otherwise overhead is too high Multilevel Queue Scheduling  Ready queue is partitioned into separate queues: foreground (interactive) background (batch)  Each queue has its own scheduling algorithm o foreground – RR o background – FCFS  Scheduling must be done between the queues o Fixed priority scheduling; (i.e., serve all from foreground then from background). Possibility of starvation. o Time slice – each queue gets a certain amount of CPU time which it can schedule amongst its processes; i.e., 80% to foreground in RR o 20% to background in FCFS Multilevel Feedback Queue Scheduling  A process can move between the various queues; aging can be implemented this way  Multilevel-feedback-queue scheduler defined by the following parameters: o number of queues o scheduling algorithms for each queue o method used to determine when to upgrade a process o method used to determine when to demote a process o method used to determine which queue a process will enter when that process needs service   Consider a system consisting of n processes {P0, P1, ..., Pn−1}. Each process has a segment of code, called a critical section, in which the process may be changing common variables, updating a table, writing a file, and so on.  The important feature of the system is that, when one process is executing in its critical section, no other process is allowed to execute in its critical section. That is, no two processes are executing in their critical sections at the same time.  The critical-section problem is to design a protocol that the processes can use to cooperate. Each process must request permission to enter its critical section. The section of code implementing this  request is the entry section. The critical section may be followed by an exit section. The remaining code is the remainder section. Solution to Critical Section Problem 1. Mutual Exclusion - If process Pi is executing in its critical section, then no other processes can be executing in their critical sections 2. Progress - If no process is executing in its critical section and there exist some processes that wish to enter their critical section, then the selection of the processes that will enter the critical section next cannot be postponed indefinitely 3. Bounded Waiting - A bound must exist on the number of times that other processes are allowed to enter their critical sections after a process has made a request to enter its critical section and before that request is granted  Assume that each process executes at a nonzero speed  No assumption concerning relative speed of the N processes Peterson’s Solution  Two process solution  Assume that the LOAD and STORE instructions are atomic; that is, cannot be interrupted.  The two processes share two variables: o int turn; o Boolean flag[2]  The variable turn indicates whose turn it is to enter the critical section.  The flag array is used to indicate if a process is ready to enter the critical section. flag[i] = true implies that process Pi is ready! Hardware Synchronization  Many systems provide hardware support for critical section code  Uniprocessors – could disable interrupts o Currently running code would execute without preemption o Generally too inefficient on multiprocessor systems  Operating systems using this not broadly scalable  Modern machines provide special atomic hardware instructions  Atomic = non-interruptable o Either test memory word and set value o Or swap contents of two memory words Solution to Critical Section Problem using Lock do { acquire lock critical section release lock remainder section } while (TRUE); TestAndndSet Instruction boolean TestAndSet (boolean *target) { boolean rv = *target; *target = TRUE; return rv: } Solution using TestAndSet  Shared boolean variable lock., initialized to false.  Solution: do { while ( TestAndSet (&lock )) ; // do nothing // critical section lock = FALSE; // remainder section } while (TRUE);  Binary semaphore – integer value can range only between 0 and 1; can be simpler to implement o Also known as mutex locks  Can implement a counting semaphore S as a binary semaphore  Provides mutual exclusion Semaphore mutex; // initialized to 1 do { wait (mutex); // Critical Section signal (mutex); // remainder section } while (TRUE); Semaphore Implementation  Must guarantee that no two processes can execute wait () and signal () on the same semaphore at the same time  Thus, implementation becomes the critical section problem where the wait and signal code are placed in the crtical section. o Could now have busy waiting in critical section implementation  But implementation code is short  Little busy waiting if critical section rarely occupied  Note that applications may spend lots of time in critical sections and therefore this is not a good solution.  With each semaphore there is an associated waiting queue. Each entry in a waiting queue has two data items: o value (of type integer) o pointer to next record in the list  Two operations: o block – place the process invoking the operation on the appropriate waiting queue. o wakeup – remove one of processes in the waiting queue and place it in the ready queue.  Implementation of wait: wait(semaphore *S) { S->value--; if (S->value < 0) { add this process to S->list; block(); } }  Implementation of signal: signal(semaphore *S) { S->value++; if (S->value <= 0) { remove a process P from S->list; wakeup(P); } } Classical Problems of Synchronization  Bounded-Buffer Problem  Readers and Writers Problem  Dining-Philosophers Problem Bounded-Buffer Problem The pool consists of n buffers, each capable of holding one item. The mutex semaphore provides mutual exclusion for accesses to the buffer pool and is initialized to the value 1. The empty and full semaphores count the number of empty and full buffers. The semaphore empty is initialized to the value n; the semaphore full is initialized to the value 0.  N buffers, each can hold one item  Semaphore mutex initialized to the value 1  Semaphore full initialized to the value 0  Semaphore empty initialized to the value N.  The structure of the producer process do { // produce an item in nextp wait (empty); wait (mutex); // add the item to the buffer signal (mutex); signal (full); } while (TRUE);  The structure of the consumer process do { wait (full); wait (mutex); // remove an item from buffer to nextc signal (mutex); signal (empty); chopstick that is already in the hand of a neighbor. When a hungry philosopher has both her chopsticks at the same time, she eats without releasing the chopsticks. When she is finished eating, she puts down both chopsticks and starts thinking again.  Shared data o Bowl of rice (data set) o Semaphore chopstick [5] initialized to 1  The structure of Philosopher i: do { wait ( chopstick[i] ); wait ( chopStick[ (i + 1) % 5] ); // eat signal ( chopstick[i] ); signal (chopstick[ (i + 1) % 5] ); // think } while (TRUE); Monitors  A high-level abstraction that provides a convenient and effective mechanism for process synchronization  Only one process may be active within the monitor at a time monitor monitor-name { // shared variable declarations procedure P1 (…) { …. } … procedure Pn (…) {……} Initialization code ( ….) { … } … } } Schematic view of a Monitor Condition Variables  condition x, y;  Two operations on a condition variable: o x.wait () – a process that invokes the operation is suspended.  x.signal () – resumes one of processes (if any) that invoked x.wait () Monitor with Condition Variables Monitor Implementation Using Semaphores  Variables semaphore mutex; // (initially = 1) semaphore next; // (initially = 0) int next-count = 0;  Each procedure F will be replaced by wait(mutex); … body of F; … if (next_count > 0) signal(next) else signal(mutex);  Mutual exclusion within a monitor is ensured. Monitor Implementation For each condition variable x, we have: semaphore x_sem; // (initially = 0) int x-count = 0; The operation x.wait can be implemented as: x-count++; if (next_count > 0) signal(next); else signal(mutex); wait(x_sem); x-count--; The operation x.signal can be implemented as: if (x-count > 0) {  Pi is holding an instance of Rj Fig: RAG Fig: RAG with a deadlock  If graph contains no cycles  no deadlock  If graph contains a cycle  o if only one instance per resource type, then deadlock o if several instances per resource type, possibility of deadlock Methods for Handling Deadlock  Ensure that the system will never enter a deadlock state  Allow the system to enter a deadlock state and then recover  Ignore the problem and pretend that deadlocks never occur in the system; used by most operating systems, including UNIX Deadlock Prevention  Mutual Exclusion – not required for sharable resources; must hold for nonsharable resources  Hold and Wait – must guarantee that whenever a process requests a resource, it does not hold any other resources o Require process to request and be allocated all its resources before it begins execution, or allow process to request resources only when the process has none o Low resource utilization; starvation possible  No Preemption – o If a process that is holding some resources requests another resource that cannot be immediately allocated to it, then all resources currently being held are released o Preempted resources are added to the list of resources for which the process is waiting o Process will be restarted only when it can regain its old resources, as well as the new ones that it is requesting  Circular Wait – impose a total ordering of all resource types, and require that each process requests resources in an increasing order of enumeration Deadlock Avoidance  Requires that the system has some additional a priori information available  Simplest and most useful model requires that each process declare the maximum number of resources of each type that it may need  The deadlock-avoidance algorithm dynamically examines the resource-allocation state to ensure that there can never be a circular-wait condition.  Resource-allocation state is defined by the number of available and allocated resources, and the maximum demands of the processes Safe state  When a process requests an available resource, system must decide if immediate allocation leaves the system in a safe state  System is in safe state if there exists a sequence <P1, P2, …, Pn> of ALL the processes is the systems such that for each Pi, the resources that Pi can still request can be satisfied by currently available resources + resources held by all the Pj, with j < i  That is: o If Pi resource needs are not immediately available, then Pi can wait until all Pj have finished o When Pj is finished, Pi can obtain needed resources, execute, return allocated resources, and terminate o When Pi terminates, Pi +1 can obtain its needed resources, and so on Facts Deadlock Avoidance Algorithm  Single instance of a resource type o Use a resource-allocation graph  Multiple instances of a resource type o Use the banker’s algorithm n If a system is in safe state  no deadlocks n If a system is in unsafe state  possibility of deadlock n Avoidance  ensure that a system will never enter an unsafe state. Deadlock Detection  Allow system to enter deadlock state  Detection algorithm  Recovery scheme Recovery from Deadlock A. Process Termination  Abort all deadlocked processes  Abort one process at a time until the deadlock cycle is eliminated  In which order should we choose to abort? o Priority of the process o How long process has computed, and how much longer to completion o Resources the process has used o Resources process needs to complete o How many processes will need to be terminated B. Resource Preemption  Selecting a victim – minimize cost  Rollback – return to some safe state, restart process for that state  Starvation – same process may always be picked as victim, include number of rollback in cost factor Memory Management  Program must be brought (from disk) into memory and placed within a process for it to be run  Main memory and registers are only storage CPU can access directly  Register access in one CPU clock (or less)  Main memory can take many cycles  Cache sits between main memory and CPU registers  Protection of memory required to ensure correct operation  A pair of base and limit registers define the logical address space Logical vs Physical Address Space  The concept of a logical address space that is bound to a separate physical address space is central to proper memory management o Logical address – generated by the CPU; also referred to as virtual address o Physical address – address seen by the memory unit  Logical and physical addresses are the same in compile-time and load-time address-binding schemes; logical (virtual) and physical addresses differ in execution-time address-binding scheme Address Binding  Address binding of instructions and data to memory addresses can happen at three different stages o Compile time: If memory location known a priori, absolute code can be generated; must recompile code if starting location changes o Load time: Must generate relocatable code if memory location is not known at compile time o Execution time: Binding delayed until run time if the process can be moved during its execution from one memory segment to another. Need hardware support for address maps (e.g., base and limit registers) Memory Management Unit  Hardware device that maps virtual to physical address  In MMU scheme, the value in the relocation register is added to every address generated by a user process at the time it is sent to memory  The user program deals with logical addresses; it never sees the real physical addresses Dynamic Loading  Routine is not loaded until it is called  Better memory-space utilization; unused routine is never loaded  Useful when large amounts of code are needed to handle infrequently occurring cases  No special support from the operating system is required implemented through program design Dynamic Linking  Linking postponed until execution time  Small piece of code, stub, used to locate the appropriate memory-resident library routine  Stub replaces itself with the address of the routine, and executes the routine  Operating system needed to check if routine is in processes’ memory address  Dynamic linking is particularly useful for libraries  System also known as shared libraries Swapping  A process can be swapped temporarily out of memory to a backing store, and then brought back into memory for continued execution  Backing store – fast disk large enough to accommodate copies of all memory images for all users; must provide direct access to these memory images  Roll out, roll in – swapping variant used for priority-based scheduling algorithms; lower-priority process is swapped out so higher-priority process can be loaded and executed  Major part of swap time is transfer time; total transfer time is directly proportional to the amount of memory swapped  Modified versions of swapping are found on many systems (i.e., UNIX, Linux, and Windows)  System maintains a ready queue of ready-to-run processes which have memory images on disk  To run a program of size n pages, need to find n free frames and load program  Set up a page table to translate logical to physical addresses  Internal fragmentation  Address generated by CPU is divided into: o Page number (p) – used as an index into a page table which contains base address of each page in physical memory o Page offset (d) – combined with base address to define the physical memory address that is sent to the memory unit Implementation of Page table  Page table is kept in main memory  Page-table base register (PTBR) points to the page table  Page-table length register (PRLR) indicates size of the page table  In this scheme every data/instruction access requires two memory accesses. One for the page table and one for the data/instruction.  The two memory access problem can be solved by the use of a special fast- lookup hardware cache called associative memory or translation look-aside buffers (TLBs)  Some TLBs store address-space identifiers (ASIDs) in each TLB entry – uniquely identifies each process to provide address-space protection for that process Paging with TLB Memory Protection  Memory protection implemented by associating protection bit with each frame  Valid-invalid bit attached to each entry in the page table: o “valid” indicates that the associated page is in the process’ logical address space, and is thus a legal page o “invalid” indicates that the page is not in the process’ logical address space Shared Pages  Shared code o One copy of read-only (reentrant) code shared among processes (i.e., text editors, compilers, window systems). o Shared code must appear in same location in the logical address space of all processes  Private code and data o Each process keeps a separate copy of the code and data o The pages for the private code and data can appear anywhere in the logical address space Structure of Page table Hierarchical Paging  Break up the logical address space into multiple page tables  A simple technique is a two-level page table o With each entry in segment table associate:  validation bit = 0  illegal segment  read/write/execute privileges  Protection bits associated with segments; code sharing occurs at segment level  Since segments vary in length, memory allocation is a dynamic storage- allocation problem  A segmentation example is shown in the following diagram Virtual Memory Management  Virtual memory – separation of user logical memory from physical memory. o Only part of the program needs to be in memory for execution o Logical address space can therefore be much larger than physical address space o Allows address spaces to be shared by several processes o Allows for more efficient process creation  Virtual memory can be implemented via: o Demand paging o Demand segmentation Demand Paging  Bring a page into memory only when it is needed o Less I/O needed o Less memory needed o Faster response o More users  Page is needed  reference to it o invalid reference  abort o not-in-memory  bring to memory  Lazy swapper – never swaps a page into memory unless page will be needed o Swapper that deals with pages is a pager  With each page table entry a valid–invalid bit is associated (v  in-memory, i  not-in-memory)  Initially valid–invalid bit is set to i on all entries  During address translation, if valid–invalid bit in page table entry is I  page fault Page Fault If there is a reference to a page, first reference to that page will trap to operating system: page fault 1. Operating system looks at another table to decide: l Invalid reference  abort l Just not in memory 2. Get empty frame 3. Swap page into frame 4. Reset tables 5. Set validation bit = v 6. Restart the instruction that caused the page fault Page Replacement  Prevent over-allocation of memory by modifying page-fault service routine to include page replacement  Use modify (dirty) bit to reduce overhead of page transfers – only modified pages are written to disk  Page replacement completes separation between logical memory and physical memory – large virtual memory can be provided on a smaller physical memory  Find the location of the desired page on disk  Find a free frame: - If there is a free frame, use it - If there is no free frame, use a page replacement algorithm to select a victim frame  Bring the desired page into the (newly) free frame; update the page and frame tables m S s pa m sS ps i ii i ii      for allocation frames ofnumber total process of size Global vs Local Allocation  Global replacement – process selects a replacement frame from the set of all frames; one process can take a frame from another  Local replacement – each process selects from only its own set of allocated frames Thrashing  If a process does not have “enough” pages, the page-fault rate is very high. This leads to: o low CPU utilization o operating system thinks that it needs to increase the degree of multiprogramming o another process added to the system  Thrashing  a process is busy swapping pages in and out MODULE-III File System File  Contiguous logical address space  Types: o Data  numeric  character  binary o Program File Structure  None - sequence of words, bytes  Simple record structure o Lines o Fixed length o Variable length  Complex Structures o Formatted document o Relocatable load file  Can simulate last two with first method by inserting appropriate control characters  Who decides: o Operating system l Program File Attribute  Name – only information kept in human-readable form  Identifier – unique tag (number) identifies file within file system  Type – needed for systems that support different types  Location – pointer to file location on device  Size – current file size  Protection – controls who can do reading, writing, executing  Time, date, and user identification – data for protection, security, and usage monitoring  Information about files are kept in the directory structure, which is maintained on the disk File Types C. Tree Structure Directory  Efficient searching  Grouping Capability D. Acyclic Graph Directories  Have shared subdirectories and files File Sharing  Sharing of files on multi-user systems is desirable  Sharing may be done through a protection scheme  On distributed systems, files may be shared across a network  Network File System (NFS) is a common distributed file-sharing method  User IDs identify users, allowing permissions and protections to be per-user  Group IDs allow users to be in groups, permitting group access rights  Uses networking to allow file system access between systems o Manually via programs like FTP o Automatically, seamlessly using distributed file systems o Semi automatically via the world wide web  Client-server model allows clients to mount remote file systems from servers o Server can serve multiple clients o Client and user-on-client identification is insecure or complicated o NFS is standard UNIX client-server file sharing protocol o CIFS is standard Windows protocol o Standard operating system file calls are translated into remote calls  Distributed Information Systems (distributed naming services) such as LDAP, DNS, NIS, Active Directory implement unified access to information needed for remote computing  Remote file systems add new failure modes, due to network failure, server failure  Recovery from failure can involve state information about status of each remote request  Stateless protocols such as NFS include all information in each request, allowing easy recovery but less security  Consistency semantics specify how multiple users are to access a shared file simultaneously o Similar to Ch 7 process synchronization algorithms  Tend to be less complex due to disk I/O and network latency (for remote file systems o Andrew File System (AFS) implemented complex remote file sharing semantics o Unix file system (UFS) implements:  Writes to an open file visible immediately to other users of the same open file  Sharing file pointer to allow multiple users to read and write concurrently o AFS has session semantics  Writes only visible to sessions starting after the file is closed File System Structure  File structure o Logical storage unit o Collection of related information n File system resides on secondary storage (disks) n File system organized into layers n File control block – storage structure consisting of information about a file C. Indexed Allocation n Brings all pointers together into the index block. n Need index table n Random access n Dynamic access without external fragmentation, but have overhead of index block. Secondary Storage Structure Magnetic Disk  Magnetic disks provide bulk of secondary storage of modern computers o Drives rotate at 60 to 200 times per second o Transfer rate is rate at which data flow between drive and computer o Positioning time (random-access time) is time to move disk arm to desired cylinder (seek time) and time for desired sector to rotate under the disk head (rotational latency) o Head crash results from disk head making contact with the disk surface  That’s bad  Disks can be removable  Drive attached to computer via I/O bus o Busses vary, including EIDE, ATA, SATA, USB, Fibre Channel, SCSI o Host controller in computer uses bus to talk to disk controller built into drive or storage array Magnetic Tap  Was early secondary-storage medium  Relatively permanent and holds large quantities of data  Access time slow  Random access ~1000 times slower than disk  Mainly used for backup, storage of infrequently-used data, transfer medium between systems  Kept in spool and wound or rewound past read-write head  Once data under head, transfer rates comparable to disk  20-200GB typical storage Disk Structure  Disk drives are addressed as large 1-dimensional arrays of logical blocks, where the logical block is the smallest unit of transfer.  The 1-dimensional array of logical blocks is mapped into the sectors of the disk sequentially. o Sector 0 is the first sector of the first track on the outermost cylinder. o Mapping proceeds in order through that track, then the rest of the tracks in that cylinder, and then through the rest of the cylinders from outermost to innermost. Disk Scheduling  The operating system is responsible for using hardware efficiently — for the disk drives, this means having a fast access time and disk bandwidth.  Access time has two major components o Seek time is the time for the disk are to move the heads to the cylinder containing the desired sector. C-SCAN  Provides a more uniform wait time than SCAN.  The head moves from one end of the disk to the other. servicing requests as it goes. When it reaches the other end, however, it immediately returns to the beginning of the disk, without servicing any requests on the return trip.  Treats the cylinders as a circular list that wraps around from the last cylinder to the first one C-LOOK  Version of C-SCAN  Arm only goes as far as the last request in each direction, then reverses direction immediately, without first going all the way to the end of the disk. Disk Management  Low-level formatting, or physical formatting — Dividing a disk into sectors that the disk controller can read and write.  To use a disk to hold files, the operating system still needs to record its own data structures on the disk. o Partition the disk into one or more groups of cylinders. o Logical formatting or “making a file system”.  Boot block initializes system. o The bootstrap is stored in ROM. o Bootstrap loader program.  Methods such as sector sparing used to handle bad blocks.  The controller can be told to replace each bad sector logically with one of the spare sectors. This scheme is known as sector sparing or forwarding. Swap Space Management  Swap-space — Virtual memory uses disk space as an extension of main memory.  Swap-space can be carved out of the normal file system or, more commonly, it can be in a separate disk partition.  A swap space can reside in one of two places: it can be carved out of the normal file system, or it can be in a separate disk partition.  If the swap space is simply a large file within the file system, normal file-system routines can be used to create it, name it, and allocate its space.  Alternatively, swap space can be created in a separate raw partition. No file system or directory structure is placed in this space.  A separate swap-space storage manager is used to allocate and deallocate the blocks from the raw partition. I/O Systems I/O Hardware  A device communicates with a computer system by sending signals over a cable or even through the air. The device communicates with the machine via a connection point, or port—for example, a serial port.  If devices share a common set of wires, the connection is called a bus.  A bus is a set of wires and a rigidly defined protocol that specifies a set of messages that can be sent on the wires.  When device A has a cable that plugs into device B, and device B has a cable that plugs into device C, and device C plugs into a port on the computer, this arrangement is called a daisy chain. A daisy chain usually operates as a bus.  A PCI bus (the common PC system bus) connects the processor–memory subsystem to fast devices, and an expansion bus connects relatively slow devices, such as the keyboard and serial and USB ports.  Disks are connected together on a Small Computer System Interface (SCSI) bus plugged into a SCSI controller. Direct Memory Access  Used to avoid programmed I/O for large data movement  Requires DMA controller  Bypasses CPU to transfer data directly between I/O device and memory Application I/O Interface  I/O system calls encapsulate device behaviors in generic classes  Device-driver layer hides differences among I/O controllers from kernel  Devices vary in many dimensions o Character-stream or block o Sequential or random-access o Sharable or dedicated o Speed of operation o read-write, read only, or write only Kernel I/O Structure Characteristics of I/O Devices Block and Character Devices  Block devices include disk drives o Commands include read, write, seek o Raw I/O or file-system access o Memory-mapped file access possible  Character devices include keyboards, mice, serial ports o Commands include get, put o Libraries layered on top allow line editing Network Devices  Varying enough from block and character to have own interface  Unix and Windows NT/9x/2000 include socket interface o Separates network protocol from network operation o Includes select functionality  Approaches vary widely (pipes, FIFOs, streams, queues, mailboxes) Clock and Timers  Provide current time, elapsed time, timer  Programmable interval timer used for timings, periodic interrupts Blocking and Non-blocking I/O  Blocking - process suspended until I/O completed o Easy to use and understand o Insufficient for some needs  Nonblocking - I/O call returns as much as available o User interface, data copy (buffered I/O) o Implemented via multi-threading
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved