UNIX Foundations The Process and the Kernel 1

  • Slides: 87
Download presentation
UNIX Foundations The Process and the Kernel 1

UNIX Foundations The Process and the Kernel 1

Course Description u The Goals for this course u Understand UNIX u Understand Operating

Course Description u The Goals for this course u Understand UNIX u Understand Operating Systems u Prerequisites: u COSC 2 P 13 : Introduction to Operating Systems u COSC 2 P 91 : Procedural Programming

Course Description u An intensive study of computer operating system design u Multiprogramming u

Course Description u An intensive study of computer operating system design u Multiprogramming u Time-sharing u Real-time processing u Job and task control u Synchronization of concurrent processes and processors u Resource scheduling u Protection u Management of hierarchical storage.

How to study this course u Read and remember u Read the book, remember

How to study this course u Read and remember u Read the book, remember the concepts and commands u Think operating systems as natural administrative agents u Practice u Coding with UNIX, use and understand of UNIX commands and get the results

The Textbook Used u Uresh Vahalia, UNIX Internals: The New Frontiers, Prentice Hall, 1996

The Textbook Used u Uresh Vahalia, UNIX Internals: The New Frontiers, Prentice Hall, 1996 u Why we use this book? u UNIX is one of the most popular operating systems of the world. u If you understand UNIX, you can understand other operating systems.

References u William Stallings, Operating Systems, 5 th Ed. , Prentice Hall, 2005 u

References u William Stallings, Operating Systems, 5 th Ed. , Prentice Hall, 2005 u A. Tanenbaum, Modern Operating Systems, 2 nd ed. Prentice Hall 2001 u Kay A. Robbins and Steven Robbins, UNIX Systems Programming, Prentice Hall, 2003 u W. R. Stevens, Advanced Programming in the UNIX Environment, Addison Wesley, 1992

Summary of UNIX History XPG SVID POSIX Solaris Digital UNIX ULTRIX SVR 4 HP-UX

Summary of UNIX History XPG SVID POSIX Solaris Digital UNIX ULTRIX SVR 4 HP-UX 4. 3 BSD SCO UNIX SVR 3 XENIX Sun. OS AIX 4. 2 BSD SVR 2 4 BSD 3 BSD 7 4. 4 BSD UNIX

V 1. . . V 6 Summary of UNIX History Xenix BSD V 7

V 1. . . V 6 Summary of UNIX History Xenix BSD V 7 PWB Xenix 2 PWB 2 32 V SIII V 8 SYSV SCO 2 BSD. . . 2. 9 BSD 3 BSD 2. 10 BSD 4 BSD 2. 11 BSD V 10 4. 2 BSD 4. 3 BSD V. 2 Plan 9 Ultrix V. 3 SUNOS AIX V. 3. 2 SVR 4 8 4. 4 BSD Mach Solaris LINUX OSF 1

Flexibility u Traditional Kernel: file, scheduling, executable file formats 9

Flexibility u Traditional Kernel: file, scheduling, executable file formats 9

Modern UNIX Kernel 10

Modern UNIX Kernel 10

Assessment of UNIX u Advantages: - open software process, - well designed, small and

Assessment of UNIX u Advantages: - open software process, - well designed, small and simple kernel, - text files in system databases, - simple, uniform interface to I/O devices, - portability (written in C) 11

Assessment of UNIX u Disadvantages: - expansion of the more and more complex I/O

Assessment of UNIX u Disadvantages: - expansion of the more and more complex I/O library, - unfriendly user interface, - building block approach to tools, but not to the kernel, - too many versions and standards, - monolithic, unmodular and more complex kernel. 12

UNIX Architecture u Hardware is surrounded by the operating-system u Operating system is called

UNIX Architecture u Hardware is surrounded by the operating-system u Operating system is called the kernel u Comes with a number of user services and interfaces u shell u. C 13 compiler

UNIX Architecture Application Programs 14 Compiler Components Compiler Shell Editors, and Private User Programs

UNIX Architecture Application Programs 14 Compiler Components Compiler Shell Editors, and Private User Programs Kernel Hardware

User Interface The layers of a UNIX system. 15

User Interface The layers of a UNIX system. 15

UNIX Utility Programs A few of the more common UNIX utility programs required by

UNIX Utility Programs A few of the more common UNIX utility programs required by 16 POSIX

UNIX shell programming u cp src dest u head – 20 file u ls

UNIX shell programming u cp src dest u head – 20 file u ls *. c u sort <in >out u sort <in >temp; head – 30<temp; rm temp u sort <in | head – 30 u grep ter *. t | sort | head – 20 | tail – 5 >foo u sort <x | head & 17

Process u In UNIX u Process is an instance of a running program. u

Process u In UNIX u Process is an instance of a running program. u Lifetime: fork/vfork->exec->exit u Well-defined hierarchy: parent, child, init, u init process: the top process u swapper & pagedeamon u Orphans: the parent process is terminated. 18

19

19

Process Creation u Submission of a batch job u User logs on u Created

Process Creation u Submission of a batch job u User logs on u Created to provide a service such as printing u Spawned by an existing process 20

Process Termination u Batch job issues Halt instruction u User logs off u Process

Process Termination u Batch job issues Halt instruction u User logs off u Process executes a service request to terminate u Error and fault conditions 21

Reasons for Process Termination u Normal completion u Time limit exceeded u Memory unavailable

Reasons for Process Termination u Normal completion u Time limit exceeded u Memory unavailable u Bounds violation u Protection error u example write to read-only file u Arithmetic error u Time overrun u process waited longer than a specified maximum for an event 22

Reasons for Process Termination u I/O failure u Invalid instruction u happens when try

Reasons for Process Termination u I/O failure u Invalid instruction u happens when try to execute data u Privileged instruction u Data misuse u Operating system intervention u such u Parent as when deadlock occurs terminates so child processes terminate u Parent request 23

Process States u The Running state u The process that gets executed (single CPU)

Process States u The Running state u The process that gets executed (single CPU) u The Ready state u any u The process that is ready to be executed Blocked state u when a process cannot execute until some event occurs (ex: the completion of an I/O) 24

Process States u The New state u OS has performed the necessary actions to

Process States u The New state u OS has performed the necessary actions to create the process has created a process identifier u has created tables needed to manage the process u u but has not yet committed to execute the process (not yet admitted) u u The because resources are limited Exit state u Termination moves the process to this state u It is no longer eligible for execution u Tables and other info are temporarily preserved for auxiliary program 25

Five-State Process Model Dispatch New Admit Ready Release Running Time-out Event Occurs Blocked 26

Five-State Process Model Dispatch New Admit Ready Release Running Time-out Event Occurs Blocked 26 Event Wait Exit

Single Blocked Queue Ready Queue Dispatch Admit Release Processor Time-out Event Wait Event Occurs

Single Blocked Queue Ready Queue Dispatch Admit Release Processor Time-out Event Wait Event Occurs 27 Blocked Queue

Multiple Blocked Queues Ready Queue Dispatch Admit Release Processor Time-out Event 1 Wait Event

Multiple Blocked Queues Ready Queue Dispatch Admit Release Processor Time-out Event 1 Wait Event 1 Occurs Event 1 Queue Event 2 Wait Event 2 Occurs 28 Event 2 Queue

Suspended Processes u Processor is faster than I/O so all processes could be waiting

Suspended Processes u Processor is faster than I/O so all processes could be waiting for I/O u Swap these processes to disk to free up more memory u Blocked state becomes suspend state when swapped to disk u Two new states u Blocked, suspend u Ready, suspend 29

Process State Transition Diagram with Two Suspend States Ready Admit Ready, suspend Admit Suspend

Process State Transition Diagram with Two Suspend States Ready Admit Ready, suspend Admit Suspend Dispatch Activate Ready Suspend 30 Time out Event Occurs Blocked, suspend Running Activate Blocked Event Wait Exit

Processor State Information u Contents of processor registers u User-visible registers u Control and

Processor State Information u Contents of processor registers u User-visible registers u Control and status registers u Stack pointers u Program status word (PSW) u contains 31 status information

Process Control Information u Additional information needed by the operating system to control and

Process Control Information u Additional information needed by the operating system to control and coordinate the various active processes u scheduling and state information u data structuring u interprocess communication u process privileges u memory management u resource ownership and utilization 32

Process Creation u Assign a unique process identifier u Allocate space for the process

Process Creation u Assign a unique process identifier u Allocate space for the process u Initialize process control block u Set up appropriate linkages u Ex: add new process to linked list used for scheduling queue u Other u maintain 33 an accounting file

When to Switch a Process u Interrupts u Clock u process has executed for

When to Switch a Process u Interrupts u Clock u process has executed for the maximum allowable time slice u I/O u Memory fault u memory address is in virtual memory so it must be brought into main memory u Trap u error occurred u may cause process to be moved to Exit state u Supervisor u such 34 call as file open

Change of Process State u Save context of processor including program counter and other

Change of Process State u Save context of processor including program counter and other registers u Update the process control block with the new state and any accounting information u Move process control block to appropriate queue - ready, blocked u Select another process for execution u Update the process control block of the process selected u Update memory-management data structures u Restore context of the selected process 35

UNIX Process State u u u 36 Initial (idle) Ready to run Kernel/User running

UNIX Process State u u u 36 Initial (idle) Ready to run Kernel/User running Zombie Asleep for 4 BSD: stopped/suspend

Process states and state transitions 37

Process states and state transitions 37

Process Context u User address space: u code, u Control u data, stack, shared

Process Context u User address space: u code, u Control u data, stack, shared memory regions, information: u area, proc, kernel stack, ATM u Credentials: UID & GID u Environment variables: u inherited u Hardware u PC, 38 from the parent context(in PCB of u area): SP, PSW, MMR, FPU

User Credentials u Superuser: UID=0, GID=1 u Real IDs: log in, send signals u

User Credentials u Superuser: UID=0, GID=1 u Real IDs: log in, send signals u Effective IDs: file creation and access u exec: u u suid mode: that of the owner; sgid mode: that of the calling process setuid / setgid: u SV & BSD are different with these u u saved u 39 UID, saved GID in SV setgroup in BSD

The u Area u part of the process space, needed only when running. u

The u Area u part of the process space, needed only when running. u u u u u 40 PCB proc pointer UID s Arguments, results, error status from system calls Signal handlers and related information Info from the program header, text, data, stack size, MM info Open file descriptor Vnodes & controlling terminal pointers CPU usage statistics, profiling info, disk quotas, & resource limits Per-process kernel stack

u Process table The proc u Id u Location 41 of the kernel address

u Process table The proc u Id u Location 41 of the kernel address map for the u area u Current process state u Forward and backward pointers in scheduled queue u Sleep channel (7. 2. 3) u Scheduling priority and related (Chapter 5) u Signal handling info(Chapter 4). u MM info u Pointers to link active, free, zombie processes in lists u Flags u Pointers to keep structures on a hash queue by PID u Hierarchy info

Process ID A typical process hierarchy in Parent Process ID pointer to 4. 3

Process ID A typical process hierarchy in Parent Process ID pointer to 4. 3 BSD UNIX parent’s proc Pointer to the younger sibling 42 Pointer to the oldest child

Typical Functions of an Operating-System Kernel u Process Management u Process creation and termination

Typical Functions of an Operating-System Kernel u Process Management u Process creation and termination u Process scheduling and dispatching u Process switching u Process synchronization and support for interprocess communication u Management of process control blocks u Memory Management u Allocation of address space to processes u Swapping u Page 43 and segment management

Typical Functions of an Operating-System Kernel u I/O Management u Buffer management u Allocation

Typical Functions of an Operating-System Kernel u I/O Management u Buffer management u Allocation of I/O channels and devices to processes u Support Functions u Interrupt handling u Accounting u Monitoring 44

Operating System Control Structures u. An OS maintains the following tables for managing processes

Operating System Control Structures u. An OS maintains the following tables for managing processes and resources: u. Memory tables u. I/O tables u. File tables u. Process tables 45

Memory Tables u Allocation of main memory to processes u Allocation of secondary memory

Memory Tables u Allocation of main memory to processes u Allocation of secondary memory to processes u Protection attributes for access to shared memory regions u Information needed to manage virtual memory 46

I/O Tables u I/O device is available or assigned u Status of I/O operation

I/O Tables u I/O device is available or assigned u Status of I/O operation u Location in main memory being used as the source or destination of the I/O transfer 47

File Tables u Existence of files u Location on secondary memory u Current Status

File Tables u Existence of files u Location on secondary memory u Current Status u Attributes u Sometimes this information is maintained by a file-management system 48

Process Table u Process image consists of program, data, stack, and attributes u Attributes

Process Table u Process image consists of program, data, stack, and attributes u Attributes u process 49 control block

Process Control Block Process Identification u Unique numeric identifier u may be an index

Process Control Block Process Identification u Unique numeric identifier u may be an index into the primary process table u User identifier u who 50 is responsible for the job

Execution of the Operating System u Nonprocess Kernel u execute kernel outside of any

Execution of the Operating System u Nonprocess Kernel u execute kernel outside of any process u operating system code is executed as a separate entity that operates in privileged mode u Execution u operating Within User Processes system software within context of a user process u process executes in privileged mode when executing operating system code 51

Execution of the Operating System u Process-Based u major Operating System kernel functions are

Execution of the Operating System u Process-Based u major Operating System kernel functions are separate processes u a process is invoked by the operating system 52

The UNIX kernel u. A special program that runs directly on the hardware. u

The UNIX kernel u. A special program that runs directly on the hardware. u Implements the process model and services. u Resides on disk, in a file /vmunix or /unix. u Bootstrapping: loads the kernel. u Initializes the system and sets up the environment, remains in memory before shut down 53

UNIX Services u System call interface u Hardware exceptions u Divide by 0, overflowing

UNIX Services u System call interface u Hardware exceptions u Divide by 0, overflowing user stack u Interrupts u Devices u Swapper, 54 pagedaemon

The Kernel interacts with processes and devices 55 BACK

The Kernel interacts with processes and devices 55 BACK

Mode, Space & Context u By modes: some critical resources can be protected. u

Mode, Space & Context u By modes: some critical resources can be protected. u Kernel Mode: More privileged, kernel functions u User Mode: Less privileged, user functions u Virtual u VM Memory space u Address Translation Maps u Memory Management Unit 56

Kernel data u Current process & Context switch u One instance of the kernel

Kernel data u Current process & Context switch u One instance of the kernel u Global data structure u Pre-process objects u System call, Mode Switch u User area: info. about a process u Kernel stack: 57

Context u UNIX kernel is re-entrant: several processes may be involved in kernel activities

Context u UNIX kernel is re-entrant: several processes may be involved in kernel activities concurrently. u Execution context u Process context: u System context (Interrupt context): 58

Execution mode and Context 59

Execution mode and Context 59

Executing in Kernel Mode u 3 types of events: u Device interrupts u Exceptions

Executing in Kernel Mode u 3 types of events: u Device interrupts u Exceptions u Traps or software interrupts u Dispatch table u System context: interrupts u Process context: traps, exceptions & software interrupts 60

The System Call Interface syscall(): the starting point u in kernel mode, but in

The System Call Interface syscall(): the starting point u in kernel mode, but in process context. u Copy arguments , save hardware context on the kernel stack. u Use system call number to index dispatch vector u Return results in registers, restore hardware context, to user mode, control back to the library routine. u 61

UNIX Interrupt Handling u Interrupt handler(interrupt service routine): u runs in kernel mode and

UNIX Interrupt Handling u Interrupt handler(interrupt service routine): u runs in kernel mode and system context, u not permitted to block. u the time used to service an interrupt charged to the interrupted process u The clock interrupt handler charges the clock tick to the current process u ipl(interrupt priority level)- specified for each interrupt and saved in interrupt register of the processor status word u Interrupts are preemptive 62

Setting the interrupt priority in 4. 3 BSD and SVR 4 63

Setting the interrupt priority in 4. 3 BSD and SVR 4 63

Interrupt handling 64

Interrupt handling 64

Synchronization u UNIX is reentrant u UNIX is nonpreemptive, keeping the kernel states consistent.

Synchronization u UNIX is reentrant u UNIX is nonpreemptive, keeping the kernel states consistent. u Relinquish CPU voluntarily. 65

Blocking Operations u Blocks the process (make it sleep). u Lock: a single bit

Blocking Operations u Blocks the process (make it sleep). u Lock: a single bit flag u wanted(flag): u sleep(): u wake(): wake all the waiting processes. u upon waking up: check once again to make sure. 66

Algorithm for resource locking 67

Algorithm for resource locking 67

Blocking Interrupts u Blocking sections. u u u interrupts while accessing critical int x

Blocking Interrupts u Blocking sections. u u u interrupts while accessing critical int x = splbio(); /* raise ipl*/ modify disk buffer cache; splx(x); /*restore ipl*/ u Critical region: few & brief. u Blocked interrupts may access the critical region. u Different interrupts may have the same ipl u Blocking an interrupt may block others. 68

UNIX Process Implementation 69

UNIX Process Implementation 69

New Processes & Programs ufork: ucreates a new process. ureturns 0 to the child,

New Processes & Programs ufork: ucreates a new process. ureturns 0 to the child, PID to the parent u exec: u 70 begins to execute a new program

Using fork & exec if ((result = fork()==0){ u /* child code*/ u ……

Using fork & exec if ((result = fork()==0){ u /* child code*/ u …… u if (execve(“new program”), …)<0) u perror(“execve failed!”); u } else if (result<0) { u perror(“fork”); /*fork failed*/ u} u /*parent continures here*/ u 71

Shell creating a process 72 A highly simplified shell

Shell creating a process 72 A highly simplified shell

The ls Command Steps in executing the command ls typed to the shell 73

The ls Command Steps in executing the command ls typed to the shell 73

Process Creation u Almost u u u 74 u an exact clone of the

Process Creation u Almost u u u 74 u an exact clone of the parent. Reserve swap space for the child Allocate a new PID and proc structure for the child Initialize proc structure Allocate address translation map (ATM) Allocate u area and copy Update the u area to refer to the new ATM & Swap space Add the child to the set of processes sharing the text region of the program Duplicate the parent’s data and stack regions update ATM to refer to these new pages. Acquire references to shared resources inherited by the child Initialize the hardware context Make the child runnable and put it on a scheduler queue Arrange to return with 0 Return the PID to the parent

fork Optimization u It is wasteful to make an actual copy of the address

fork Optimization u It is wasteful to make an actual copy of the address space of the parent u Copy-on-write (SV) : only the pages that are modified must be copied u vfork (BSD): The parent loans the address space and blocks until the child returns to it. u u 75 dangerous! csh: exploits it.

Invoking a New Program u Process u Text: address space code u Initialized data:

Invoking a New Program u Process u Text: address space code u Initialized data: u Uninitialized data(bss): u Shared memory(SV): u Shared libraries: u Heap: dynamic space u User stack: space allocated by the kernel 76

exec System Call u u u u u 77 Parse & access Verify the

exec System Call u u u u u 77 Parse & access Verify the permission Read the header and check if valid executable If the file has SUID or SGID bits set in its mode, change the caller’s effective UID or GID to that of the owner Copy the arguments to exec and the env. variables into kernel. Allocate swap space for the data and stack region Set up the new address space. Copy the arguments and env. variables back onto the new user stack. Reset all signal handlers to default actions. Initialize the hardware context.

Process Termination (exit()) u u u 78 Turns off all signals. Closes all open

Process Termination (exit()) u u u 78 Turns off all signals. Closes all open files. Releases the text file and other resources such as the current directory. Writes to the accounting log. Saves resource usage statistics and exit status in the proc structure. Changes state to SZOMB, and puts the proc on the zombie process list. Makes the init process inherit any live children of the exiting process. Releases the address space, u area, ATM, and swap space. Notifies the parent by sending it a SIGCHLD signal. Wakes up the parent if it is asleep. Calls swtch() to schedule a new process to run.

Awaiting Process Termination u u 79 wait(stat_loc); /* SV, BSD & POSIX*/ wait 3(statusp,

Awaiting Process Termination u u 79 wait(stat_loc); /* SV, BSD & POSIX*/ wait 3(statusp, options, rusagep); /*BSD*/ waitpid(pid, stat_loc, options); /*POSIX*/ waitid(idtype, id, infop, options); /*SVR 4*/

Zombie Processes u after exit(), process holds only proc structure and is in zombie

Zombie Processes u after exit(), process holds only proc structure and is in zombie state until cleaned completely. u wait() (issued by the parent or the init process)frees the proc structure and completes process exit, u If the child dies before the parent which does not wait for it, the proc is not released until the system is rebooted. u Parent can specify that it will not wait for its children 80

LINUX u u u 81 Modular structure – collection of modules, some of them

LINUX u u u 81 Modular structure – collection of modules, some of them loadable and unloadable on demand, Module – object file whose code be linked and unlinked from the kernel at runtime, executed in kernel mode on behalf of the current process Loadable module characteristic – Dynamic linking, -- Stackable modules – may serve as libraries when they are referenced by client modules higher up in the hierarchy, and as clients when they reference modules further down the hierarchy.

82

82

Linux components u u u 83 At user level – tasks (specific to Linux

Linux components u u u 83 At user level – tasks (specific to Linux – combine features of processes and threads); At kernel level – interacting collection of components; Hardware components – in this case IA-64 Intel Itanium architecture

84

84

u State Linux Task Data Structure u Scheduling information u Identifiers u Interprocess communication

u State Linux Task Data Structure u Scheduling information u Identifiers u Interprocess communication u Links u Times and timers u File system u Address space u Processor-specific context 85

Linux States of a Process/Thread u Running u Interruptable u Uninterruptable u Stopped u

Linux States of a Process/Thread u Running u Interruptable u Uninterruptable u Stopped u Zombie 86

87

87