CSUSM denial

Document Sample
CSUSM denial Powered By Docstoc
					CSE433




             Deadlocks




CS433-W4-1               Tarun Soni
The plan



   The story so far
   •Computer architecture and organization
   •OS Structure and layers, Processes and threads
   •Inter-process communications
       •Producer Consumer, Dining Philosopher problems
       •Mutexes, Semaphores
       •Pipes, Message passing




CS433-W4-2                                        Tarun Soni
   The plan

   1. Computer architecture and organization
   2. OS Structure and layers, Processes and threads
   3. Inter-process communications
   4. Unix IPCs, Deadlocks and Starvation
   5. Memory management, Virtual memory
   6. File system interface, implementation
   7. I/O management
   8. Network structures, distributed systems
   9. Protection, Security
   10. Unix/Wrap up




CS433-W4-3                                             Tarun Soni
  Unix: Miscellaneous services                  Signals

                                           /* this is the handler */
#include <stdio.h>
                                           void sigint_handler(int sig)
#include <stdlib.h>
                                           {
#include <errno.h>
                                              printf("Not this time!\n");
#include <signal.h>
                                           }
int main(void)
   {
     void sigint_handler(int sig); /* prototype */
     char s[200];

           /* set up the handler */
     if (signal(SIGINT, sigint_handler) == SIG_ERR) {
        perror("signal");
        exit(1);
     }
……. Other code here …..             Basically software interrupts
}                                   Implementation?

   CS433-W4-4                                              Tarun Soni
Unix: Miscellaneous services                     Shared memory

   #define SHM_SIZE 1024 /* make it a 1K shared memory segment */
   int main(int argc, char *argv[])
   {
… includes and defines omitted…
      /* make the key: */
      if ((key = ftok("shmdemo.c", 'R')) == -1) { error stuff }
      /* connect to (and possibly create) the segment: */
      if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {err}
      /* attach to the segment to get a pointer to it: */
      data = shmat(shmid, (void *)0, 0);
      if (data == (char *)(-1)) { error stuff }
      /* read or modify the segment, based on the command line: */
          strncpy(data, argv[1], SHM_SIZE);
     /* detach from the segment: */
      if (shmdt(data) == -1) {error stuff }
      shmctl(shmid, IPC_RMID, NULL); /* delete the segment */
}

                               What about a ^C in the middle of this ?

CS433-W4-5                                                    Tarun Soni
Unix: Miscellaneous services                           Pipes


             int main()
                {
                  int pfds[2];
                  char buf[30];
                                          Named pipes and FIFO also available
                   pipe(pfds);            mknod("myfifo", S_IFIFO | 0644 , 0);

                   if (!fork()) {
                      printf(" CHILD: writing to the pipe\n");
                      write(pfds[1], "test", 5);
                      printf(" CHILD: exiting\n");
                      exit(0);
                   } else {
                      printf("PARENT: reading from pipe\n");
                      read(pfds[0], buf, 5);
                      printf("PARENT: read \"%s\"\n", buf);
                      wait(NULL);
                   }
               }
CS433-W4-6                                                       Tarun Soni
Deadlocks: The plan



   •    System Model
   •    Deadlock Characterization
   •    Methods for Handling Deadlocks
   •    Deadlock Prevention
   •    Deadlock Avoidance
   •    Deadlock Detection
   •    Recovery from Deadlock
   •    Combined Approach to Deadlock Handling




CS433-W4-7                                       Tarun Soni
Deadlocks: The problem


    • A set of blocked processes each holding a resource
      and waiting to acquire a resource held by another
      process in the set.
    • Example
       – System has 2 tape drives.
       – P1 and P2 each hold one tape drive and each
         needs another one.
    • Example
       – semaphores A and B, initialized to 1

                    P0            P1
                  wait (A);            wait(B)
                  wait (B);            wait(A)


CS433-W4-8                                         Tarun Soni
Deadlocks: The definition


• Permanent blocking of a set of processes that either
  compete for system resources or communicate with each
  other
• Involves conflicting needs for resources by two or more
  processes
• There is no satisfactory solution in the general case



 • 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.

CS433-W4-9                                           Tarun Soni
Deadlocks: The framework/system model


   • Resource types R1, R2, . . ., Rm
          CPU cycles, memory space, I/O devices
   • Each resource type Ri has Wi instances.
   • Each process utilizes a resource as follows:
      – request
      – use
      – release



    • E.g., Dining Philosophers problem:
              – Resource = forks
              – Process = philosopher




CS433-W4-10                                         Tarun Soni
Deadlocks

                                Deadlocks highly probable




Process resource trajectories
CS433-W4-11                                 Tarun Soni
Deadlocks

              Deadlocks not possible




CS433-W4-12               Tarun Soni
Deadlocks: Characterization

Deadlock can arise if four conditions hold simultaneously.


   • Mutual exclusion: only one process at a time can use a
     resource.
   • Hold and wait: a process holding at least one resource is
     waiting to acquire additional resources held by other
     processes.
   • No preemption: a resource can be released only
     voluntarily by the process holding it, after that process
     has completed its task.
   • Circular wait: there exists a set {P0, P1, …, P0} of waiting
     processes such that P0 is waiting for a resource that is
     held by P1, P1 is waiting for a resource that is held by P2,
     …, Pn–1 is waiting for a resource that is held by Pn, and P0
     is waiting for a resource that is held by P0.

CS433-W4-13                                            Tarun Soni
Resource allocation graphs: Notation


              A set of vertices V and a set of edges E.


                      V is partitioned into two types:
                      • P = {P1, P2, …, Pn}, the set consisting of all the
                         processes in the system.

                      • R = {R1, R2, …, Rm}, the set consisting of all
                        resource types in the system.
 Pi
                      • request edge – directed edge P1  Rj
              Rj

                      • assignment edge – directed edge Rj  Pi
   Pi
              Rj

CS433-W4-14                                                  Tarun Soni
Deadlocks: Requirements



  • Circular wait
        • a closed chain of processes exists, such that each
           process holds at least one resource needed by the next
           process in the chain




CS433-W4-15                                         Tarun Soni
 Deadlocks: Examples




• Space is available for allocation of 200K bytes, and the
  following sequence of events occur

                  P1                         P2
           ...                        ...
        Request 80K bytes;
           ...                     Request 70K bytes;
                                      ...
        Request 60K bytes;         Request 80K bytes;



• Deadlock occurs if both processes progress to their second
  request



 CS433-W4-16                                            Tarun Soni
    Deadlocks: Examples



    Consumable Resources can cause deadlocks too !

•    Created (produced) and destroyed (consumed) by a process
•    Interrupts, signals, messages, and information in I/O buffers
•    Deadlock may occur if a Receive message is blocking
•    May take a rare combination of events to cause deadlock



                      P1                             P2
               ...                           ...
             Receive(P2);
               ...                         Receive(P1);
                                             ...
              Send(P2);                     Send(P1);




    CS433-W4-17                                           Tarun Soni
Handling deadlocks




     • Deadlock prevention
        – disallow 1 of the 4 necessary conditions of deadlock
          occurrence
     • Deadlock avoidance
        – do not grant a resource request if this allocation might
          lead to deadlock
     • Deadlock detection
        – always grant resource request when possible. But
          periodically check for the presence of deadlock and then
          recover from it




CS433-W4-18                                          Tarun Soni
Deadlock prevention




• The OS is design in such a way as to exclude a priori the
  possibility of deadlock
• Indirect methods of deadlock prevention:
   – to disallow one of the 3 conditions
                      •   Mutual exclusion
                      •   Hold and wait
                      •   No preemption
                      •   Circular wait

• Direct methods of deadlock prevention:
   – to prevent the occurrence of circular wait


CS433-W4-19                                         Tarun Soni
Deadlock prevention


Deadlock prevention: Indirect methods..
Need to disallow at least one condition?
• Mutual Exclusion                  – process may be held up
   – cannot be disallowed             for a long time waiting for
   – ex: only 1 process at a          all its requests
     time can write to a file       – resources allocated to a
• Hold-and-Wait                       process may remain
                                      unused for a long time.
   – can be disallowed by             These resources could be
     requiring that a process         used by other processes
     request all its required
     resources at one time          – an application would need
                                      to be aware of all the
   – block the process until all      resources that will be
     requests can be granted          needed
     simultaneously


CS433-W4-20                                           Tarun Soni
 Deadlock prevention

                                Deadlock prevention: Indirect methods..
• No preemption                 Need to disallow at least one condition?
   – Can be prevented in several ways. E.g.,
           • 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.
           • Preempted resources are added to the list of resources for which the
             process is waiting.
           • Process will be restarted only when it can regain its old resources,
             as well as the new ones that it is requesting.
    – But whenever a process must release a resource who’s usage is
      in progress, the state of this resource must be saved for later
      resumption.
    – Hence: practical only when the state of a resource can be easily
      saved and restored later, such as the processor.


 CS433-W4-21                                                      Tarun Soni
Deadlock prevention


 Direct methods of prevention: Avoiding circular waits

  • A protocol to prevent circular wait:
     – define a strictly increasing linear ordering O() for resource
       types. Ex:
         • R1: tape drives: O(R1) = 2
         • R2: disk drives: O(R2) = 4
         • R3: printers: O(R3) = 7
     – A process initially request a number of instances of a
       resource type, say Ri. A single request must be issued to
       obtain several instances.
     – After that, the process can request instances for resource
       type Rj if and only if O(Rj) > O(Ri)



CS433-W4-22                                                Tarun Soni
Deadlock prevention


 Direct methods of prevention: Avoiding circular waits

  • Circular wait cannot hold under this protocol. Proof:
     – Processes {P0, P1..Pn} are involved in circular wait iff Pi is
        waiting for Ri which is held by Pi+1 and Pn is waiting for Rn
        held which is held by P0 (circular waiting)




CS433-W4-23                                               Tarun Soni
Deadlock prevention


 Direct methods of prevention: Avoiding circular waits

   – under this protocol, this means:
       • O(R0) < O(R1) < .. < O(Rn) < O(R0) impossible!
• This protocol prevents deadlock but will often deny resources
  unnecessarily (inefficient) because of the ordering imposed on
  the requests


 • 2 process/2 resource example:
 • P1 requests A; while holding B => O(A) > O(B) { from ordering }
 • P2 requests B; while holding A => O(B) > O(A)
        – This will not happen if you insist on the ordering



                        Generally deadlock prevention is hard and inefficient

CS433-W4-24                                                    Tarun Soni
Deadlock avoidance



    • We allow the 3 policy conditions but make judicious choices
      to assure that the deadlock point is never reached
    • Allows more concurrency than prevention
    • Two approaches:
       – do not start a process if it’s demand might lead to deadlock
              • Process initiation denial
       – do not grant an incremental resource request if this allocation
          might lead to deadlock
    • In both cases: maximum requirements of each resource
      must be stated in advance




CS433-W4-25                                               Tarun Soni
Deadlock avoidance

Resource types



 • Resources in a system are partitioned in resources types
 • Each resource type in a system exists with a certain amount.
   Let R(i) be the total amount of resource type i present in the
   system. Ex:
    – R(main memory) = 128 MB
    – R(disk drives) = 8
    – R(printers) = 5
 • The partition is system specific (ex: printers may be further
   partitioned...)




CS433-W4-26                                          Tarun Soni
 Deadlock avoidance                      Process initiation denial


• Let C(k,i) be the amount of resource type i claimed by
  process k.
• To be admitted in the system, process k must show C(k,i) for
  all resource types i
• C(k,i) is the maximum value of resource type i permitted for
  process k.
• Let U(i) be the total amount of resource type i unclaimed in
  the system:
    – U(i) = R(i) - S_k C(k,i)
• A new process n is admitted in the system only if C(n,i) <=
  U(i) for all resource type i
• This policy ensures that deadlock is always avoided since a
  process is admitted only if all its requests can always be
  satisfied (no matter what will be their order)

                  Sub-optimal but handles the worst case
 CS433-W4-27                                               Tarun Soni
Deadlock avoidance                               Resource allocation denial

Bankers algorithm

    • Processes are like customers wanting to borrow money
      (resources) to a bank...
    • A banker should not allocate cash when it cannot satisfy the
      needs of all its customers
    • At any time the state of the system is defined by the values
      of
              – R(i) : Max resources available of type i
              – C(j,i): Max resources needed by process j (of type i)
              – A(I,j): Resources currently allocated to process j (of type i)
    • Total resources available then becomes
       – V(i) = R(i) - S_k A(k,i)
    • and further needs can be defined as
       – N(j,i) = C(j,i) - A(j,i)

CS433-W4-28                                                         Tarun Soni
Deadlock avoidance                   Resource allocation denial

Bankers algorithm

  • To decide if a resource request made by a process should be
    granted, the banker’s algorithm test if granting the request
    will lead to a safe state:
     – If the resulting state is safe then grant request
     – Else do not grant the request


  • A state is safe iff there exist a sequence {P1..Pn} where each
    Pi is allocated all of its needed resources to be run to
    completion
     – ie: we can always run all the processes to completion
        from a safe state
  • The safety algorithm is the part that determines if a state is
    safe

CS433-W4-29                                           Tarun Soni
Deadlock avoidance                        Resource allocation denial

Bankers algorithm: the safety algorithm

  • Initialization:
     – all processes are said to be “unfinished”
     – set the work vector to the amount resources available:
        W(i) = V(i) for all i;


 • REPEAT: Find a unfinished process j such that N(j,i) <= W(i)
   for all i.
    – If no such j exists, goto EXIT
    – Else: “finish” this process and recover its resources:
       W(i) = W(i) + A(j,i) for all i. Then goto REPEAT
 • EXIT: If all processes have “finished” then this state is safe.
   Else it is unsafe.


CS433-W4-30                                                Tarun Soni
Deadlock avoidance                          Resource allocation denial

Bankers algorithm: the algorithm itself
    • Let Q(j,i) = amount of resource type i requested by process j.
    • To determine if this request should be granted we use the
      banker’s algorithm:
       – If Q(j,i) <= N(j,i) for all i then continue. Else raise error
         condition (claim exceeded).
       – If Q(j,i) <= V(i) for all i then continue. Else wait (resource
         not yet available)
       – Pretend that the request is granted and determine the
         new resource-allocation state:
              • V(i) = V(i) - Q(j,i) for all I /* available resources */
              • A(j,i) = A(j,i) + Q(j,i) for all I /* allocated resources */
              • N(j,i) = N(j,i) - Q(j,i) for all I /* needed resources */
          – If the resulting state is safe then allocate resource to
            process j. Else process j must wait for request Q(j,i) and
            restore old state.
CS433-W4-31                                                    Tarun Soni
Deadlock avoidance                       Resource allocation denial

Bankers algorithm: an example

    • We have 3 resources types with amount:
       – R(1) = 9, R(2) = 3, R(3) = 6
    • and have 4 processes with initial state:


               MaxReqd           Allocated          Available
               R1 R2 R3         R1 R2 R3         R1 R2 R3
          P1   3 2 2             1   0   0       1 1 2
          P2   6 1 3             5   1   1
          P3   3 1 4             2   1   1
          P4   4 2 2             0   0   2

        • Suppose that P2 is requesting Q = (1,0,1). Should this request be
          granted?

CS433-W4-32                                               Tarun Soni
Deadlock avoidance                        Resource allocation denial

Bankers algorithm: an example


    • The resulting state would be:

               MaxReqd           Allocated           Available
                R1   R2   R3    R1   R2   R3     R1 R2 R3
          P1    3    2     2    1    0     0     0 1 1
          P2    6    1     3    6    1     2
          P3    3    1     4    2    1     1
          P4    4    2     2    0    0     2


    • This state is safe with sequence {P2, P1, P3, P4}. After P2, we
      have W = (6,2,3) which enables the other processes to finish.
      Hence: request granted.


CS433-W4-33                                                Tarun Soni
Deadlock avoidance                       Resource allocation denial

Bankers algorithm: an example
    • However, if from the initial state, P1 request Q = (1,0,1). The
      resulting state would be:



               MaxReqd           Allocated           Available
              R1 R2 R3         R1 R2 R3          R1 R2 R3
         P1   3 2 2             2    0   1       0 1 1
         P2   6 1 3             5    1   1
         P3   3 1 4             2    1   1
         P4   4 2 2             0    0   2

     • Which is not a safe state since any process to finish would need
       an additional unit of R1. Request refused: P1 is blocked.


CS433-W4-34                                                Tarun Soni
Deadlock avoidance

Bankers algorithm: summary

 • A safe state cannot be deadlocked. But an unsafe state is not
   necessarily deadlocked.
    – Ex: P1 from the previous (unsafe) state could release
       temporarily a unit of R1 and R3 (returning to a safe state)
    – some process may need to wait unnecessarily
    – sub optimal use of resources
 • All deadlock avoidance algorithms assume that processes are
   independent: free from any synchronization constraint




CS433-W4-35                                              Tarun Soni
Deadlock detection




     • Resource access are granted to processes whenever
       possible. The OS needs:
        – an algorithm to check if deadlock is present
        – an algorithm to recover from deadlock
     • The deadlock check can be performed at every resource
       request
     • Such frequent checks consume CPU time




CS433-W4-36                                        Tarun Soni
Deadlock detection                                                 one algorithm


• use of previous notation:
     – resource-allocation matrices and vectors
• Marks each process not deadlocked. Initially all processes are
  unmarked. Then perform:
   – Mark each process j for which: A(j,i) = 0 for all resource type i.
     (since these are not deadlocked)
   – Initialize work vector: W(i) = V(i) for all i
   – REPEAT: Find a unmarked process j such that Q(j,i) <= W(i) for
     all i. Stop if such j does not exists. Goto end;
   – If such j exists:
              • mark process j /* This could be the next process run */
              • set W(i) = W(i) + A(j,i) for all i. /* process resources will be
                reclaims after process is done ! */
              • Goto REPEAT
     – At the end: each unmarked process is deadlocked
               Essentially finding sequence of processes for 1-step safe state !
CS433-W4-37                                                           Tarun Soni
Deadlock detection                                   one algorithm




 • Process j is not deadlocked when Q(j,i) <= W(i) for all i.
 • Then we are optimistic and assume that process j will
   require no more resources to complete its task
 • It will thus soon return all of its allocated resources. Thus:
   W(i) = W(i) + A(j,i) for all i
 • If this assumption is incorrect, a deadlock may occur later
 • This deadlock will be detected the next time the deadlock
   detection algorithm is invoked




CS433-W4-38                                            Tarun Soni
Deadlock detection

 Example
               Request                   Allocated               Available
              R1 R2 R3 R4 R5        R1 R2 R3 R4 R5           R1 R2 R3 R4 R5
   P1         0   1   0   0   1      1     0   1     1   0   0      0          0   0   1
   P2         0   0   1   0   1      1     1   0     0   0
   P3         0   0   0   0   1      0     0   0     1   0
   P4         1   0   1   0   1      0     0   0     0   0

    •    Mark P4 since it has no allocated resources
    •    Set W = (0,0,0,0,1)
    •    P3’s request <= W. So mark P3 and set W = W + (0,0,0,1,0) = (0,0,0,1,1)
    •    Algorithm terminates. P1 and P2 are deadlocked




CS433-W4-39                                                       Tarun Soni
Deadlock recovery



 • Needed when deadlock is detected. The following
   approaches are possible:
    – Abort all deadlocked processes (one of the most
      common solution adopted in OS!!)
    – Rollback each deadlocked process to some previously
      defined checkpoint and restart them (original deadlock
      may reoccur)
    – Successively abort deadlock processes until deadlock no
      longer exists (each time we need to invoke the deadlock
      detection algorithm)
    – Successively preempt some resources from processes
      and give them to other processes until deadlock no
      longer exists
        • a process that has a resource preempted must be
          rolled back prior to its acquisition
CS433-W4-40                                       Tarun Soni
Deadlock recovery


    • In which order should we choose to abort?
       – Priority of the process.
       – How long process has computed, and how much
          longer to completion.
       – Resources the process has used.
       – Resources process needs to complete.
       – How many processes will need to be terminated.
       – Is process interactive or batch?


      • Selecting a victim – minimize cost.
      • Starvation – same process may always be picked as
        victim, include number of rollback in cost factor.




CS433-W4-41                                            Tarun Soni
Deadlock: integrated approaches


• Combine the three basic approaches
   – prevention
   – avoidance
   – detection
• Use hierarchical classes of resources
   – Group resources into a number of different classes and
     order them. Ex:
      • Swappable space (secondary memory)
      • Process resources (I/O devices, files...)
      • Main memory...
   – Use prevention of circular wait to prevent deadlock
     between resource classes
   – Use the most appropriate approach for each class for
     deadlocks within each class

CS433-W4-42                                       Tarun Soni

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:7
posted:7/15/2011
language:English
pages:42