Operating Systems
Introduction, Processes, Threads
Daniel Gruss October 2, 2020 Table of contents www.tugraz.at
1. Basics
2. History
3. Booting
4. Process and Thread Fundamentals
5. Context Switches
6. Process and Thread Organization
1
Basics What is an Operating System www.tugraz.at
2 What is an Operating System www.tugraz.at
3 What is an Operating System www.tugraz.at
4 What is an Operating System www.tugraz.at
Run on all sorts of devices: Servers, Desktops, Notebooks Tablets, Smartphones Routers, Switches, Displays Door Locks, Washing Machines, Toasters Cars, Airplanes .... We focus on general purpose operating systems
5 Operating System Roles www.tugraz.at
Referee Illusionist Glue
6 Operating System Roles: Referee www.tugraz.at
Referee
Manage resource allocation among users and applications Isolation of different users, applications from each other Isolation of applications and operating system Communication between users, application
7 Operating System Roles: Illusionist www.tugraz.at
Illusionist
Abstraction of hardware and other things Makes application design simpler Each application appears to have the entire machine to itself Illusion of Infinite number of processors (near) infinite amount of memory reliable storage reliable network transport
8 Operating System Roles: Glue www.tugraz.at
Glue
Libraries, user interface widgets, . . .
9 Example: File Systems www.tugraz.at
Referee Prevent users from accessing each other’s files without permission Even after a file is deleted and its space re-used Illusionist Files can grow (nearly) arbitrarily large Files persist even when the machine crashes in the middle of a save
10 Example: File Systems www.tugraz.at
Glue Nam ed directories, printf, . . .
11 OS Design Patterns I www.tugraz.at
OS challenges are not unique - apply to many different computing domains many complex software systems have multiple users run programs written by third-party developers need to coordinate simultaneous activities
12 OS Design Patterns II www.tugraz.at
Challenges:
resource allocation fault isolation communication abstraction how to provide a set of common services
13 Reliability and Availability Security Portability Performance Adoption
Design Criteria for OS www.tugraz.at
Design Criteria for Operating Systems
14 Security Portability Performance Adoption
Design Criteria for OS www.tugraz.at
Design Criteria for Operating Systems
Reliability and Availability
14 Portability Performance Adoption
Design Criteria for OS www.tugraz.at
Design Criteria for Operating Systems
Reliability and Availability Security
14 Performance Adoption
Design Criteria for OS www.tugraz.at
Design Criteria for Operating Systems
Reliability and Availability Security Portability
14 Adoption
Design Criteria for OS www.tugraz.at
Design Criteria for Operating Systems
Reliability and Availability Security Portability Performance
14 Design Criteria for OS www.tugraz.at
Design Criteria for Operating Systems
Reliability and Availability Security Portability Performance Adoption
14 It does, what it is designed to do
Application failures can be “ok” - OS provides fault isolation and clean restart after errors OS errors are bad, real bad...
Reliability and Availability www.tugraz.at
Reliability
15 Application failures can be “ok” - OS provides fault isolation and clean restart after errors OS errors are bad, real bad...
Reliability and Availability www.tugraz.at
Reliability
It does, what it is designed to do
15 Reliability and Availability www.tugraz.at
Reliability
It does, what it is designed to do
Application failures can be “ok” - OS provides fault isolation and clean restart after errors OS errors are bad, real bad...
15 hostile environment (viruses, malicious code take control) testing helps - but is much more difficult extremely rare corner cases can occur regularly
Reliability www.tugraz.at
Making an OS reliable is challenging
16 Reliability www.tugraz.at
Making an OS reliable is challenging
hostile environment (viruses, malicious code take control) testing helps - but is much more difficult extremely rare corner cases can occur regularly
16 Percentage of time the system is usable
Buggy OS that loses users work is unreliable AND unavailable Buggy OS that never loses users work is reliable BUT unavailable Buggy OS that has been subverted but continues to run (and e.g. logs keystrokes and sends them of) is available BUT unreliable
Availability www.tugraz.at
Availability
17 Buggy OS that loses users work is unreliable AND unavailable Buggy OS that never loses users work is reliable BUT unavailable Buggy OS that has been subverted but continues to run (and e.g. logs keystrokes and sends them of) is available BUT unreliable
Availability www.tugraz.at
Availability
Percentage of time the system is usable
17 Availability www.tugraz.at
Availability
Percentage of time the system is usable
Buggy OS that loses users work is unreliable AND unavailable Buggy OS that never loses users work is reliable BUT unavailable Buggy OS that has been subverted but continues to run (and e.g. logs keystrokes and sends them of) is available BUT unreliable
17 Reliability and Availability www.tugraz.at
Reliablity and Availability are desireable Two factors: MTTF: mean time to failure MTTR: mean time to repair
18 Security www.tugraz.at
Security: computers operation cannot be compromised by a malicious attacker Privacy: data stored on the computer is only accessible to authorized users
19 Security www.tugraz.at
Unfortunately: no useful computer is perfectly secure! OS is a complex piece of software complex software has bugs bugs can be exploited HW may be tampered with Sysadmin may be untrustworthy SW-developer may be untrustworthy (backdoors)
20 Security www.tugraz.at
OS should be designed to minimize its vulnerability to attack Fault isolation But: interaction between users and programs required
21 Security Policy www.tugraz.at
Security Policy defines
who can access what data who can perform what operations
22 Policies and Enforcement may possess vulnerabilities...
Enforcement www.tugraz.at
Enforcment
ensures that policy is followed
23 Enforcement www.tugraz.at
Enforcment
ensures that policy is followed
Policies and Enforcement may possess vulnerabilities...
23 does not change as the hardware changes
Portability is an important design criteria of the OS don’t want to reimplement everything when HW changes e.g. iOS was derived from the MacOS X code base
Portability www.tugraz.at
OS provides an abstraction of underlying HW
24 Portability is an important design criteria of the OS don’t want to reimplement everything when HW changes e.g. iOS was derived from the MacOS X code base
Portability www.tugraz.at
OS provides an abstraction of underlying HW
does not change as the hardware changes
24 don’t want to reimplement everything when HW changes e.g. iOS was derived from the MacOS X code base
Portability www.tugraz.at
OS provides an abstraction of underlying HW
does not change as the hardware changes
Portability is an important design criteria of the OS
24 e.g. iOS was derived from the MacOS X code base
Portability www.tugraz.at
OS provides an abstraction of underlying HW
does not change as the hardware changes
Portability is an important design criteria of the OS don’t want to reimplement everything when HW changes
24 Portability www.tugraz.at
OS provides an abstraction of underlying HW
does not change as the hardware changes
Portability is an important design criteria of the OS don’t want to reimplement everything when HW changes e.g. iOS was derived from the MacOS X code base
24 Windows 10 based on Windows NT (started 1988) MS/DOS introduced 1981 - phased out ˜2000 First Linux release 1991
Portability www.tugraz.at
Lifetime of successful operating systems measured in decades
25 MS/DOS introduced 1981 - phased out ˜2000 First Linux release 1991
Portability www.tugraz.at
Lifetime of successful operating systems measured in decades Windows 10 based on Windows NT (started 1988)
25 First Linux release 1991
Portability www.tugraz.at
Lifetime of successful operating systems measured in decades Windows 10 based on Windows NT (started 1988) MS/DOS introduced 1981 - phased out ˜2000
25 Portability www.tugraz.at
Lifetime of successful operating systems measured in decades Windows 10 based on Windows NT (started 1988) MS/DOS introduced 1981 - phased out ˜2000 First Linux release 1991
25 Portability www.tugraz.at
An OS must be designed to support applications that have not yet been written and hardware that has not been developed Simple, standard way for applications to interact with OS API memory access model instructions that can be executed
26 Example for a highly portable OS?
Hardware Abstraction Layer www.tugraz.at
in older/more theoretical literature sometimes “Abstract Virtual Machine” provides fixed point across which both application and hardware can develop independently
27 Hardware Abstraction Layer www.tugraz.at
in older/more theoretical literature sometimes “Abstract Virtual Machine” provides fixed point across which both application and hardware can develop independently
Example for a highly portable OS?
27 Performance www.tugraz.at
Performance associated with application - OS design can affect the percieved performance OS decides when app can run how much memory it gets etc. Performance can be measured in different ways Overhead / Efficiency Added (lack of) cost of implementing an abstraction presented to applications
28 Performance aspects www.tugraz.at
Fairness: resource allocation can impact performance
divide resources equally - or treat some differently? How to decide which task gets priority?
29 Performance aspects www.tugraz.at
Response Time
(delay) how long does it take for a single task to run from the time it starts to the time it completes (move the mouse . . . mouse pointer reflects movement)
Throughput
Rate at which system completes tasks
30 Performance aspects www.tugraz.at
Predictability
whether systems response time is consistent over time can be more important than average performance
31 Network Effect
value of technology does not depend only on its intrinsic capabilities but on the number of people adopting it
Adoption www.tugraz.at
Success of an OS depends on adoption SWEB may be the best - but if no application providers support it, it remains doomed for the this exercise
32 Adoption www.tugraz.at
Success of an OS depends on adoption SWEB may be the best - but if no application providers support it, it remains doomed for the this exercise
Network Effect
value of technology does not depend only on its intrinsic capabilities but on the number of people adopting it
32 Adoption www.tugraz.at
App and HW-vendors focus on OS with most users users favor OS with best applications or cheapest hardware Goal for OS: take advantage of network effect make it easy to accommodate new hardware make it easy for applications to be ported across different versions of the OS
33 Windows, MacOS: proprietary Linux: open All are widely used
Adoption www.tugraz.at
API and OS source code - open? proprietary?
34 All are widely used
Adoption www.tugraz.at
API and OS source code - open? proprietary? Windows, MacOS: proprietary Linux: open
34 Adoption www.tugraz.at
API and OS source code - open? proprietary? Windows, MacOS: proprietary Linux: open All are widely used
34 Design Criteria for OS www.tugraz.at
Design Criteria for Operating Systems
Reliability and Availability Security Portability Performance Adoption
35 Balance between these goals www.tugraz.at
Improving portability can make the system less reliable and less secure e.g. preserving legacy interfaces Improving performance may add complexity and hurt reliability
36 Tradeoff www.tugraz.at
Research OS in the 1980’s: use type-safe language to reduce programmer errors For speed: frequently used routines implemented in assembly Optimized sequence of instructions - but which would sometimes break if the OS exceeded a specific size Initially nowhere near this limitation After a few years in production: random crashes occured Problem search took weeks .... Was it worth it?
37 History History www.tugraz.at
The first computers were so called “mainframes” that had no operating systems.
38 Mainframes www.tugraz.at
39 assemblers, compilers, debugging tools standard routines for input and output buffers to “spool” printer and tape output utilities designed to load sequence (or “batch”) of programs into memory automate some of the reconfiguration performed by human operators
later: collection of compatible utility programs (Multics [2])
Operating System www.tugraz.at
At that time: did not exist
40 assemblers, compilers, debugging tools standard routines for input and output buffers to “spool” printer and tape output utilities designed to load sequence (or “batch”) of programs into memory automate some of the reconfiguration performed by human operators
Operating System www.tugraz.at
At that time: did not exist later: collection of compatible utility programs (Multics [2])
40 standard routines for input and output buffers to “spool” printer and tape output utilities designed to load sequence (or “batch”) of programs into memory automate some of the reconfiguration performed by human operators
Operating System www.tugraz.at
At that time: did not exist later: collection of compatible utility programs (Multics [2]) assemblers, compilers, debugging tools
40 buffers to “spool” printer and tape output utilities designed to load sequence (or “batch”) of programs into memory automate some of the reconfiguration performed by human operators
Operating System www.tugraz.at
At that time: did not exist later: collection of compatible utility programs (Multics [2]) assemblers, compilers, debugging tools standard routines for input and output
40 utilities designed to load sequence (or “batch”) of programs into memory automate some of the reconfiguration performed by human operators
Operating System www.tugraz.at
At that time: did not exist later: collection of compatible utility programs (Multics [2]) assemblers, compilers, debugging tools standard routines for input and output buffers to “spool” printer and tape output
40 automate some of the reconfiguration performed by human operators
Operating System www.tugraz.at
At that time: did not exist later: collection of compatible utility programs (Multics [2]) assemblers, compilers, debugging tools standard routines for input and output buffers to “spool” printer and tape output utilities designed to load sequence (or “batch”) of programs into memory
40 Operating System www.tugraz.at
At that time: did not exist later: collection of compatible utility programs (Multics [2]) assemblers, compilers, debugging tools standard routines for input and output buffers to “spool” printer and tape output utilities designed to load sequence (or “batch”) of programs into memory automate some of the reconfiguration performed by human operators
40 (no PCs at that time) thought to be used by many users concurrently
goal: support powerful central computers
MULTICS www.tugraz.at
one of the first endeavors towards a “real operating system”
41 (no PCs at that time) thought to be used by many users concurrently
MULTICS www.tugraz.at
one of the first endeavors towards a “real operating system” goal: support powerful central computers
41 thought to be used by many users concurrently
MULTICS www.tugraz.at
one of the first endeavors towards a “real operating system” goal: support powerful central computers (no PCs at that time)
41 MULTICS www.tugraz.at
one of the first endeavors towards a “real operating system” goal: support powerful central computers (no PCs at that time) thought to be used by many users concurrently
41 memory disk and CPU between hundreds of users
responsible for sharing
Important: Protection against faults and tampering
Requirements www.tugraz.at
required reliable system software
42 memory disk and CPU between hundreds of users Important: Protection against faults and tampering
Requirements www.tugraz.at
required reliable system software responsible for sharing
42 disk and CPU between hundreds of users Important: Protection against faults and tampering
Requirements www.tugraz.at
required reliable system software responsible for sharing memory
42 CPU between hundreds of users Important: Protection against faults and tampering
Requirements www.tugraz.at
required reliable system software responsible for sharing memory disk and
42 between hundreds of users Important: Protection against faults and tampering
Requirements www.tugraz.at
required reliable system software responsible for sharing memory disk and CPU
42 Important: Protection against faults and tampering
Requirements www.tugraz.at
required reliable system software responsible for sharing memory disk and CPU between hundreds of users
42 Requirements www.tugraz.at
required reliable system software responsible for sharing memory disk and CPU between hundreds of users Important: Protection against faults and tampering
42 hierarchical file systems multiple processor support shared memory modularized structure written in a high level programming language
Results www.tugraz.at
new concepts still valid today in modern operating systems
paged and segmented memory
43 multiple processor support shared memory modularized structure written in a high level programming language
Results www.tugraz.at
new concepts still valid today in modern operating systems
paged and segmented memory hierarchical file systems
43 shared memory modularized structure written in a high level programming language
Results www.tugraz.at
new concepts still valid today in modern operating systems
paged and segmented memory hierarchical file systems multiple processor support
43 modularized structure written in a high level programming language
Results www.tugraz.at
new concepts still valid today in modern operating systems
paged and segmented memory hierarchical file systems multiple processor support shared memory
43 written in a high level programming language
Results www.tugraz.at
new concepts still valid today in modern operating systems
paged and segmented memory hierarchical file systems multiple processor support shared memory modularized structure
43 Results www.tugraz.at
new concepts still valid today in modern operating systems
paged and segmented memory hierarchical file systems multiple processor support shared memory modularized structure written in a high level programming language
43 Ken Thompson and Dennis Ritchie started working on an OS for microcomputers: UNIX by programmers - for programmers originally in assembly language rewritten in C portable operating system!
UNIX et al. www.tugraz.at
Multics never gained critical mass in the market place
44 by programmers - for programmers originally in assembly language rewritten in C portable operating system!
UNIX et al. www.tugraz.at
Multics never gained critical mass in the market place Ken Thompson and Dennis Ritchie started working on an OS for microcomputers: UNIX
44 originally in assembly language rewritten in C portable operating system!
UNIX et al. www.tugraz.at
Multics never gained critical mass in the market place Ken Thompson and Dennis Ritchie started working on an OS for microcomputers: UNIX by programmers - for programmers
44 rewritten in C portable operating system!
UNIX et al. www.tugraz.at
Multics never gained critical mass in the market place Ken Thompson and Dennis Ritchie started working on an OS for microcomputers: UNIX by programmers - for programmers originally in assembly language
44 portable operating system!
UNIX et al. www.tugraz.at
Multics never gained critical mass in the market place Ken Thompson and Dennis Ritchie started working on an OS for microcomputers: UNIX by programmers - for programmers originally in assembly language rewritten in C
44 UNIX et al. www.tugraz.at
Multics never gained critical mass in the market place Ken Thompson and Dennis Ritchie started working on an OS for microcomputers: UNIX by programmers - for programmers originally in assembly language rewritten in C portable operating system!
44 IBM’s OS/360 www.tugraz.at
Pugh et al. [5]
concept that the OS keeps track of all of the system resources that are used, including program and data space allocation in main memory file space in secondary storage file locking during update
45 Evolution of Operating Systems www.tugraz.at
Phase Idea Open shop operating systems Batch processing tape batching, first-in/first -out scheduling Multiprogramming processor multiplexing, atomic operations, demand paging, I/O spooling, priority scheduling, remote job entry Timesharing simultaneous user interactions, on-line file systems Concurrent programming hierarchical systems, extensible kernels, parallel programming Personal Computing graphical user interface Distributed Systems remote servers
46 operated manually Programmers were alloted time to use the machine. How did this work?
Open Shop www.tugraz.at
1954
computers had no operating systems
47 Programmers were alloted time to use the machine. How did this work?
Open Shop www.tugraz.at
1954
computers had no operating systems operated manually
47 Open Shop www.tugraz.at
1954
computers had no operating systems operated manually Programmers were alloted time to use the machine. How did this work?
47 Open Shop www.tugraz.at
Each user was allocated a minimum 15-minute slot, of which time he usually spent 10 minutes in setting up the equipment to do his computation... By the time he got his computation going, he may have had only 5 minutes or less of actual computation completed - wasting two thirds of his time slot. (George Ryckman on operating IBM’s first computer, the IBM 701 [3])
48 punched cards to code programs line printers produce output
remove programmers from the computer room (closed shop).
Batch processing www.tugraz.at
Most efficient way to reduce idle computer time:
49 punched cards to code programs line printers produce output
Batch processing www.tugraz.at
Most efficient way to reduce idle computer time: remove programmers from the computer room (closed shop).
49 line printers produce output
Batch processing www.tugraz.at
Most efficient way to reduce idle computer time: remove programmers from the computer room (closed shop). punched cards to code programs
49 Batch processing www.tugraz.at
Most efficient way to reduce idle computer time: remove programmers from the computer room (closed shop). punched cards to code programs line printers produce output
49 8.192 words of fixed store 1.025 words of subsidiary store 98.304 words on drum 8 magnetic tape mechanisms 3 paper tape readers 3 paper tape punches 2 teleprinters 1 line printer 1 card reader 1 card punch
Atlas www.tugraz.at
One of the early batch processing Operating Systems (then called supervisor) running on “The Atlas Supervisor” [4]
16.284 words of core store
50 1.025 words of subsidiary store 98.304 words on drum 8 magnetic tape mechanisms 3 paper tape readers 3 paper tape punches 2 teleprinters 1 line printer 1 card reader 1 card punch
Atlas www.tugraz.at
One of the early batch processing Operating Systems (then called supervisor) running on “The Atlas Supervisor” [4]
16.284 words of core store 8.192 words of fixed store
50 98.304 words on drum 8 magnetic tape mechanisms 3 paper tape readers 3 paper tape punches 2 teleprinters 1 line printer 1 card reader 1 card punch
Atlas www.tugraz.at
One of the early batch processing Operating Systems (then called supervisor) running on “The Atlas Supervisor” [4]
16.284 words of core store 8.192 words of fixed store 1.025 words of subsidiary store
50 8 magnetic tape mechanisms 3 paper tape readers 3 paper tape punches 2 teleprinters 1 line printer 1 card reader 1 card punch
Atlas www.tugraz.at
One of the early batch processing Operating Systems (then called supervisor) running on “The Atlas Supervisor” [4]
16.284 words of core store 8.192 words of fixed store 1.025 words of subsidiary store 98.304 words on drum
50 3 paper tape readers 3 paper tape punches 2 teleprinters 1 line printer 1 card reader 1 card punch
Atlas www.tugraz.at
One of the early batch processing Operating Systems (then called supervisor) running on “The Atlas Supervisor” [4]
16.284 words of core store 8.192 words of fixed store 1.025 words of subsidiary store 98.304 words on drum 8 magnetic tape mechanisms
50 3 paper tape punches 2 teleprinters 1 line printer 1 card reader 1 card punch
Atlas www.tugraz.at
One of the early batch processing Operating Systems (then called supervisor) running on “The Atlas Supervisor” [4]
16.284 words of core store 8.192 words of fixed store 1.025 words of subsidiary store 98.304 words on drum 8 magnetic tape mechanisms 3 paper tape readers
50 2 teleprinters 1 line printer 1 card reader 1 card punch
Atlas www.tugraz.at
One of the early batch processing Operating Systems (then called supervisor) running on “The Atlas Supervisor” [4]
16.284 words of core store 8.192 words of fixed store 1.025 words of subsidiary store 98.304 words on drum 8 magnetic tape mechanisms 3 paper tape readers 3 paper tape punches
50 1 line printer 1 card reader 1 card punch
Atlas www.tugraz.at
One of the early batch processing Operating Systems (then called supervisor) running on “The Atlas Supervisor” [4]
16.284 words of core store 8.192 words of fixed store 1.025 words of subsidiary store 98.304 words on drum 8 magnetic tape mechanisms 3 paper tape readers 3 paper tape punches 2 teleprinters
50 1 card reader 1 card punch
Atlas www.tugraz.at
One of the early batch processing Operating Systems (then called supervisor) running on “The Atlas Supervisor” [4]
16.284 words of core store 8.192 words of fixed store 1.025 words of subsidiary store 98.304 words on drum 8 magnetic tape mechanisms 3 paper tape readers 3 paper tape punches 2 teleprinters 1 line printer
50 1 card punch
Atlas www.tugraz.at
One of the early batch processing Operating Systems (then called supervisor) running on “The Atlas Supervisor” [4]
16.284 words of core store 8.192 words of fixed store 1.025 words of subsidiary store 98.304 words on drum 8 magnetic tape mechanisms 3 paper tape readers 3 paper tape punches 2 teleprinters 1 line printer 1 card reader
50 Atlas www.tugraz.at
One of the early batch processing Operating Systems (then called supervisor) running on “The Atlas Supervisor” [4]
16.284 words of core store 8.192 words of fixed store 1.025 words of subsidiary store 98.304 words on drum 8 magnetic tape mechanisms 3 paper tape readers 3 paper tape punches 2 teleprinters 1 line printer 1 card reader 1 card punch
50 too much valuable time lost between two jobs Load multiple programs concurrently switch between programs requires protection mechanisms enhanced by virtual memory
Multiprogramming www.tugraz.at
Drawback of Batch Processing: one job at a time
51 Load multiple programs concurrently switch between programs requires protection mechanisms enhanced by virtual memory
Multiprogramming www.tugraz.at
Drawback of Batch Processing: one job at a time too much valuable time lost between two jobs
51 switch between programs requires protection mechanisms enhanced by virtual memory
Multiprogramming www.tugraz.at
Drawback of Batch Processing: one job at a time too much valuable time lost between two jobs Load multiple programs concurrently
51 requires protection mechanisms enhanced by virtual memory
Multiprogramming www.tugraz.at
Drawback of Batch Processing: one job at a time too much valuable time lost between two jobs Load multiple programs concurrently switch between programs
51 enhanced by virtual memory
Multiprogramming www.tugraz.at
Drawback of Batch Processing: one job at a time too much valuable time lost between two jobs Load multiple programs concurrently switch between programs requires protection mechanisms
51 Multiprogramming www.tugraz.at
Drawback of Batch Processing: one job at a time too much valuable time lost between two jobs Load multiple programs concurrently switch between programs requires protection mechanisms enhanced by virtual memory
51 use computer via terminals interaction with computer
submit a job multiple jobs run in parallel receive results Timesharing
Timesharing www.tugraz.at
Multiprogramming still “Batch-like”
52 use computer via terminals interaction with computer
multiple jobs run in parallel receive results Timesharing
Timesharing www.tugraz.at
Multiprogramming still “Batch-like” submit a job
52 use computer via terminals interaction with computer
receive results Timesharing
Timesharing www.tugraz.at
Multiprogramming still “Batch-like” submit a job multiple jobs run in parallel
52 use computer via terminals interaction with computer
Timesharing
Timesharing www.tugraz.at
Multiprogramming still “Batch-like” submit a job multiple jobs run in parallel receive results
52 use computer via terminals interaction with computer
Timesharing www.tugraz.at
Multiprogramming still “Batch-like” submit a job multiple jobs run in parallel receive results Timesharing
52 interaction with computer
Timesharing www.tugraz.at
Multiprogramming still “Batch-like” submit a job multiple jobs run in parallel receive results Timesharing use computer via terminals
52 Timesharing www.tugraz.at
Multiprogramming still “Batch-like” submit a job multiple jobs run in parallel receive results Timesharing use computer via terminals interaction with computer
52 Scheduling Swapping File-systems Protection
Timesharing www.tugraz.at
Requires
53 Swapping File-systems Protection
Timesharing www.tugraz.at
Requires Scheduling
53 File-systems Protection
Timesharing www.tugraz.at
Requires Scheduling Swapping
53 Protection
Timesharing www.tugraz.at
Requires Scheduling Swapping File-systems
53 Timesharing www.tugraz.at
Requires Scheduling Swapping File-systems Protection
53 Concurrent Programming www.tugraz.at
Fundamental Problems were not understood properly Deadlocks Race Conditions Led to the discovery of fundamental principles of concurrent programming
54 THE Operating System www.tugraz.at
By Edsger E. Dijkstra (1968) Spooling System with paper tape in/output demand paging between a 512K word drum and 32K word memory 5 user processes, 10 I/O processes (one for each device) Used semaphores for synchronization
55 THE www.tugraz.at
Claim by Dijkstra [1] We have found that it is possible to design a refined multiprogramming system in such a way that it its logical soundness can be proved a priori and its implementation can admit exhaustive testing. The only errors that showed up during testing were trivial coding errors. The resulting system is guaranteed to be flawless.
56 Personal Computing www.tugraz.at
1968: First devices named “personal computer” (actually a calculator)
57 PCs www.tugraz.at
1973: Xerox Alto, first computer with mouse, desktop, and GUI
58 PC Operating Systems www.tugraz.at
Different requirements: only one user CP/M, DOS, Apple-DOS Windows OS-2, Windows-XP, OS-X, Linux....
59 Distributed Systems www.tugraz.at
By 1980 all major OS concepts discovered distributed systems developed communication via RPC - remote procedure call a few made it to commercial systems now, the “Internet” as a huge distributed system...
60
Booting actually only 4 bit, but shifted by 16 bits to the left → 4 bits (base/prefix) + 16 bits (address/offset) = 20 bit address
Address space: 1 MB How is that possible? CS register has a 20-bit base address
Starting in Real Mode www.tugraz.at
16 bit mode
61 actually only 4 bit, but shifted by 16 bits to the left → 4 bits (base/prefix) + 16 bits (address/offset) = 20 bit address
How is that possible? CS register has a 20-bit base address
Starting in Real Mode www.tugraz.at
16 bit mode Address space: 1 MB
61 actually only 4 bit, but shifted by 16 bits to the left → 4 bits (base/prefix) + 16 bits (address/offset) = 20 bit address
CS register has a 20-bit base address
Starting in Real Mode www.tugraz.at
16 bit mode Address space: 1 MB How is that possible?
61 actually only 4 bit, but shifted by 16 bits to the left → 4 bits (base/prefix) + 16 bits (address/offset) = 20 bit address
Starting in Real Mode www.tugraz.at
16 bit mode Address space: 1 MB How is that possible? CS register has a 20-bit base address
61 → 4 bits (base/prefix) + 16 bits (address/offset) = 20 bit address
Starting in Real Mode www.tugraz.at
16 bit mode Address space: 1 MB How is that possible? CS register has a 20-bit base address actually only 4 bit, but shifted by 16 bits to the left
61 Starting in Real Mode www.tugraz.at
16 bit mode Address space: 1 MB How is that possible? CS register has a 20-bit base address actually only 4 bit, but shifted by 16 bits to the left → 4 bits (base/prefix) + 16 bits (address/offset) = 20 bit address
61 Booting x86 Intel www.tugraz.at
62 CS register also has a 32-bit base address (initialized to 0xFFFF0000)
physical address space 6= RAM directly mapped
How is that possible?
What if I have < 4 GB RAM?
Booting in Real Mode www.tugraz.at
Address: 0xFFFFFFF0
63 physical address space 6= RAM directly mapped
CS register also has a 32-bit base address (initialized to 0xFFFF0000) What if I have < 4 GB RAM?
Booting in Real Mode www.tugraz.at
Address: 0xFFFFFFF0 How is that possible?
63 physical address space 6= RAM directly mapped
What if I have < 4 GB RAM?
Booting in Real Mode www.tugraz.at
Address: 0xFFFFFFF0 How is that possible? CS register also has a 32-bit base address (initialized to 0xFFFF0000)
63 physical address space 6= RAM directly mapped
Booting in Real Mode www.tugraz.at
Address: 0xFFFFFFF0 How is that possible? CS register also has a 32-bit base address (initialized to 0xFFFF0000) What if I have < 4 GB RAM?
63 Booting in Real Mode www.tugraz.at
Address: 0xFFFFFFF0 How is that possible? CS register also has a 32-bit base address (initialized to 0xFFFF0000) What if I have < 4 GB RAM? physical address space 6= RAM directly mapped
63 Physical Address Space www.tugraz.at
00000000-007fffff (prio 0, RW): alias ram-below-4g (this is our RAM) 000a0000-000bffff (prio 1, RW): vga-lowmem (remember for later) 000c0000-000dffff (prio 1, RW): pc.rom 000e0000-000fffff (prio 1, R-): alias isa-bios fd000000-fdffffff (prio 1, RW): vga.vram febc0000-febdffff (prio 1, RW): e1000-mmio febf0400-febf041f (prio 0, RW): vga ioports remapped febf0500-febf0515 (prio 0, RW): bochs dispi interface febf0600-febf0607 (prio 0, RW): qemu extended regs fffc0000-ffffffff (prio 0, R-): pc.bios (ahhh!) ...
64 Switch to protected mode (32 bit) Select a device to boot from Load MBR from device into memory Execute code from MBR
BIOS www.tugraz.at
BIOS initializes hardware platform
65 Select a device to boot from Load MBR from device into memory Execute code from MBR
BIOS www.tugraz.at
BIOS initializes hardware platform Switch to protected mode (32 bit)
65 Load MBR from device into memory Execute code from MBR
BIOS www.tugraz.at
BIOS initializes hardware platform Switch to protected mode (32 bit) Select a device to boot from
65 Execute code from MBR
BIOS www.tugraz.at
BIOS initializes hardware platform Switch to protected mode (32 bit) Select a device to boot from Load MBR from device into memory
65 BIOS www.tugraz.at
BIOS initializes hardware platform Switch to protected mode (32 bit) Select a device to boot from Load MBR from device into memory Execute code from MBR
65 Booting x86 Intel (Illustration) www.tugraz.at
66 GRUB www.tugraz.at
Boot loader for Linux, SWEB, . . . Loads the OS image from disk and starts OS
GRUB One of the important features in GRUB is flexibility; GRUB understands file-systems and kernel executable formats, so you can load an arbitrary operating system the way you like, without recording the physical position of your kernel on the disk. Thus you can load the kernel just by specifying its file name and the drive and partition where the kernel resides.
67 Booting www.tugraz.at
68 Start device drivers and initialize devices Start initial processes (e.g. init-process)
Booting the OS www.tugraz.at
Prepare hardware
69 Start initial processes (e.g. init-process)
Booting the OS www.tugraz.at
Prepare hardware Start device drivers and initialize devices
69 Booting the OS www.tugraz.at
Prepare hardware Start device drivers and initialize devices Start initial processes (e.g. init-process)
69 % readelf -a kernel.x | grep Entry Entry point address: 0x801001ba
% objdump -S kernel.x | less 801001ba
Wait, that’s C-Code!
Booting the OS (SWEB) www.tugraz.at
Kernel is a compiled binary (e.g. an ELF binary)
70 % objdump -S kernel.x | less 801001ba
Wait, that’s C-Code!
Booting the OS (SWEB) www.tugraz.at
Kernel is a compiled binary (e.g. an ELF binary)
% readelf -a kernel.x | grep Entry Entry point address: 0x801001ba
70 Wait, that’s C-Code!
Booting the OS (SWEB) www.tugraz.at
Kernel is a compiled binary (e.g. an ELF binary)
% readelf -a kernel.x | grep Entry Entry point address: 0x801001ba
% objdump -S kernel.x | less 801001ba
70 Booting the OS (SWEB) www.tugraz.at
Kernel is a compiled binary (e.g. an ELF binary)
% readelf -a kernel.x | grep Entry Entry point address: 0x801001ba
% objdump -S kernel.x | less 801001ba
Wait, that’s C-Code!
70 Booting the OS (SWEB) www.tugraz.at
extern "C" void entry() { asm("mov%ebx,multi_boot_structure_pointer- BASE");
PRINT("Booting...\n");
71 Booting the OS (SWEB) www.tugraz.at
PRINT("Clearing Framebuffer...\n"); memset((char*) 0xB8000, 0, 80 * 25 * 2);
PRINT("Clearing BSS...\n"); char* bss_start= TRUNCATE(&bss_start_address); memset(bss_start, 0, TRUNCATE(&bss_end_address)- bss_start);
PRINT("Initializing Kernel Paging Structures...\n"); //...
72 Booting the OS (SWEB) www.tugraz.at
PRINT("Enable PSE and PAE...\n"); asm("mov%cr4,%eax\n" "or $0x20,%eax\n" "mov%eax,%cr4\n");
PRINT("Setting CR3 Register...\n"); asm("mov%[pd],%%cr3"::[pd]"r"(TRUNCATE(kernel_page_map_level_4)));
PRINT("Enable EFER.LME and EFER.NXE...\n"); asm("mov $0xC0000080,%ecx\n" "rdmsr\n" "or $0x900,%eax\n" "wrmsr\n"); //... PRINT("Enable Paging...\n"); asm("mov%cr0,%eax\n" "or $0x80000001,%eax\n" "mov%eax,%cr0\n");
73 Booting the OS (SWEB) www.tugraz.at
PRINT("Setup TSS...\n"); TSS* g_tss_p=(TSS *) TRUNCATE(&g_tss); g_tss_p->ist0_h = -1U; g_tss_p->ist0_l=(uint32) TRUNCATE(boot_stack) | 0x80004000; g_tss_p->rsp0_h = -1U; g_tss_p->rsp0_l=(uint32) TRUNCATE(boot_stack) | 0x80004000;
74 Booting the OS (SWEB) www.tugraz.at
75 Booting the OS (SWEB) www.tugraz.at
76 Booting the OS (SWEB) www.tugraz.at
static void setSegmentDescriptor(uint32 index, uint32 baseH, uint32 baseL, uint32 limit, uint8 dpl, uint8 code, uint8 tss);
PRINT("Setup Segments...\n"); setSegmentDescriptor(1, 0, 0, 0, 0, 1, 0); setSegmentDescriptor(2, 0, 0, 0, 0, 0, 0); setSegmentDescriptor(3, 0, 0, 0, 3, 1, 0); setSegmentDescriptor(4, 0, 0, 0, 3, 0, 0); setSegmentDescriptor(5, -1U,(uint32) TRUNCATE(&g_tss) | 0x80000000, sizeof(TSS) - 1, 0, 0, 1);
PRINT("Loading Long Mode GDT...\n");
struct GDT32Ptr gdt32_ptr; gdt32_ptr.limit= sizeof(gdt) - 1; gdt32_ptr.addr=(uint32) TRUNCATE(gdt); asm("lgdt%[gdt_ptr]"::[gdt_ptr]"m"(gdt32_ptr)); // ...
77 Booting the OS (SWEB) www.tugraz.at
PRINT("Setting Long Mode Segment Selectors...\n"); asm("mov%%ax,%%ds\n" "mov%%ax,%%es\n" "mov%%ax,%%ss\n" "mov%%ax,%%fs\n" "mov%%ax,%%gs\n" ::"a"(KERNEL_DS));
PRINT("Calling entry64()...\n"); asm("ljmp%[cs],$entry64-BASE\n"::[cs]"i"(KERNEL_CS));
PRINT("Returned from entry64()? This should never happen.\n"); asm("hlt"); }
78 Booting the OS (SWEB) www.tugraz.at
PRINT("Setting Long Mode Segment Selectors...\n"); asm("mov%%ax,%%ds\n" "mov%%ax,%%es\n" "mov%%ax,%%ss\n" "mov%%ax,%%fs\n" "mov%%ax,%%gs\n" ::"a"(KERNEL_DS));
PRINT("Calling entry64()...\n"); asm("ljmp%[cs],$entry64-BASE\n"::[cs]"i"(KERNEL_CS));
PRINT("Returned from entry64()? This should never happen.\n"); asm("hlt"); }
79 Booting the OS (SWEB) www.tugraz.at
extern "C" void entry64() { PRINT("Parsing Multiboot Header...\n"); parseMultibootHeader(); PRINT("Initializing Kernel Paging Structures...\n"); initialisePaging(); PRINT("Setting CR3 Register...\n"); asm("mov%%rax,%%cr3"::"a"(VIRTUAL_TO_PHYSICAL_BOOT(ArchMemory:: getRootOfKernelPagingStructure()))); PRINT("Switch to our own stack...\n"); asm("mov%[stack],%%rsp\n" "mov%[stack],%%rbp\n"::[stack]"i"(boot_stack+0x4000));
80 Booting the OS (SWEB) www.tugraz.at
PRINT("Loading Long Mode Segments...\n");
gdt_ptr.limit= sizeof(gdt) - 1; gdt_ptr.addr=(uint64)gdt; asm("lgdt (%%rax)"::"a"(&gdt_ptr)); asm("mov%%ax,%%ds\n" "mov%%ax,%%es\n" "mov%%ax,%%ss\n" "mov%%ax,%%fs\n" "mov%%ax,%%gs\n" ::"a"(KERNEL_DS)); asm("ltr%%ax"::"a"(KERNEL_TSS)); PRINT("Calling startup()...\n"); asm("jmp *%[startup]"::[startup]"r"(startup)); while (1); }
81 Booting the OS (SWEB) www.tugraz.at
extern "C" void startup() { writeLine2Bochs("Removing Boot Time Ident Mapping...\n"); removeBootTimeIdentMapping(); system_state= BOOTING;
PageManager::instance(); writeLine2Bochs("PageManager and KernelMemoryManager created\n");
main_console= ArchCommon::createConsole(1); writeLine2Bochs("Console created\n"); // ...
82 Booting the OS (SWEB) www.tugraz.at
Scheduler::instance();
//needs to be done after scheduler and terminal, but prior to enableInterrupts kprintf_init();
debug(MAIN,"Threads init\n"); ArchThreads::initialise(); debug(MAIN,"Interupts init\n"); ArchInterrupts::initialise();
ArchInterrupts::setTimerFrequency(IRQ0_TIMER_FREQUENCY);
83 Booting the OS (SWEB) www.tugraz.at
ArchCommon::initDebug();
vfs.initialize(); debug(MAIN,"Mounting DeviceFS under/dev/\n"); DeviceFSType *devfs= new DeviceFSType(); vfs.registerFileSystem(devfs); default_working_dir= vfs.root_mount("devicefs", 0);
debug(MAIN,"Block Device creation\n"); BDManager::getInstance()->doDeviceDetection(); debug(MAIN,"Block Device done\n");
for (BDVirtualDevice* bdvd: BDManager::getInstance()->device_list_) { debug(MAIN,"Detected Device:%s::%d\n", bdvd->getName(), bdvd-> getDeviceNumber()); }
84 Booting the OS (SWEB) www.tugraz.at
// initialise global and static objects extern ustl::list
85 Booting the OS (SWEB) www.tugraz.at
debug(MAIN,"Adding Kernel threads\n"); Scheduler::instance()->addNewThread(main_console); Scheduler::instance()->addNewThread(new ProcessRegistry(new FileSystemInfo(* default_working_dir), user_progs /*see user_progs.h*/)); Scheduler::instance()->printThreadList();
kprintf("Now enabling Interrupts...\n"); system_state= RUNNING;
ArchInterrupts::enableInterrupts();
Scheduler::instance()->yield(); //not reached assert(false); }
86 Booting www.tugraz.at
87 Process and Thread Fundamentals actions: run, interrupt, stop resources: CPU time, stack, registers
actions: create, start, terminate resources: threads, memory, program
actions: write, compile, install, load resources: file A thread: an execution context
A process: a container for threads and memory contents of a program
Program, Process, Thread www.tugraz.at
A program: a binary file containing code and data
88 actions: run, interrupt, stop resources: CPU time, stack, registers
actions: create, start, terminate resources: threads, memory, program
resources: file A thread: an execution context
A process: a container for threads and memory contents of a program
Program, Process, Thread www.tugraz.at
A program: a binary file containing code and data actions: write, compile, install, load
88 actions: run, interrupt, stop resources: CPU time, stack, registers
actions: create, start, terminate resources: threads, memory, program
A thread: an execution context
A process: a container for threads and memory contents of a program
Program, Process, Thread www.tugraz.at
A program: a binary file containing code and data actions: write, compile, install, load resources: file
88 actions: create, start, terminate resources: threads, memory, program
actions: run, interrupt, stop resources: CPU time, stack, registers A process: a container for threads and memory contents of a program
Program, Process, Thread www.tugraz.at
A program: a binary file containing code and data actions: write, compile, install, load resources: file A thread: an execution context
88 actions: create, start, terminate resources: threads, memory, program
resources: CPU time, stack, registers A process: a container for threads and memory contents of a program
Program, Process, Thread www.tugraz.at
A program: a binary file containing code and data actions: write, compile, install, load resources: file A thread: an execution context actions: run, interrupt, stop
88 actions: create, start, terminate resources: threads, memory, program
A process: a container for threads and memory contents of a program
Program, Process, Thread www.tugraz.at
A program: a binary file containing code and data actions: write, compile, install, load resources: file A thread: an execution context actions: run, interrupt, stop resources: CPU time, stack, registers
88 actions: create, start, terminate resources: threads, memory, program
Program, Process, Thread www.tugraz.at
A program: a binary file containing code and data actions: write, compile, install, load resources: file A thread: an execution context actions: run, interrupt, stop resources: CPU time, stack, registers A process: a container for threads and memory contents of a program
88 resources: threads, memory, program
Program, Process, Thread www.tugraz.at
A program: a binary file containing code and data actions: write, compile, install, load resources: file A thread: an execution context actions: run, interrupt, stop resources: CPU time, stack, registers A process: a container for threads and memory contents of a program actions: create, start, terminate
88 Program, Process, Thread www.tugraz.at
A program: a binary file containing code and data actions: write, compile, install, load resources: file A thread: an execution context actions: run, interrupt, stop resources: CPU time, stack, registers A process: a container for threads and memory contents of a program actions: create, start, terminate resources: threads, memory, program
88
File: abstraction of a disk or a device Socket: abstraction of a network connection Window: abstraction of a display
→ Abstractions hide many details but provide the required capabilities
Abstractions www.tugraz.at
Process: abstraction of a computer
89 Socket: abstraction of a network connection Window: abstraction of a display
→ Abstractions hide many details but provide the required capabilities
Abstractions www.tugraz.at
Process: abstraction of a computer File: abstraction of a disk or a device
89 Window: abstraction of a display
→ Abstractions hide many details but provide the required capabilities
Abstractions www.tugraz.at
Process: abstraction of a computer File: abstraction of a disk or a device Socket: abstraction of a network connection
89 → Abstractions hide many details but provide the required capabilities
Abstractions www.tugraz.at
Process: abstraction of a computer File: abstraction of a disk or a device Socket: abstraction of a network connection Window: abstraction of a display
89 → Abstractions hide many details but provide the required capabilities
Abstractions www.tugraz.at
Process: abstraction of a computer File: abstraction of a disk or a device Socket: abstraction of a network connection Window: abstraction of a display
89 Abstractions www.tugraz.at
Process: abstraction of a computer File: abstraction of a disk or a device Socket: abstraction of a network connection Window: abstraction of a display
→ Abstractions hide many details but provide the required capabilities
89 CPU vs. Process www.tugraz.at
90 CPU vs. Process www.tugraz.at
91 Processes www.tugraz.at
Implemented by the kernel
92 Implementation? www.tugraz.at
We have “one hardware” We have many “processes” How do we solve this?
93 The Process Abstraction www.tugraz.at
94 setting up a stack and setting the stack pointer and setting the instruction pointer (of the first thread) to the programs first instruction Process is an instance of a program Kernel must organize running code of multiple processes Must be able to switch from one process to another OS keeps a list of process data structure (aka the “PCB”)
Program, Process, Thread www.tugraz.at
Once a program is loaded in memory, OS can start it(s first thread) by
95 setting the instruction pointer (of the first thread) to the programs first instruction Process is an instance of a program Kernel must organize running code of multiple processes Must be able to switch from one process to another OS keeps a list of process data structure (aka the “PCB”)
Program, Process, Thread www.tugraz.at
Once a program is loaded in memory, OS can start it(s first thread) by setting up a stack and setting the stack pointer and
95 Process is an instance of a program Kernel must organize running code of multiple processes Must be able to switch from one process to another OS keeps a list of process data structure (aka the “PCB”)
Program, Process, Thread www.tugraz.at
Once a program is loaded in memory, OS can start it(s first thread) by setting up a stack and setting the stack pointer and setting the instruction pointer (of the first thread) to the programs first instruction
95 Kernel must organize running code of multiple processes Must be able to switch from one process to another OS keeps a list of process data structure (aka the “PCB”)
Program, Process, Thread www.tugraz.at
Once a program is loaded in memory, OS can start it(s first thread) by setting up a stack and setting the stack pointer and setting the instruction pointer (of the first thread) to the programs first instruction Process is an instance of a program
95 Must be able to switch from one process to another OS keeps a list of process data structure (aka the “PCB”)
Program, Process, Thread www.tugraz.at
Once a program is loaded in memory, OS can start it(s first thread) by setting up a stack and setting the stack pointer and setting the instruction pointer (of the first thread) to the programs first instruction Process is an instance of a program Kernel must organize running code of multiple processes
95 OS keeps a list of process data structure (aka the “PCB”)
Program, Process, Thread www.tugraz.at
Once a program is loaded in memory, OS can start it(s first thread) by setting up a stack and setting the stack pointer and setting the instruction pointer (of the first thread) to the programs first instruction Process is an instance of a program Kernel must organize running code of multiple processes Must be able to switch from one process to another
95 Program, Process, Thread www.tugraz.at
Once a program is loaded in memory, OS can start it(s first thread) by setting up a stack and setting the stack pointer and setting the instruction pointer (of the first thread) to the programs first instruction Process is an instance of a program Kernel must organize running code of multiple processes Must be able to switch from one process to another OS keeps a list of process data structure (aka the “PCB”)
95 where program is loaded in memory Process ID where image is on disk User ID which user asked to execute Process status what privileges the process has Scheduling information etc. I/O resources
same program code and data own stack own registers (including instruction pointer)
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores
96 Process ID User ID Process status Scheduling information I/O resources
same program code and data own stack own registers (including instruction pointer)
where program is loaded in memory where image is on disk which user asked to execute what privileges the process has etc.
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores
96 Process ID User ID Process status Scheduling information I/O resources
same program code and data own stack own registers (including instruction pointer)
where image is on disk which user asked to execute what privileges the process has etc.
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory
96 Process ID User ID Process status Scheduling information I/O resources
same program code and data own stack own registers (including instruction pointer)
which user asked to execute what privileges the process has etc.
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory where image is on disk
96 Process ID User ID Process status Scheduling information I/O resources
same program code and data own stack own registers (including instruction pointer)
what privileges the process has etc.
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory where image is on disk which user asked to execute
96 Process ID User ID Process status Scheduling information I/O resources
same program code and data own stack own registers (including instruction pointer)
etc.
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory where image is on disk which user asked to execute what privileges the process has
96 Process ID User ID Process status Scheduling information I/O resources
same program code and data own stack own registers (including instruction pointer)
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory where image is on disk which user asked to execute what privileges the process has etc.
96 same program code and data own stack own registers (including instruction pointer)
Process ID User ID Process status Scheduling information I/O resources
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory where image is on disk which user asked to execute what privileges the process has etc.
96 same program code and data own stack own registers (including instruction pointer)
User ID Process status Scheduling information I/O resources
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory Process ID where image is on disk which user asked to execute what privileges the process has etc.
96 same program code and data own stack own registers (including instruction pointer)
Process status Scheduling information I/O resources
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory Process ID where image is on disk User ID which user asked to execute what privileges the process has etc.
96 same program code and data own stack own registers (including instruction pointer)
Scheduling information I/O resources
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory Process ID where image is on disk User ID which user asked to execute Process status what privileges the process has etc.
96 same program code and data own stack own registers (including instruction pointer)
I/O resources
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory Process ID where image is on disk User ID which user asked to execute Process status what privileges the process has Scheduling information etc.
96 same program code and data own stack own registers (including instruction pointer)
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory Process ID where image is on disk User ID which user asked to execute Process status what privileges the process has Scheduling information etc. I/O resources
96 same program code and data own stack own registers (including instruction pointer)
Process can have multiple threads
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory Process ID where image is on disk User ID which user asked to execute Process status what privileges the process has Scheduling information etc. I/O resources
96 same program code and data own stack own registers (including instruction pointer)
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory Process ID where image is on disk User ID which user asked to execute Process status what privileges the process has Scheduling information etc. I/O resources
Process can have multiple threads
96 own stack own registers (including instruction pointer)
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory Process ID where image is on disk User ID which user asked to execute Process status what privileges the process has Scheduling information etc. I/O resources
Process can have multiple threads
same program code and data
96 own registers (including instruction pointer)
Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory Process ID where image is on disk User ID which user asked to execute Process status what privileges the process has Scheduling information etc. I/O resources
Process can have multiple threads
same program code and data own stack
96 Process List (aka PCB) www.tugraz.at
Process list stores where program is loaded in memory Process ID where image is on disk User ID which user asked to execute Process status what privileges the process has Scheduling information etc. I/O resources
Process can have multiple threads
same program code and data own stack own registers (including instruction pointer)
96 Process Protection Mechanisms Malicious? We want to give the program restricted privileges How can we do that?
What code? Do we trust that code? Maybe buggy?
How can it be safe to run untrusted software on your hardware? www.tugraz.at
Challenges:
Threads of a process run code
97 Malicious? We want to give the program restricted privileges How can we do that?
Do we trust that code? Maybe buggy?
How can it be safe to run untrusted software on your hardware? www.tugraz.at
Challenges:
Threads of a process run code What code?
97 Malicious? We want to give the program restricted privileges How can we do that?
Maybe buggy?
How can it be safe to run untrusted software on your hardware? www.tugraz.at
Challenges:
Threads of a process run code What code? Do we trust that code?
97 We want to give the program restricted privileges How can we do that?
Malicious?
How can it be safe to run untrusted software on your hardware? www.tugraz.at
Challenges:
Threads of a process run code What code? Do we trust that code? Maybe buggy?
97 We want to give the program restricted privileges How can we do that?
Malicious?
How can it be safe to run untrusted software on your hardware? www.tugraz.at
Challenges:
Threads of a process run code What code? Do we trust that code? Maybe buggy?
97 How can we do that?
How can it be safe to run untrusted software on your hardware? www.tugraz.at
Challenges:
Threads of a process run code What code? Do we trust that code? Maybe buggy? Malicious? We want to give the program restricted privileges
97 How can it be safe to run untrusted software on your hardware? www.tugraz.at
Challenges:
Threads of a process run code What code? Do we trust that code? Maybe buggy? Malicious? We want to give the program restricted privileges How can we do that?
97 Some instructions can
asm("cli"); asm("hlt");
Privileged and unprivileged instructions www.tugraz.at
Most instructions cannot do any harm
98 asm("cli"); asm("hlt");
Privileged and unprivileged instructions www.tugraz.at
Most instructions cannot do any harm Some instructions can
98 Privileged and unprivileged instructions www.tugraz.at
Most instructions cannot do any harm Some instructions can
asm("cli"); asm("hlt");
98 Examples for Privileged Instructions (Intel) www.tugraz.at
LGDT: Load GDT register LLDT: Load LDT register LTR: Load task register LIDT: Load IDT register MOV (control registers): Load and store control registers LMSW: Load machine status word CLTS: Clear task-switched flag in register CR0 MOV (debug registers): Load and store debug registers INVD: Invalidate cache, without writeback WBINVD: Invalidate cache, with writeback INVLPG: Invalidate TLB entry HLT: Halt processor RDMSR: Read Model-Specific Registers WRMSR: Write Model-Specific Registers
99 Recall: DPL defined in segment descriptor
User-mode: DPL = 3 Kernel-mode: DPL = 0
→ hardware-assisted control mechanisms
Dual-mode operation www.tugraz.at
User-mode: limited privileges Kernel-mode: complete privileges
100 → hardware-assisted control mechanisms
Dual-mode operation www.tugraz.at
User-mode: limited privileges Kernel-mode: complete privileges
Recall: DPL defined in segment descriptor
User-mode: DPL = 3 Kernel-mode: DPL = 0
100 Dual-mode operation www.tugraz.at
User-mode: limited privileges Kernel-mode: complete privileges
Recall: DPL defined in segment descriptor
User-mode: DPL = 3 Kernel-mode: DPL = 0
→ hardware-assisted control mechanisms
100 Hardware Support: Dual-Mode www.tugraz.at
Kernel Mode: User Mode:
101 Hardware Support: Dual-Mode www.tugraz.at
Kernel Mode: User Mode: OS runs in kernel mode User programs run in user mode
101 Hardware Support: Dual-Mode www.tugraz.at
Kernel Mode: User Mode: OS runs in kernel mode User programs run in user mode Full privileges for hardware accesses Limited privileges
101 Hardware Support: Dual-Mode www.tugraz.at
Kernel Mode: User Mode: OS runs in kernel mode User programs run in user mode Full privileges for hardware accesses Limited privileges Read/write to any memory Some instructions and memory regions are not accessible
101 Hardware Support: Dual-Mode www.tugraz.at
Kernel Mode: User Mode: OS runs in kernel mode User programs run in user mode Full privileges for hardware accesses Limited privileges Read/write to any memory Some instructions and memory regions are not Access to any I/O-device accessible If tried anyway: exception is raised by the CPU.
101 Hardware Support: Dual-Mode www.tugraz.at
Kernel Mode: User Mode: OS runs in kernel mode User programs run in user mode Full privileges for hardware accesses Limited privileges Read/write to any memory Some instructions and memory regions are not Access to any I/O-device accessible Access to all disk content If tried anyway: exception is raised by the CPU. Need something user mode can’t do?
101 Hardware Support: Dual-Mode www.tugraz.at
Kernel Mode: User Mode: OS runs in kernel mode User programs run in user mode Full privileges for hardware accesses Limited privileges Read/write to any memory Some instructions and memory regions are not Access to any I/O-device accessible Access to all disk content If tried anyway: exception is raised by the CPU. Access to all network traffic Need something user mode can’t do? → ask operating system for help
101 Hardware Support: Dual-Mode www.tugraz.at
Kernel Mode: User Mode: OS runs in kernel mode User programs run in user mode Full privileges for hardware accesses Limited privileges Read/write to any memory Some instructions and memory regions are not Access to any I/O-device accessible Access to all disk content If tried anyway: exception is raised by the CPU. Access to all network traffic Need something user mode can’t do? → “call” operating system for help
101 Hardware Support: Dual-Mode www.tugraz.at
Kernel Mode: User Mode: OS runs in kernel mode User programs run in user mode Full privileges for hardware accesses Limited privileges Read/write to any memory Some instructions and memory regions are not Access to any I/O-device accessible Access to all disk content If tried anyway: exception is raised by the CPU. Access to all network traffic Need something user mode can’t do? → “call” operating system for help → system call
101 Hardware Support: Dual-Mode Implementation www.tugraz.at
mode stored in EFLAGS register segment descriptors paging structures ...
102 IA-32 Ring Structure www.tugraz.at
103 How to change from ring to ring . . . www.tugraz.at
change from kernel mode (lower level ring) to user mode (higher level ring) not a problem
104 How to change from ring to ring . . . www.tugraz.at
change from kernel mode (lower level ring) to user mode (higher level ring) not a problem change from user mode (higher level ring) to kernel mode (lower level ring) must be a controlled procedure
104 How to change from ring to ring . . . www.tugraz.at
change from kernel mode (lower level ring) to user mode (higher level ring) not a problem change from user mode (higher level ring) to kernel mode (lower level ring) must be a controlled procedure
→ Otherwise there would be no protection
104 How to change from ring to ring . . . www.tugraz.at
change from ring 0 to ring 3 not a problem change from user mode (higher level ring) to kernel mode (lower level ring) must be a controlled procedure
→ Otherwise there would be no protection
104 How to change from ring to ring . . . www.tugraz.at
change from ring 0 to ring 3 not a problem change from ring 3 to ring 0 through controlled procedure
→ Otherwise there would be no protection
104 How to change from ring to ring . . . www.tugraz.at
change from ring 0 to ring 3 through special return instruction (iret) change from ring 3 to ring 0 through controlled procedure
→ Otherwise there would be no protection
104 How to change from ring to ring . . . www.tugraz.at
change from ring 0 to ring 3 through special return instruction (iret) change from ring 3 to ring 0 through int 0x80, sysenter, or syscall
→ Otherwise there would be no protection
104 timer I/O-devices exceptions (divide-by-zero, page fault, etc.)
or by the hardware
Interrupts www.tugraz.at
either generated by the software (e.g. syscall)
105 timer I/O-devices exceptions (divide-by-zero, page fault, etc.)
Interrupts www.tugraz.at
either generated by the software (e.g. syscall) or by the hardware
105 I/O-devices exceptions (divide-by-zero, page fault, etc.)
Interrupts www.tugraz.at
either generated by the software (e.g. syscall) or by the hardware timer
105 exceptions (divide-by-zero, page fault, etc.)
Interrupts www.tugraz.at
either generated by the software (e.g. syscall) or by the hardware timer I/O-devices
105 Interrupts www.tugraz.at
either generated by the software (e.g. syscall) or by the hardware timer I/O-devices exceptions (divide-by-zero, page fault, etc.)
105 Security and stability Who knows where the users SP points Maybe SP points to illegal address Would raises an page fault exception (in the kernel) Some register values are pushed to stack by the CPU during a context switch
Why?
How many stacks do we actually need? Do we need multiple stacks for the kernel?
Interrupts and Stacks www.tugraz.at
Interrupts switch stack to a kernel stack
106 Security and stability Who knows where the users SP points Maybe SP points to illegal address Would raises an page fault exception (in the kernel) Some register values are pushed to stack by the CPU during a context switch How many stacks do we actually need? Do we need multiple stacks for the kernel?
Interrupts and Stacks www.tugraz.at
Interrupts switch stack to a kernel stack Why?
106 Who knows where the users SP points Maybe SP points to illegal address Would raises an page fault exception (in the kernel) Some register values are pushed to stack by the CPU during a context switch How many stacks do we actually need? Do we need multiple stacks for the kernel?
Interrupts and Stacks www.tugraz.at
Interrupts switch stack to a kernel stack Why? Security and stability
106 Maybe SP points to illegal address Would raises an page fault exception (in the kernel) Some register values are pushed to stack by the CPU during a context switch How many stacks do we actually need? Do we need multiple stacks for the kernel?
Interrupts and Stacks www.tugraz.at
Interrupts switch stack to a kernel stack Why? Security and stability Who knows where the users SP points
106 Would raises an page fault exception (in the kernel) Some register values are pushed to stack by the CPU during a context switch How many stacks do we actually need? Do we need multiple stacks for the kernel?
Interrupts and Stacks www.tugraz.at
Interrupts switch stack to a kernel stack Why? Security and stability Who knows where the users SP points Maybe SP points to illegal address
106 Some register values are pushed to stack by the CPU during a context switch How many stacks do we actually need? Do we need multiple stacks for the kernel?
Interrupts and Stacks www.tugraz.at
Interrupts switch stack to a kernel stack Why? Security and stability Who knows where the users SP points Maybe SP points to illegal address Would raises an page fault exception (in the kernel)
106 How many stacks do we actually need? Do we need multiple stacks for the kernel?
Interrupts and Stacks www.tugraz.at
Interrupts switch stack to a kernel stack Why? Security and stability Who knows where the users SP points Maybe SP points to illegal address Would raises an page fault exception (in the kernel) Some register values are pushed to stack by the CPU during a context switch
106 Do we need multiple stacks for the kernel?
Interrupts and Stacks www.tugraz.at
Interrupts switch stack to a kernel stack Why? Security and stability Who knows where the users SP points Maybe SP points to illegal address Would raises an page fault exception (in the kernel) Some register values are pushed to stack by the CPU during a context switch How many stacks do we actually need?
106 Interrupts and Stacks www.tugraz.at
Interrupts switch stack to a kernel stack Why? Security and stability Who knows where the users SP points Maybe SP points to illegal address Would raises an page fault exception (in the kernel) Some register values are pushed to stack by the CPU during a context switch How many stacks do we actually need? Do we need multiple stacks for the kernel?
106 Stacks www.tugraz.at
107 Stacks www.tugraz.at
108 Stacks www.tugraz.at
Running Ready to Run Blocked
system call
procedure 2 procedure 2 procedure 2
procedure 1 procedure 1 procedure 1
main main main User Stack
I/O-Driver
Syscall handler
CPU state CPU state user mode user mode Kerrnel Stack Kerrnel
109 Context Switches how?
how to switch between threads? how do we let a CPU / core execute a different function? change the instruction pointer?
Threads. Multiple Threads. www.tugraz.at
one CPU / core: one active thread at any point in time
110 how?
how do we let a CPU / core execute a different function? change the instruction pointer?
Threads. Multiple Threads. www.tugraz.at
one CPU / core: one active thread at any point in time how to switch between threads?
110 how?
change the instruction pointer?
Threads. Multiple Threads. www.tugraz.at
one CPU / core: one active thread at any point in time how to switch between threads? how do we let a CPU / core execute a different function?
110 how?
Threads. Multiple Threads. www.tugraz.at
one CPU / core: one active thread at any point in time how to switch between threads? how do we let a CPU / core execute a different function? change the instruction pointer?
110 how?
Threads. Multiple Threads. www.tugraz.at
one CPU / core: one active thread at any point in time how to switch between threads? how do we let a CPU / core execute a different function? change the instruction pointer?
110 Threads. Multiple Threads. www.tugraz.at
one CPU / core: one active thread at any point in time how to switch between threads? how do we let a CPU / core execute a different function? change the instruction pointer? how?
110 asm("jmp *%[other_thread_function]" : :[other_thread_function]"r"(other_thread_function));
does this work? Yes, but . . .
what if the thread is in another process? scheduling thread slices: how do we later restore the state we came from? what if we’re coming from kernelspace?
Threads. Multiple Threads. www.tugraz.at
Changing the instruction pointer
111 does this work? Yes, but . . .
what if the thread is in another process? scheduling thread slices: how do we later restore the state we came from? what if we’re coming from kernelspace?
Threads. Multiple Threads. www.tugraz.at
Changing the instruction pointer
asm("jmp *%[other_thread_function]" : :[other_thread_function]"r"(other_thread_function));
111 Yes, but . . .
what if the thread is in another process? scheduling thread slices: how do we later restore the state we came from? what if we’re coming from kernelspace?
Threads. Multiple Threads. www.tugraz.at
Changing the instruction pointer
asm("jmp *%[other_thread_function]" : :[other_thread_function]"r"(other_thread_function));
does this work?
111 what if the thread is in another process? scheduling thread slices: how do we later restore the state we came from? what if we’re coming from kernelspace?
Threads. Multiple Threads. www.tugraz.at
Changing the instruction pointer
asm("jmp *%[other_thread_function]" : :[other_thread_function]"r"(other_thread_function));
does this work? Yes, but . . .
111 scheduling thread slices: how do we later restore the state we came from? what if we’re coming from kernelspace?
Threads. Multiple Threads. www.tugraz.at
Changing the instruction pointer
asm("jmp *%[other_thread_function]" : :[other_thread_function]"r"(other_thread_function));
does this work? Yes, but . . .
what if the thread is in another process?
111 how do we later restore the state we came from? what if we’re coming from kernelspace?
Threads. Multiple Threads. www.tugraz.at
Changing the instruction pointer
asm("jmp *%[other_thread_function]" : :[other_thread_function]"r"(other_thread_function));
does this work? Yes, but . . .
what if the thread is in another process? scheduling thread slices:
111 what if we’re coming from kernelspace?
Threads. Multiple Threads. www.tugraz.at
Changing the instruction pointer
asm("jmp *%[other_thread_function]" : :[other_thread_function]"r"(other_thread_function));
does this work? Yes, but . . .
what if the thread is in another process? scheduling thread slices: how do we later restore the state we came from?
111 Threads. Multiple Threads. www.tugraz.at
Changing the instruction pointer
asm("jmp *%[other_thread_function]" : :[other_thread_function]"r"(other_thread_function));
does this work? Yes, but . . .
what if the thread is in another process? scheduling thread slices: how do we later restore the state we came from? what if we’re coming from kernelspace?
111 Caused only by an interrupt → privilege level change CPU pushes to stack: ss, rsp, rflags, cs, rip Store register values (→ next slide) Old thread executes Scheduler (code to switch to a new thread) Context switch to a new thread
Context Switch: Old Thread → New Thread www.tugraz.at
112 CPU pushes to stack: ss, rsp, rflags, cs, rip Store register values (→ next slide) Old thread executes Scheduler (code to switch to a new thread) Context switch to a new thread
Context Switch: Old Thread → New Thread www.tugraz.at
Caused only by an interrupt → privilege level change
112 Store register values (→ next slide) Old thread executes Scheduler (code to switch to a new thread) Context switch to a new thread
Context Switch: Old Thread → New Thread www.tugraz.at
Caused only by an interrupt → privilege level change CPU pushes to stack: ss, rsp, rflags, cs, rip
112 Old thread executes Scheduler (code to switch to a new thread) Context switch to a new thread
Context Switch: Old Thread → New Thread www.tugraz.at
Caused only by an interrupt → privilege level change CPU pushes to stack: ss, rsp, rflags, cs, rip Store register values (→ next slide)
112 Context switch to a new thread
Context Switch: Old Thread → New Thread www.tugraz.at
Caused only by an interrupt → privilege level change CPU pushes to stack: ss, rsp, rflags, cs, rip Store register values (→ next slide) Old thread executes Scheduler (code to switch to a new thread)
112 Context Switch: Old Thread → New Thread www.tugraz.at
Caused only by an interrupt → privilege level change CPU pushes to stack: ss, rsp, rflags, cs, rip Store register values (→ next slide) Old thread executes Scheduler (code to switch to a new thread) Context switch to a new thread
112 1. Push all CPU register values on the stack
No modification of instruction pointer / stack pointer: rip and rsp were already pushed to the stack by CPU
2. Pop all CPU register values into a struct
3. Set currentThreadInfo, etc. to kernel thread
Context Switch: Store register values www.tugraz.at
113 No modification of instruction pointer / stack pointer: rip and rsp were already pushed to the stack by CPU
2. Pop all CPU register values into a struct
3. Set currentThreadInfo, etc. to kernel thread
Context Switch: Store register values www.tugraz.at
1. Push all CPU register values on the stack
113 rip and rsp were already pushed to the stack by CPU
2. Pop all CPU register values into a struct
3. Set currentThreadInfo, etc. to kernel thread
Context Switch: Store register values www.tugraz.at
1. Push all CPU register values on the stack
No modification of instruction pointer / stack pointer:
113 2. Pop all CPU register values into a struct
3. Set currentThreadInfo, etc. to kernel thread
Context Switch: Store register values www.tugraz.at
1. Push all CPU register values on the stack
No modification of instruction pointer / stack pointer: rip and rsp were already pushed to the stack by CPU
113 3. Set currentThreadInfo, etc. to kernel thread
Context Switch: Store register values www.tugraz.at
1. Push all CPU register values on the stack
No modification of instruction pointer / stack pointer: rip and rsp were already pushed to the stack by CPU
2. Pop all CPU register values into a struct
113 Context Switch: Store register values www.tugraz.at
1. Push all CPU register values on the stack
No modification of instruction pointer / stack pointer: rip and rsp were already pushed to the stack by CPU
2. Pop all CPU register values into a struct
3. Set currentThreadInfo, etc. to kernel thread
113 currentThreadRegisters www.tugraz.at
struct ArchThreadRegisters { uint64 rip; //0 uint64 r12; // 120 uint64 cs; //8 uint64 r13; // 128 uint64 rflags; // 16 uint64 r14; // 136 uint64 rax; // 24 uint64 r15; // 144 uint64 rcx; // 32 uint64 ds; // 152 uint64 rdx; // 40 uint64 es; // 160 uint64 rbx; // 48 uint64 fs; // 168 uint64 rsp; // 56 uint64 gs; // 176 uint64 rbp; // 64 uint64 ss; // 184 uint64 rsi; // 72 uint64 dpl; // 192 uint64 rdi; // 80 uint64 rsp0; // 200 uint64 r8; // 88 uint64 ss0; // 208 uint64 r9; // 96 uint64 cr3; // 216 uint64 r10; // 104 uint32 fpu[28]; // 224 uint64 r11; // 112 };
114 1. “Restore” CPU register values 1.1 iretq (interrupt return) expects ss, rsp, rflags, cs, rip on the stack 1.2 iretq pops values from stack into the registers 2. Instruction pointer has a new value, execution continues there
Context Switch: Old Thread → New Thread www.tugraz.at
115 1.1 iretq (interrupt return) expects ss, rsp, rflags, cs, rip on the stack 1.2 iretq pops values from stack into the registers 2. Instruction pointer has a new value, execution continues there
Context Switch: Old Thread → New Thread www.tugraz.at
1. “Restore” CPU register values
115 2. Instruction pointer has a new value, execution continues there
Context Switch: Old Thread → New Thread www.tugraz.at
1. “Restore” CPU register values 1.1 iretq (interrupt return) expects ss, rsp, rflags, cs, rip on the stack 1.2 iretq pops values from stack into the registers
115 Context Switch: Old Thread → New Thread www.tugraz.at
1. “Restore” CPU register values 1.1 iretq (interrupt return) expects ss, rsp, rflags, cs, rip on the stack 1.2 iretq pops values from stack into the registers 2. Instruction pointer has a new value, execution continues there
115 Context Switch www.tugraz.at
Looks identical for 64 bits
116 Act as if:
Thread was running already We are returning from an interrupt
Context Switch: New Thread/First Thread www.tugraz.at
117 Context Switch: New Thread/First Thread www.tugraz.at
Act as if:
Thread was running already We are returning from an interrupt
117 1. Push stored register values to stack (modifies registers) 2. “Restore” CPU register values as before 3. Instruction pointer has a new value, execution continues there
Context Switch: New Thread/First Thread www.tugraz.at
118 2. “Restore” CPU register values as before 3. Instruction pointer has a new value, execution continues there
Context Switch: New Thread/First Thread www.tugraz.at
1. Push stored register values to stack (modifies registers)
118 3. Instruction pointer has a new value, execution continues there
Context Switch: New Thread/First Thread www.tugraz.at
1. Push stored register values to stack (modifies registers) 2. “Restore” CPU register values as before
118 Context Switch: New Thread/First Thread www.tugraz.at
1. Push stored register values to stack (modifies registers) 2. “Restore” CPU register values as before 3. Instruction pointer has a new value, execution continues there
118 executing privileged instruction divide by 0 integer overflow bad memory access
device system call (syscall / sysenter / int 0x80) cpu fault (trap / interrupt)
Context Switches: When and why? www.tugraz.at
Interrupts:
clock
119 executing privileged instruction divide by 0 integer overflow bad memory access
system call (syscall / sysenter / int 0x80) cpu fault (trap / interrupt)
Context Switches: When and why? www.tugraz.at
Interrupts:
clock device
119 executing privileged instruction divide by 0 integer overflow bad memory access
cpu fault (trap / interrupt)
Context Switches: When and why? www.tugraz.at
Interrupts:
clock device system call (syscall / sysenter / int 0x80)
119 executing privileged instruction divide by 0 integer overflow bad memory access
Context Switches: When and why? www.tugraz.at
Interrupts:
clock device system call (syscall / sysenter / int 0x80) cpu fault (trap / interrupt)
119 divide by 0 integer overflow bad memory access
Context Switches: When and why? www.tugraz.at
Interrupts:
clock device system call (syscall / sysenter / int 0x80) cpu fault (trap / interrupt) executing privileged instruction
119 integer overflow bad memory access
Context Switches: When and why? www.tugraz.at
Interrupts:
clock device system call (syscall / sysenter / int 0x80) cpu fault (trap / interrupt) executing privileged instruction divide by 0
119 bad memory access
Context Switches: When and why? www.tugraz.at
Interrupts:
clock device system call (syscall / sysenter / int 0x80) cpu fault (trap / interrupt) executing privileged instruction divide by 0 integer overflow
119 Context Switches: When and why? www.tugraz.at
Interrupts:
clock device system call (syscall / sysenter / int 0x80) cpu fault (trap / interrupt) executing privileged instruction divide by 0 integer overflow bad memory access
119 Process and Thread Organization a sequence of instructions if part of a process: restricted to the boundaries of a process
an instance of a program restricted to its own boundaries and rights
a mold for a process Thread: an execution context
Process: a container for threads and memory contents of a program
Program, Process, Thread www.tugraz.at
Program: a binary file containing code and data
120 a sequence of instructions if part of a process: restricted to the boundaries of a process
an instance of a program restricted to its own boundaries and rights
Thread: an execution context
Process: a container for threads and memory contents of a program
Program, Process, Thread www.tugraz.at
Program: a binary file containing code and data a mold for a process
120 an instance of a program restricted to its own boundaries and rights
a sequence of instructions if part of a process: restricted to the boundaries of a process Process: a container for threads and memory contents of a program
Program, Process, Thread www.tugraz.at
Program: a binary file containing code and data a mold for a process Thread: an execution context
120 an instance of a program restricted to its own boundaries and rights
if part of a process: restricted to the boundaries of a process Process: a container for threads and memory contents of a program
Program, Process, Thread www.tugraz.at
Program: a binary file containing code and data a mold for a process Thread: an execution context a sequence of instructions
120 an instance of a program restricted to its own boundaries and rights
Process: a container for threads and memory contents of a program
Program, Process, Thread www.tugraz.at
Program: a binary file containing code and data a mold for a process Thread: an execution context a sequence of instructions if part of a process: restricted to the boundaries of a process
120 an instance of a program restricted to its own boundaries and rights
Program, Process, Thread www.tugraz.at
Program: a binary file containing code and data a mold for a process Thread: an execution context a sequence of instructions if part of a process: restricted to the boundaries of a process Process: a container for threads and memory contents of a program
120 restricted to its own boundaries and rights
Program, Process, Thread www.tugraz.at
Program: a binary file containing code and data a mold for a process Thread: an execution context a sequence of instructions if part of a process: restricted to the boundaries of a process Process: a container for threads and memory contents of a program an instance of a program
120 Program, Process, Thread www.tugraz.at
Program: a binary file containing code and data a mold for a process Thread: an execution context a sequence of instructions if part of a process: restricted to the boundaries of a process Process: a container for threads and memory contents of a program an instance of a program restricted to its own boundaries and rights
120 Filename Program file (Loader) (Open) file descriptors Address space (ArchMemory, CR3 register) Accounting Threads Child processes?
Process Resources www.tugraz.at
A process is a container.
Process ID
121 Program file (Loader) (Open) file descriptors Address space (ArchMemory, CR3 register) Accounting Threads Child processes?
Process Resources www.tugraz.at
A process is a container.
Process ID Filename
121 (Open) file descriptors Address space (ArchMemory, CR3 register) Accounting Threads Child processes?
Process Resources www.tugraz.at
A process is a container.
Process ID Filename Program file (Loader)
121 Address space (ArchMemory, CR3 register) Accounting Threads Child processes?
Process Resources www.tugraz.at
A process is a container.
Process ID Filename Program file (Loader) (Open) file descriptors
121 Accounting Threads Child processes?
Process Resources www.tugraz.at
A process is a container.
Process ID Filename Program file (Loader) (Open) file descriptors Address space (ArchMemory, CR3 register)
121 Threads Child processes?
Process Resources www.tugraz.at
A process is a container.
Process ID Filename Program file (Loader) (Open) file descriptors Address space (ArchMemory, CR3 register) Accounting
121 Child processes?
Process Resources www.tugraz.at
A process is a container.
Process ID Filename Program file (Loader) (Open) file descriptors Address space (ArchMemory, CR3 register) Accounting Threads
121 Process Resources www.tugraz.at
A process is a container.
Process ID Filename Program file (Loader) (Open) file descriptors Address space (ArchMemory, CR3 register) Accounting Threads Child processes?
121 Not all registers are different Some register values are process-specific and not thread-specific (e.g. CR3)
Thread state (Running, Sleeping, . . . ) A set of register values (defining the state of the execution of the userspace thread function)
A user stack A kernel stack (for syscalls) A second set of register values for the kernel (for syscalls)
Thread Resources www.tugraz.at
A thread is a unit for execution.
Thread ID
122 Not all registers are different Some register values are process-specific and not thread-specific (e.g. CR3)
A set of register values (defining the state of the execution of the userspace thread function)
A user stack A kernel stack (for syscalls) A second set of register values for the kernel (for syscalls)
Thread Resources www.tugraz.at
A thread is a unit for execution.
Thread ID Thread state (Running, Sleeping, . . . )
122 Not all registers are different Some register values are process-specific and not thread-specific (e.g. CR3) A user stack A kernel stack (for syscalls) A second set of register values for the kernel (for syscalls)
Thread Resources www.tugraz.at
A thread is a unit for execution.
Thread ID Thread state (Running, Sleeping, . . . ) A set of register values (defining the state of the execution of the userspace thread function)
122 Some register values are process-specific and not thread-specific (e.g. CR3) A user stack A kernel stack (for syscalls) A second set of register values for the kernel (for syscalls)
Thread Resources www.tugraz.at
A thread is a unit for execution.
Thread ID Thread state (Running, Sleeping, . . . ) A set of register values (defining the state of the execution of the userspace thread function) Not all registers are different
122 A user stack A kernel stack (for syscalls) A second set of register values for the kernel (for syscalls)
Thread Resources www.tugraz.at
A thread is a unit for execution.
Thread ID Thread state (Running, Sleeping, . . . ) A set of register values (defining the state of the execution of the userspace thread function) Not all registers are different Some register values are process-specific and not thread-specific (e.g. CR3)
122 A kernel stack (for syscalls) A second set of register values for the kernel (for syscalls)
Thread Resources www.tugraz.at
A thread is a unit for execution.
Thread ID Thread state (Running, Sleeping, . . . ) A set of register values (defining the state of the execution of the userspace thread function) Not all registers are different Some register values are process-specific and not thread-specific (e.g. CR3) A user stack
122 A second set of register values for the kernel (for syscalls)
Thread Resources www.tugraz.at
A thread is a unit for execution.
Thread ID Thread state (Running, Sleeping, . . . ) A set of register values (defining the state of the execution of the userspace thread function) Not all registers are different Some register values are process-specific and not thread-specific (e.g. CR3) A user stack A kernel stack (for syscalls)
122 Thread Resources www.tugraz.at
A thread is a unit for execution.
Thread ID Thread state (Running, Sleeping, . . . ) A set of register values (defining the state of the execution of the userspace thread function) Not all registers are different Some register values are process-specific and not thread-specific (e.g. CR3) A user stack A kernel stack (for syscalls) A second set of register values for the kernel (for syscalls)
122 1 initial thread executes the main()-function it’s not a “main”-thread process may start further threads if required (how?)
Process and Thread Interaction www.tugraz.at
Load program, create process, . . .
123 executes the main()-function it’s not a “main”-thread process may start further threads if required (how?)
Process and Thread Interaction www.tugraz.at
Load program, create process, . . .
1 initial thread
123 it’s not a “main”-thread process may start further threads if required (how?)
Process and Thread Interaction www.tugraz.at
Load program, create process, . . .
1 initial thread executes the main()-function
123 process may start further threads if required (how?)
Process and Thread Interaction www.tugraz.at
Load program, create process, . . .
1 initial thread executes the main()-function it’s not a “main”-thread
123 Process and Thread Interaction www.tugraz.at
Load program, create process, . . .
1 initial thread executes the main()-function it’s not a “main”-thread process may start further threads if required (how?)
123 Pure Userspace Threading: lightweight, but many drawbacks
As illustrated before: works by creative and clever usage of interrupts Threads can be implemented with and without support of the operating system
Threads can be implemented with and without support of the CPU (int 0x80 vs. sysenter/syscall)
Threads www.tugraz.at
“There is no such thing as a thread” at the CPU-level
124 Pure Userspace Threading: lightweight, but many drawbacks
Threads can be implemented with and without support of the operating system
Threads can be implemented with and without support of the CPU (int 0x80 vs. sysenter/syscall)
Threads www.tugraz.at
“There is no such thing as a thread” at the CPU-level As illustrated before: works by creative and clever usage of interrupts
124 Pure Userspace Threading: lightweight, but many drawbacks Threads can be implemented with and without support of the CPU (int 0x80 vs. sysenter/syscall)
Threads www.tugraz.at
“There is no such thing as a thread” at the CPU-level As illustrated before: works by creative and clever usage of interrupts Threads can be implemented with and without support of the operating system
124 Threads can be implemented with and without support of the CPU (int 0x80 vs. sysenter/syscall)
Threads www.tugraz.at
“There is no such thing as a thread” at the CPU-level As illustrated before: works by creative and clever usage of interrupts Threads can be implemented with and without support of the operating system Pure Userspace Threading: lightweight, but many drawbacks
124 Threads www.tugraz.at
“There is no such thing as a thread” at the CPU-level As illustrated before: works by creative and clever usage of interrupts Threads can be implemented with and without support of the operating system Pure Userspace Threading: lightweight, but many drawbacks Threads can be implemented with and without support of the CPU (int 0x80 vs. sysenter/syscall)
124 (that’s how it started) Implement threads in userspace as library can be implemented in all operating systems
Pure Userspace Threads www.tugraz.at
Kernel has no concept of threads and no idea they might exist
125 Pure Userspace Threads www.tugraz.at
Kernel has no concept of threads and no idea they might exist (that’s how it started) Implement threads in userspace as library can be implemented in all operating systems
125 Userspace Threads www.tugraz.at
126 YES: save registers in thread table choose other thread ready to run load chosen the thread’s registers from thread table change stack pointer and instruction pointer (this time jmp)
call method in libc to check: thread going to block?
user-mode-runtime-system in libc! function that might block the thread
Userspace Threads www.tugraz.at
process manages threads
127 YES: save registers in thread table choose other thread ready to run load chosen the thread’s registers from thread table change stack pointer and instruction pointer (this time jmp)
call method in libc to check: thread going to block?
function that might block the thread
Userspace Threads www.tugraz.at
process manages threads user-mode-runtime-system in libc!
127 YES: save registers in thread table choose other thread ready to run load chosen the thread’s registers from thread table change stack pointer and instruction pointer (this time jmp)
call method in libc to check: thread going to block?
Userspace Threads www.tugraz.at
process manages threads user-mode-runtime-system in libc! function that might block the thread
127 YES: save registers in thread table choose other thread ready to run load chosen the thread’s registers from thread table change stack pointer and instruction pointer (this time jmp)
Userspace Threads www.tugraz.at
process manages threads user-mode-runtime-system in libc! function that might block the thread call method in libc to check: thread going to block?
127 choose other thread ready to run load chosen the thread’s registers from thread table change stack pointer and instruction pointer (this time jmp)
Userspace Threads www.tugraz.at
process manages threads user-mode-runtime-system in libc! function that might block the thread call method in libc to check: thread going to block? YES: save registers in thread table
127 load chosen the thread’s registers from thread table change stack pointer and instruction pointer (this time jmp)
Userspace Threads www.tugraz.at
process manages threads user-mode-runtime-system in libc! function that might block the thread call method in libc to check: thread going to block? YES: save registers in thread table choose other thread ready to run
127 change stack pointer and instruction pointer (this time jmp)
Userspace Threads www.tugraz.at
process manages threads user-mode-runtime-system in libc! function that might block the thread call method in libc to check: thread going to block? YES: save registers in thread table choose other thread ready to run load chosen the thread’s registers from thread table
127 Userspace Threads www.tugraz.at
process manages threads user-mode-runtime-system in libc! function that might block the thread call method in libc to check: thread going to block? YES: save registers in thread table choose other thread ready to run load chosen the thread’s registers from thread table change stack pointer and instruction pointer (this time jmp)
127 no system calls for thread handling thread-switches are very fast no change of memory configuration when switching threads can use specialized scheduling
Advantages www.tugraz.at
Advantages
128 thread-switches are very fast no change of memory configuration when switching threads can use specialized scheduling
Advantages www.tugraz.at
Advantages no system calls for thread handling
128 no change of memory configuration when switching threads can use specialized scheduling
Advantages www.tugraz.at
Advantages no system calls for thread handling thread-switches are very fast
128 can use specialized scheduling
Advantages www.tugraz.at
Advantages no system calls for thread handling thread-switches are very fast no change of memory configuration when switching threads
128 Advantages www.tugraz.at
Advantages no system calls for thread handling thread-switches are very fast no change of memory configuration when switching threads can use specialized scheduling
128 before read is called: call select should read block: switch threads and check again later not very efficient and elegant
e.g. select-Systemcall
Page faults if page not in memory, process will block if thread has an endless loop and does not free CPU...
... one could make system-calls non-blocking ... but since this should work with unchanged (and unaware) OSs... sometimes you can find out if a syscall would block
Sometimes not
Disadvantages www.tugraz.at
threads are not allowed to make direct syscalls since they might block
129 before read is called: call select should read block: switch threads and check again later not very efficient and elegant
e.g. select-Systemcall
Page faults if page not in memory, process will block if thread has an endless loop and does not free CPU...
... but since this should work with unchanged (and unaware) OSs... sometimes you can find out if a syscall would block
Sometimes not
Disadvantages www.tugraz.at
threads are not allowed to make direct syscalls since they might block ... one could make system-calls non-blocking
129 before read is called: call select should read block: switch threads and check again later not very efficient and elegant
e.g. select-Systemcall
Page faults if page not in memory, process will block if thread has an endless loop and does not free CPU...
sometimes you can find out if a syscall would block
Sometimes not
Disadvantages www.tugraz.at
threads are not allowed to make direct syscalls since they might block ... one could make system-calls non-blocking ... but since this should work with unchanged (and unaware) OSs...
129 before read is called: call select should read block: switch threads and check again later not very efficient and elegant
Page faults if page not in memory, process will block if thread has an endless loop and does not free CPU...
e.g. select-Systemcall
Sometimes not
Disadvantages www.tugraz.at
threads are not allowed to make direct syscalls since they might block ... one could make system-calls non-blocking ... but since this should work with unchanged (and unaware) OSs... sometimes you can find out if a syscall would block
129 Page faults if page not in memory, process will block if thread has an endless loop and does not free CPU...
before read is called: call select should read block: switch threads and check again later not very efficient and elegant Sometimes not
Disadvantages www.tugraz.at
threads are not allowed to make direct syscalls since they might block ... one could make system-calls non-blocking ... but since this should work with unchanged (and unaware) OSs... sometimes you can find out if a syscall would block e.g. select-Systemcall
129 Page faults if page not in memory, process will block if thread has an endless loop and does not free CPU...
should read block: switch threads and check again later not very efficient and elegant Sometimes not
Disadvantages www.tugraz.at
threads are not allowed to make direct syscalls since they might block ... one could make system-calls non-blocking ... but since this should work with unchanged (and unaware) OSs... sometimes you can find out if a syscall would block e.g. select-Systemcall before read is called: call select
129 Page faults if page not in memory, process will block if thread has an endless loop and does not free CPU...
not very efficient and elegant Sometimes not
Disadvantages www.tugraz.at
threads are not allowed to make direct syscalls since they might block ... one could make system-calls non-blocking ... but since this should work with unchanged (and unaware) OSs... sometimes you can find out if a syscall would block e.g. select-Systemcall before read is called: call select should read block: switch threads and check again later
129 Page faults if page not in memory, process will block if thread has an endless loop and does not free CPU...
Sometimes not
Disadvantages www.tugraz.at
threads are not allowed to make direct syscalls since they might block ... one could make system-calls non-blocking ... but since this should work with unchanged (and unaware) OSs... sometimes you can find out if a syscall would block e.g. select-Systemcall before read is called: call select should read block: switch threads and check again later not very efficient and elegant
129 Page faults if page not in memory, process will block if thread has an endless loop and does not free CPU...
Disadvantages www.tugraz.at
threads are not allowed to make direct syscalls since they might block ... one could make system-calls non-blocking ... but since this should work with unchanged (and unaware) OSs... sometimes you can find out if a syscall would block e.g. select-Systemcall before read is called: call select should read block: switch threads and check again later not very efficient and elegant Sometimes not
129 if page not in memory, process will block if thread has an endless loop and does not free CPU...
Disadvantages www.tugraz.at
threads are not allowed to make direct syscalls since they might block ... one could make system-calls non-blocking ... but since this should work with unchanged (and unaware) OSs... sometimes you can find out if a syscall would block e.g. select-Systemcall before read is called: call select should read block: switch threads and check again later not very efficient and elegant Sometimes not Page faults
129 if thread has an endless loop and does not free CPU...
Disadvantages www.tugraz.at
threads are not allowed to make direct syscalls since they might block ... one could make system-calls non-blocking ... but since this should work with unchanged (and unaware) OSs... sometimes you can find out if a syscall would block e.g. select-Systemcall before read is called: call select should read block: switch threads and check again later not very efficient and elegant Sometimes not Page faults if page not in memory, process will block
129 Disadvantages www.tugraz.at
threads are not allowed to make direct syscalls since they might block ... one could make system-calls non-blocking ... but since this should work with unchanged (and unaware) OSs... sometimes you can find out if a syscall would block e.g. select-Systemcall before read is called: call select should read block: switch threads and check again later not very efficient and elegant Sometimes not Page faults if page not in memory, process will block if thread has an endless loop and does not free CPU...
129 Implementation www.tugraz.at
Two and a half options:
Userspace Kernelspace Mixed
130 more or less as in userspace but: kernel programmers by definition only write safe code
takes longer than before thread-recycling
less code the user can break thread management in kernel
thread creation and management via syscall
kernel mode threads www.tugraz.at
No runtime system needed
131 more or less as in userspace but: kernel programmers by definition only write safe code
takes longer than before thread-recycling
thread management in kernel
thread creation and management via syscall
kernel mode threads www.tugraz.at
No runtime system needed less code the user can break
131 takes longer than before thread-recycling
more or less as in userspace but: kernel programmers by definition only write safe code thread creation and management via syscall
kernel mode threads www.tugraz.at
No runtime system needed less code the user can break thread management in kernel
131 takes longer than before thread-recycling
but: kernel programmers by definition only write safe code thread creation and management via syscall
kernel mode threads www.tugraz.at
No runtime system needed less code the user can break thread management in kernel more or less as in userspace
131 takes longer than before thread-recycling
thread creation and management via syscall
kernel mode threads www.tugraz.at
No runtime system needed less code the user can break thread management in kernel more or less as in userspace but: kernel programmers by definition only write safe code
131 takes longer than before thread-recycling
kernel mode threads www.tugraz.at
No runtime system needed less code the user can break thread management in kernel more or less as in userspace but: kernel programmers by definition only write safe code thread creation and management via syscall
131 thread-recycling
kernel mode threads www.tugraz.at
No runtime system needed less code the user can break thread management in kernel more or less as in userspace but: kernel programmers by definition only write safe code thread creation and management via syscall takes longer than before
131 kernel mode threads www.tugraz.at
No runtime system needed less code the user can break thread management in kernel more or less as in userspace but: kernel programmers by definition only write safe code thread creation and management via syscall takes longer than before thread-recycling
131 Kernel mode threads www.tugraz.at
132 Hybrid solution www.tugraz.at
133 Thread states www.tugraz.at
134 Threads states www.tugraz.at
135 Thread states www.tugraz.at
136 Thread states www.tugraz.at
137 Thread states www.tugraz.at
138 Thread states www.tugraz.at
139 Thread states www.tugraz.at
140 Context Switching www.tugraz.at
141 also: start of a scheduled batch job (cronjob, how?)
at request of a user (how?)
Process Creation www.tugraz.at
at boot time (kernel threads, init processes)
142 also: start of a scheduled batch job (cronjob, how?)
Process Creation www.tugraz.at
at boot time (kernel threads, init processes) at request of a user (how?)
142 Process Creation www.tugraz.at
at boot time (kernel threads, init processes) at request of a user (how?) also: start of a scheduled batch job (cronjob, how?)
142 Windows: CreateProcess (new image) SWEB: fork (as soon as you have implemented it)
Process Creation at request of a user www.tugraz.at
via Syscall!
UNIX/Linux: fork (exact copy)
143 SWEB: fork (as soon as you have implemented it)
Process Creation at request of a user www.tugraz.at
via Syscall!
UNIX/Linux: fork (exact copy) Windows: CreateProcess (new image)
143 Process Creation at request of a user www.tugraz.at
via Syscall!
UNIX/Linux: fork (exact copy) Windows: CreateProcess (new image) SWEB: fork (as soon as you have implemented it)
143 What does the fork do? www.tugraz.at
Check http://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html!!
144 Process Creation via fork (on Unix / Linux / SWEB) www.tugraz.at
http://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html:
pid_t fork(void); The fork() function shall create a new process. The new process (child process) shall be an exact copy of the calling process (parent process) except as detailed below:
unique PID copy of file descriptors semaphore state is copied shall be created with a single thread. If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources. parent and the child processes shall be capable of executing independently before either one terminates. ...
145 fork/exec Return Value www.tugraz.at
http://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html:
pid_t fork(void); Upon successful completion, fork() shall return 0 to the child process and shall return the process ID of the child process to the parent process. Both processes shall continue to execute from the fork() function. Otherwise, -1 shall be returned to the parent process, no child process shall be created, and errno shall be set to indicate the error.
146 parent knows the child parent waits for child to die (waitpid)
Fork www.tugraz.at
pid_t child_pid; child_pid= fork(); if (child_pid == -1) { printf("fork failed\n"); } else if (child_pid == 0) { child does not know the parent printf("i’m the child\n"); } else { printf("i’m the parent\n"); waitpid(child_pid,0,0); // wait for child to die }
147 parent waits for child to die (waitpid)
Fork www.tugraz.at
pid_t child_pid; child_pid= fork(); if (child_pid == -1) { printf("fork failed\n"); } else if (child_pid == 0) { child does not know the parent printf("i’m the child\n"); parent knows the child } else { printf("i’m the parent\n"); waitpid(child_pid,0,0); // wait for child to die }
147 Fork www.tugraz.at
pid_t child_pid; child_pid= fork(); if (child_pid == -1) { printf("fork failed\n"); } else if (child_pid == 0) { child does not know the parent printf("i’m the child\n"); parent knows the child } else { printf("i’m the parent\n"); parent waits for child to die (waitpid) waitpid(child_pid,0,0); // wait for child to die }
147 Error exit (return value: non-zero) Fatal error (e.g. segmentation fault) Killed by another process
Process Termination www.tugraz.at
Normal exit (return value: zero)
148 Fatal error (e.g. segmentation fault) Killed by another process
Process Termination www.tugraz.at
Normal exit (return value: zero) Error exit (return value: non-zero)
148 Killed by another process
Process Termination www.tugraz.at
Normal exit (return value: zero) Error exit (return value: non-zero) Fatal error (e.g. segmentation fault)
148 Process Termination www.tugraz.at
Normal exit (return value: zero) Error exit (return value: non-zero) Fatal error (e.g. segmentation fault) Killed by another process
148 all children, grand-children, grand-grand-children, . . . , die aswell UNIX/Linux also cheats a bit: parent process typically inherits a processes’ children, etc.
process groups in UNIX/Linux doesn’t exist in Windows
when parent dies,
Process Hierarchies www.tugraz.at
Some operating systems have hierarchies:
implicit hierarchy from forking
Implicit parent-child hierarchy on Unix/Linux:
149 all children, grand-children, grand-grand-children, . . . , die aswell UNIX/Linux also cheats a bit: parent process typically inherits a processes’ children, etc.
doesn’t exist in Windows
when parent dies,
Process Hierarchies www.tugraz.at
Some operating systems have hierarchies:
implicit hierarchy from forking process groups in UNIX/Linux
Implicit parent-child hierarchy on Unix/Linux:
149 all children, grand-children, grand-grand-children, . . . , die aswell UNIX/Linux also cheats a bit: parent process typically inherits a processes’ children, etc.
when parent dies,
Process Hierarchies www.tugraz.at
Some operating systems have hierarchies:
implicit hierarchy from forking process groups in UNIX/Linux doesn’t exist in Windows
Implicit parent-child hierarchy on Unix/Linux:
149 UNIX/Linux also cheats a bit: parent process typically inherits a processes’ children, etc.
all children, grand-children, grand-grand-children, . . . , die aswell
Process Hierarchies www.tugraz.at
Some operating systems have hierarchies:
implicit hierarchy from forking process groups in UNIX/Linux doesn’t exist in Windows
Implicit parent-child hierarchy on Unix/Linux:
when parent dies,
149 UNIX/Linux also cheats a bit: parent process typically inherits a processes’ children, etc.
all children, grand-children, grand-grand-children, . . . , die aswell
Process Hierarchies www.tugraz.at
Some operating systems have hierarchies:
implicit hierarchy from forking process groups in UNIX/Linux doesn’t exist in Windows
Implicit parent-child hierarchy on Unix/Linux:
when parent dies,
149 Process Hierarchies www.tugraz.at
Some operating systems have hierarchies:
implicit hierarchy from forking process groups in UNIX/Linux doesn’t exist in Windows
Implicit parent-child hierarchy on Unix/Linux:
when parent dies, all children, grand-children, grand-grand-children, . . . , die aswell UNIX/Linux also cheats a bit: parent process typically inherits a processes’ children, etc.
149 Process/Thread State www.tugraz.at
git grep TODO | sort
150 Process/Thread State www.tugraz.at
git grep TODO | sort
sort has to wait for input
150 Process/Thread State www.tugraz.at
git grep TODO | sort
sort has to wait for input what does the sort do in the meantime?
150 Process/Thread State www.tugraz.at
git grep TODO | sort
sort has to wait for input what does the sort do in the meantime? loop and check (busy wait)
150 Process/Thread State www.tugraz.at
git grep TODO | sort
sort has to wait for input what does the sort do in the meantime? loop and check (busy wait) sleep and get woken up
150 Process/Thread State www.tugraz.at
git grep TODO | sort
sort has to wait for input what does the sort do in the meantime? loop and check (busy wait) sleep and get woken up blocking the process makes sense
150 Process/Thread State www.tugraz.at
git grep TODO | sort
sort has to wait for input what does the sort do in the meantime? loop and check (busy wait) sleep and get woken up blocking the process makes sense do we actually block the process?
150 Using Processes and Threads Less independent than processes No protection
Processes vs. Threads www.tugraz.at
Threads are more lightweight than processes
151 No protection
Processes vs. Threads www.tugraz.at
Threads are more lightweight than processes Less independent than processes
151 Processes vs. Threads www.tugraz.at
Threads are more lightweight than processes Less independent than processes No protection
151 typing spell checking formatting on screen automatically saving
wait for mouse-click / keyboard press wait for disk etc.
Example: text processing
Some of these things may block
Why threads? www.tugraz.at
Things should happen in parallel - even within one application
152 wait for mouse-click / keyboard press wait for disk etc.
typing spell checking formatting on screen automatically saving Some of these things may block
Why threads? www.tugraz.at
Things should happen in parallel - even within one application Example: text processing
152 wait for mouse-click / keyboard press wait for disk etc.
spell checking formatting on screen automatically saving Some of these things may block
Why threads? www.tugraz.at
Things should happen in parallel - even within one application Example: text processing typing
152 wait for mouse-click / keyboard press wait for disk etc.
formatting on screen automatically saving Some of these things may block
Why threads? www.tugraz.at
Things should happen in parallel - even within one application Example: text processing typing spell checking
152 wait for mouse-click / keyboard press wait for disk etc.
automatically saving Some of these things may block
Why threads? www.tugraz.at
Things should happen in parallel - even within one application Example: text processing typing spell checking formatting on screen
152 wait for mouse-click / keyboard press wait for disk etc.
Some of these things may block
Why threads? www.tugraz.at
Things should happen in parallel - even within one application Example: text processing typing spell checking formatting on screen automatically saving
152 wait for mouse-click / keyboard press wait for disk etc.
Why threads? www.tugraz.at
Things should happen in parallel - even within one application Example: text processing typing spell checking formatting on screen automatically saving Some of these things may block
152 wait for disk etc.
Why threads? www.tugraz.at
Things should happen in parallel - even within one application Example: text processing typing spell checking formatting on screen automatically saving Some of these things may block wait for mouse-click / keyboard press
152 etc.
Why threads? www.tugraz.at
Things should happen in parallel - even within one application Example: text processing typing spell checking formatting on screen automatically saving Some of these things may block wait for mouse-click / keyboard press wait for disk
152 Why threads? www.tugraz.at
Things should happen in parallel - even within one application Example: text processing typing spell checking formatting on screen automatically saving Some of these things may block wait for mouse-click / keyboard press wait for disk etc.
152 Consumes less memory Attention: do not confuse shared memory (between processes) with shared address space (between threads)
No need to reconfigure memory
Split tasks in different blocks Like with processes But they cooperate easily because of the shared address space
Switching between threads can be faster
May achieve better performance
Why threads www.tugraz.at
Make programming easier
153 Consumes less memory Attention: do not confuse shared memory (between processes) with shared address space (between threads)
No need to reconfigure memory
Like with processes But they cooperate easily because of the shared address space
Switching between threads can be faster
May achieve better performance
Why threads www.tugraz.at
Make programming easier Split tasks in different blocks
153 Consumes less memory Attention: do not confuse shared memory (between processes) with shared address space (between threads)
No need to reconfigure memory
But they cooperate easily because of the shared address space
Switching between threads can be faster
May achieve better performance
Why threads www.tugraz.at
Make programming easier Split tasks in different blocks Like with processes
153 No need to reconfigure memory
Consumes less memory Attention: do not confuse shared memory (between processes) with shared address space (between threads) Switching between threads can be faster
May achieve better performance
Why threads www.tugraz.at
Make programming easier Split tasks in different blocks Like with processes But they cooperate easily because of the shared address space
153 No need to reconfigure memory
Attention: do not confuse shared memory (between processes) with shared address space (between threads) Switching between threads can be faster
May achieve better performance
Why threads www.tugraz.at
Make programming easier Split tasks in different blocks Like with processes But they cooperate easily because of the shared address space Consumes less memory
153 No need to reconfigure memory
Switching between threads can be faster
May achieve better performance
Why threads www.tugraz.at
Make programming easier Split tasks in different blocks Like with processes But they cooperate easily because of the shared address space Consumes less memory Attention: do not confuse shared memory (between processes) with shared address space (between threads)
153 No need to reconfigure memory May achieve better performance
Why threads www.tugraz.at
Make programming easier Split tasks in different blocks Like with processes But they cooperate easily because of the shared address space Consumes less memory Attention: do not confuse shared memory (between processes) with shared address space (between threads) Switching between threads can be faster
153 May achieve better performance
Why threads www.tugraz.at
Make programming easier Split tasks in different blocks Like with processes But they cooperate easily because of the shared address space Consumes less memory Attention: do not confuse shared memory (between processes) with shared address space (between threads) Switching between threads can be faster No need to reconfigure memory
153 Why threads www.tugraz.at
Make programming easier Split tasks in different blocks Like with processes But they cooperate easily because of the shared address space Consumes less memory Attention: do not confuse shared memory (between processes) with shared address space (between threads) Switching between threads can be faster No need to reconfigure memory May achieve better performance
153 Example www.tugraz.at
154 Example www.tugraz.at
while (TRUE) { get_next_request(&buf); handoff_work(&buf); }
while (TRUE) { wait_for_work(&buf); look_for_page_in_cache(&buf,&page); if (page_not_in_cache(&page)) read_page_from_disk(&buf,&page); return_page(&page); }
155 complicated program structure read content from disk may block process non-blocking read (polling!) decreases performance
Without Threads www.tugraz.at
Without threads,
just one thread
156 read content from disk may block process non-blocking read (polling!) decreases performance
Without Threads www.tugraz.at
Without threads,
just one thread complicated program structure
156 non-blocking read (polling!) decreases performance
Without Threads www.tugraz.at
Without threads,
just one thread complicated program structure read content from disk may block process
156 Without Threads www.tugraz.at
Without threads,
just one thread complicated program structure read content from disk may block process non-blocking read (polling!) decreases performance
156 Non-Blocking Read www.tugraz.at
while (TRUE){ // VERY simplified get_next_event(&buf); if (is_request_event(&buf)) { if (page_not_in_cache(&page)) { request_page_from_disk(&buf,&page); save_request_in_table(&buf); } else { return_page(&page); } } else if (is_disk_event(&buf)) { find_request_in_table(&buf); mark_requeust_as_done(&buf); return_page(&page); } else if (is_...
157 Actually simulates threads Better: use multithreading
Non-Blocking Read www.tugraz.at
Finite-state-machine!
158 Better: use multithreading
Non-Blocking Read www.tugraz.at
Finite-state-machine! Actually simulates threads
158 Non-Blocking Read www.tugraz.at
Finite-state-machine! Actually simulates threads Better: use multithreading
158 for the hardware: there is only 1 thread and a lot of interrupts for the userspace: we can have an arbitrary number of threads
Threads divide processor time amongst themsevles (and a few resources) Building block of modern multi-threading are context switches Operating system creates illusions
Take Aways www.tugraz.at
Processes divide resources amongst themselves (except processor time)
159 for the hardware: there is only 1 thread and a lot of interrupts for the userspace: we can have an arbitrary number of threads
Building block of modern multi-threading are context switches Operating system creates illusions
Take Aways www.tugraz.at
Processes divide resources amongst themselves (except processor time) Threads divide processor time amongst themsevles (and a few resources)
159 for the hardware: there is only 1 thread and a lot of interrupts for the userspace: we can have an arbitrary number of threads
Operating system creates illusions
Take Aways www.tugraz.at
Processes divide resources amongst themselves (except processor time) Threads divide processor time amongst themsevles (and a few resources) Building block of modern multi-threading are context switches
159 for the hardware: there is only 1 thread and a lot of interrupts for the userspace: we can have an arbitrary number of threads
Take Aways www.tugraz.at
Processes divide resources amongst themselves (except processor time) Threads divide processor time amongst themsevles (and a few resources) Building block of modern multi-threading are context switches Operating system creates illusions
159 for the userspace: we can have an arbitrary number of threads
Take Aways www.tugraz.at
Processes divide resources amongst themselves (except processor time) Threads divide processor time amongst themsevles (and a few resources) Building block of modern multi-threading are context switches Operating system creates illusions for the hardware: there is only 1 thread and a lot of interrupts
159 Take Aways www.tugraz.at
Processes divide resources amongst themselves (except processor time) Threads divide processor time amongst themsevles (and a few resources) Building block of modern multi-threading are context switches Operating system creates illusions for the hardware: there is only 1 thread and a lot of interrupts for the userspace: we can have an arbitrary number of threads
159
Bibliography www.tugraz.at
[1] Edsger Dijkstra. The structure of the multiprogramming system. Communications of the ACM, 1968. [2] Thomas Haigh. Multicians.org and the history of operating systems. online, 9 2002. URL http://www.cbi.umn.edu/iterations/haigh.html. [3] Per Brinch Hansen. Classic Operating Systems: From Batch Processing to Distributed Systems. Springer, 2001. [4] Tom Kilburn, Bruce Payne, and David Howarth. The atlas supervisor. AFIPS Computer Conference 20, 1961. in [Hansen 2001]. [5] Emerson Pugh, Lyle Johnson, and John Palmer. IBM’s 360 and Early 370 Systems (History of Computing). The MIT Press, 2003.
160