0% found this document useful (0 votes)
3 views

Chapter 02

The document provides an overview of computer systems and operating systems, detailing their structure, components, and functions. It explains the role of the operating system as an intermediary between applications and hardware, the execution modes of applications, and the organization of memory. Additionally, it covers CPU operations, instruction cycles, and the concept of context switching in multi-core CPUs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 02

The document provides an overview of computer systems and operating systems, detailing their structure, components, and functions. It explains the role of the operating system as an intermediary between applications and hardware, the execution modes of applications, and the organization of memory. Additionally, it covers CPU operations, instruction cycles, and the concept of context switching in multi-core CPUs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

1

Computer System & Operating System


2

 Computer system & Hardware


 Computer system & operating system
 Kernel & System call
 Operating system & Interrupt
Lecture Objectives

1. Understand the core structure and operating principles of hardware in a


computer system.
2. Recognize the position and role of the operating system within a
computer system and comprehend its overall functionality.
3. Gain a detailed understanding of system calls and interrupts, which the
operating system provides as an intermediary between applications and
hardware.
4. Understand the two execution modes of an application: user mode and
kernel mode, as well as the purpose of these modes.
5. Learn how the operating system divides memory space into user space
and kernel space for efficient utilization.
6. Fully grasp the concept and reality of the operating system kernel.

3
4 1. Computer System & Hardware
Layers Comprising a Computer System
5
Scope of a Computer System
6

 Layers of a Computer System


 Application Layer
 Operating System Layer
 Computer Hardware Layer
 Characteristics of the Layered Structure of a Computer System
 Users utilize computers through applications and GUI/tool programs
(tools/utilities).
 All hardware is under the exclusive and monopolistic control of the
operating system.
 Users and applications are not allowed direct access to hardware.
 Access must be made through the operating system.
 Functions of the Operating System in a Layered Structure
 Enables users to use computers without knowledge of hardware.
 Acts as an intermediary between applications and hardware.
 Interfaces with applications above and hardware below.
Computer Hardware Components
7
Explanation of Computer Hardware (1)
8

 CPU (Central Processing Unit)


 The central processing unit that interprets and executes program code (machine instructions).
 The most essential component of a computer.
 Starts operating when power is supplied and executes programs loaded into memory.
 Memory
 A space where program code and data executed by the CPU are loaded.
 Semiconductor memory (RAM).
 A program must be loaded into memory to be executed.
 Cache Memory
 Background
 The processing speed of the CPU has advanced much faster than memory speed, leading to increased CPU
wait times due to slow memory.
 To enhance CPU execution speed, a small amount of high-speed (and expensive) memory was installed
between the CPU and memory.
 Types of Cache Memory
 On-chip cache – Cache built inside the CPU; most modern CPUs use on-chip cache.
 Off-chip cache – Cache installed externally from the CPU.
 Cache Memory Operation
 When cache memory is present, the CPU executes programs only from the cache.
 Programs and data must first be loaded into memory and then moved to the cache.
 Since cache memory has limited capacity, it stores only a small portion of the currently executing code
and data.
Explanation of Computer Hardware (2)
9

 Devices
 Includes keyboard, printer, scanner, etc.
 Bus
 A term used to describe a bundle of multiple lines through which digital signals (0s
and 1s) pass, enabling hardware components to exchange data.
 Analogy
 Computer bus: Road
 Computer data: Vehicles traveling on the road
 Types of Buses (Based on the Information They Carry)
 Address Bus – A bus (road) that carries address signals.
 Data Bus – A bus (road) that carries data signals.
 Control Bus – A bus (road) that carries control signals.
 Address
 Refers to the location of storage (registers) within memory, input/output devices, or storage
devices.
 Starts at address 0 and increases positively.
 The address bus is a bundle of multiple lines through which address values are transmitted.
 When the CPU reads or writes data from/to memory or an input/output device, it must
generate an address.
Explanation of Computer Hardware (3)
10

 Classification of Buses by Purpose


 System Bus
 Transfers data between high-speed hardware components such as the CPU,
cache memory, and main memory.
 Can be compared to a highway.
 I/O Bus
 Transfers input/output data from relatively slower input/output devices.
 Can be compared to a regular road.
 I/O Controllers & Control Circuits
 Various hardware components that control input/output devices.
 Issue commands to input/output devices.
 Mediate data transfer between memory and I/O devices or between the CPU and I/O devices.
 Includes components such as DMAC (Direct Memory Access Controller) and Interrupt
Controller (INTC).
The structure of a modern PC
11
Relationship between CPU and memory
12

 CPU
 Active component. Address is generated when accessing memory
 What is a 32-bit CPU, 32-bit operating system, and 32-bit computer?
1) CPU has 32 address lines
 CPU access range: 232 different addresses (0 to 232-1)
 Maximum memory size that CPU can access: 4GB
 Since each address is 1 byte, 232 addresses = 232 bytes = 4GB
• 210 = 1KB
• 220 = 210x210 = 1MB
• 230 = 220x210 = 1GB
• 232 = 22x230 = 4x1GB = 4GB

 When installing more than 4GB of memory in a computer with a 32-bit CPU
 Areas exceeding 4GB cannot be used
2) CPU has 32 data lines for input/output
 32 bits can be read and written at a time (32 bits are 4 addresses)
Address lines, data lines, and memory of a 32-bit CPU
13
CPU machine instructions
14

 CPU instructions
 Machine instructions that the CPU can interpret and execute
 Different from the program source code of the C language or Java
 The company that designs the CPU determines the instructions, number of
instructions, and formats
 The number of CPU instructions ranges from tens to hundreds
 The instruction names, machine codes, sizes, and numbers are different for each CPU
 No compatibility of instructions between CPUs
 Since the machine language of a C program varies depending on which CPU it is compiled
for, the compiled codeis not compatible between CPUs
 CPU instruction examples

어셈블리어 명령 기계 명령
mov ecx, 51 ; b9 33 00 00 00 ecx 레지스터에 51 저장
add ax, 8 ; 83 c4 08 ax 레지스터에 8 더하기
push ebp ; 55 ebp 레지스터의 값을 스택에 저장
call _printf ; e8 00 00 00 00 _printf 함수 호출
ret 0 ; c3 이 함수를 호출한 곳으로 리턴(0 값과 함께)
#include <stdio.h>
_main PROC ; COMDAT
컴파일된 어셈블리어
기계 명령들 명령들 int main() {
; 3 : int main() { int n = 10;
논리 주소 printf("hello");
00000 55 push ebp
00001 8b ec mov ebp, esp }
00003 81 ec cc 00 00 00 sub esp, 204 ; 000000ccH
00009 53 push ebx
CPU가 처리 0000a 56 push esi
하는 명령 0000b 57 push edi
0000c 8d bd 34 ff ff ff lea edi, DWORD PTR [ebp-204]
00012 b9 33 00 00 00 mov ecx, 51 ; 00000033H
00017 b8 cc cc cc cc mov eax, -858993460 ; ccccccccH
0001c f3 ab rep stosd

; 4 : int n = 10;

0001e c7 45 f8 0a 00 00 00 mov DWORD PTR _n$[ebp], 10 ; 0000000aH

; 5 : printf("hello");
hello.c를 비주얼
00025 68 00 00 00 00 push OFFSET ??_C@_05CJBACGMB@hello?$AA@ 스튜디오에서
0002a e8 00 00 00 00 call _printf
컴파일한 코드
0002f 83 c4 04 add esp, 4

; 6 : }

00032 33 c0 xor eax, eax


00034 5f pop edi
00035 5e pop esi
00036 5b pop ebx
00037 81 c4 cc 00 00 00 add esp, 204 ; 000000ccH
0003d 3b ec cmp ebp, esp
0003f e8 00 00 00 00 call __RTC_CheckEsp
00044 8b e5 mov esp, ebp
00046 5d pop ebp
00047 c3 ret 0

_main ENDP
15
The Life of a CPU – Instruction Processing Process
16

 CPU registers
 PC(Program Counter) - Stores the memory address of the next instruction to be executed
 IR(Instruction Register) - Stores the instruction read from memory for the current execution
 SP(Stack Pointer) - Stores the top memory address of the stack
 Data registers - Stores data used or to be used in operations
 Status register - Stores control information such as CPU status information or interrupt disable
 Other registers - Registers pointing to the memory address where the page table is stored, etc.
 CPU instruction cycle - The life of a CPU
 The process by which a CPU executes a single instruction. The CPU simply repeats the instruction cycle after
the power is turned on
 Instruction cycle example: Case of executing the next instruction stored at memory address 100
mov eax, [300] ; 메모리 300 번지의 값을 읽어 eax 레지스터에 저장

1) The CPU loads the address (100) pointed to by the PC register onto the address bus.
2) The memory loads the data (mov eax, [300]) stored at address 100 onto the data bus.
3) The CPU stores the binary values contained in the data bus into the IR register. It modifies the PC to the next
address.
4) The CPU loads the address (300) of the data onto the address bus to read the data required for the operation.
5) The memory loads 50 stored at address 300 onto the data bus.
6) The CPU stores 50 from the data bus into the temporary data register.
7) Now, the CPU interprets the command and executes it. As a result of the command execution, 50 is stored in the
eax register.
CPU Instruction Cycle - The process by which the CPU executes
instructions - Understanding the relationship between the CPU and
memory
17
Where is the Stack?
18

 4 spaces allocated by the operating system for a program to run


 Code space - Program code is loaded
 Data space - Space where global variables are loaded
 Heap space - Space dynamically allocated by the program
 Stack space - Stores parameters, local variables, etc. when a function is
called
 Stack
 Space allocated to use part of the memory as a stack
 There is no separate hardware memory called stack
 The operating system allocates stack space to each program
 The CPU's SP register points to the top of the stack address of the program
currently being executed by the CPU
 Contents stored in the stack
 Local variables of the function
 Parameter values passed when the function is called
 Address to return to after the function is executed
 Values that the function intentionally stores
Stack & Memory
19

The stack is a portion of memory allocated to each program by the operating system.
Context
20

 Context
 All the situation or situation information while a program is running
 Memory
 Program code and data, stack, dynamically allocated stored values
 CPU register values
 PC contains the address of the code
 SP contains the address of the stack
 Other registers contain the results of previous execution or data used in the current execution
 Reduced definition
 The values of the registers currently in the CPU
 The situation information stored in the memory remains the same
 Context switching
 Occurrence
 When the CPU stops executing the current program and executes another program
 Process
 The context (values of the CPU registers) of the currently executing program is stored in the
memory
 The saved context (values of the CPU registers) of the program to be newly executed is
returned to the CPU
Context Case of Program A
21
Context switching from program A to program B
22
Multi-core CPU
23

 Developed multi-core CPU called PowerPC by IBM in 2001


 Contains 2 processors inside CPU
 Runs 2 programs simultaneously
 Core is a perfect processor (CPU in the past)
2. Hierarchical structure of computer
24
systems and operating system interfaces
Computer System Hierarchy
25

 Computer System Layers


 User
 Application Programs
 Operating System
 Kernel Code
 Device Drivers
 Hardware
Why Computer Systems Are Designed Hierarchically
26

 In order to secure independence between layers


 User
 Use the computer as an application program without knowing about the operating
system or hardware
 Application program
 Can be developed without knowing the type, structure, or control method of
computer hardware
 For example
 Write a program without knowing the CPU size or memory size
 Write a file input/output program without knowing whether the storage device is a hard disk or
SSD, the size of the storage device, or the number of disk heads
 Request and resolve to the operating system
 No need to rewrite the application program even if the computer hardware
changes
 Operating system
 The operating system requests all device-related tasks to the device driver
 Interface between the application program and the hardware
Why do we need an operating system?
27

 Without an operating system,


 Applications or users must directly control the hardware.
 Knowledge of hardware is required, and conflicts, management, and security issues occur.
 Examples
 When two people want to run a program at the same time, and another person wants to
run a program while another program is already running, who will schedule the two
applications? Process management
 When an application needs memory, who will manage it by dividing it into unused and
used memory, and reclaiming the used memory when the application terminates?
Memory management
 When two users print to a printer at the same time, who will prevent conflicts in device
usage? Device management
 When writing data to a file, who will decide where on the hard disk to write it, and who
will prevent another application from overwriting the disk location that I wrote it to? File
system management
 When a key is entered on the keyboard, who will decide which of the many running
applications will transmit the key? Input/Output Management
 The Need for an Operating System
 Resolving conflicts over resources, optimizing performance, and improving user
efficiency in using the system
Comparing Banks Without Employees and Banks With
Employees
28

If there is no bank employee If there is a bank employee


고 고 고
객 객 객
고 고
객 객
고 고 고 고
객 객 객 객


돈세는 기 객 직원
계를 서로
송 대 적
사용하려 금고 금 출 금
고 충돌




객 인쇄 금고
송금
• Customer: Application program
inefficiency, errors due to crashes, delays, • Employee: Various functions of the operating system
security vulnerabilities, chaos!!! (kernel functions)

Efficiency, conflict resolution, enhanced security, order

• User mode: Area where customers work


• Kernel mode: Area where employees work
Relationship between operating system and
application programs
29

 Application programs
 Word, web browser, etc., various programs written for users to utilize
the computer
 The role of the operating system for application programs
 Prevents application programs from directly handling hardware
 The operating system completely monopolizes the hardware
 Reason: To prevent hardware usage conflicts between application programs
 When an application program wants to use hardware
 It must request the operating system -> The operating system manipulates
the hardware on its behalf
 The only way to make a request - system call
 Interface between application programs and hardware
 Controls the execution order of application programs
 Relays communication between application programs
Relationship between operating system and
users
30

 Users utilize the computer through applications


 Explorer, Notepad, etc.
 The role of the operating system for users
 Make it easy for users to use the computer even if they do not have
knowledge about hardware
 Help users install or change hardware
 Provide a convenient interface for users to use the computer system
 UI, mouse, voice commands, etc.
 Provide various tool applications (utilities) that help use the computer
 Explorer and Task Manager in Windows
 Shell in Linux
 User account management
 Calculating users' computer usage time, processing billing, etc.
Relationship between operating system and hardware
31

 Controlling the hardware is entirely the responsibility of the


operating system
 printf(“hello”) in the application
 The operating system prints “hello” on the display device
 scanf() in the application
 The operating system receives characters from the keyboard
 The operating system
 An intermediary between the user/application and the hardware
 Hardware control is entirely the function of the operating system
 Reading or writing files from the hard disk
 Clicking the mouse
 Receiving keyboard input
 Sending or receiving data over the network
 Outputting text, images, graphics, etc. on the display
Full functionality of the operating system
32

 Process and Thread Management


 Execution, suspension, termination of processes/threads scheduling, context switching,
synchronization
 Memory Management
 Allocate memory to processes or threads, return memory, protect memory from other
processes/threads
 Virtual memory technology that extends memory to the hard disk area
 File Management or File System Management
 Create, save, read, copy, delete, move files, protect files
 Device Management
 Control input/output devices such as keyboard, mouse, printer, storage devices such as hard disks
 Input/Output
 User Interface
 Provide line-based command input/output window, mouse, and graphical GUI interface
 Networking
 Network awareness, connection, closing, data transmission/reception
 Protection and Security
 Protection from external attacks or unauthorized intrusions such as viruses, worms, malware, and
hacking
Components and Kernel of the Operating System
33
Operating system configuration
34

 Operating system = Kernel + Tool + Device driver


 Kernel
 Core part of the operating system, operating system in a narrow sense
 Code and data that reside in memory after booting
 Implements all core functions of the operating system
 Code and data structures that directly control and manage computer resources such as CPU,
memory, and MMU
 Kernel code is a collection of functions
 To use kernel functions, application programs must use system calls
 Tool software and GUI
 Tool software or tool application programs provided to enable users to conveniently use the
computer
 In the case of Windows, desktop GUI, explorer, command window, task manager, control panel,
etc.
 In the case of Linux, shell, login program
 Device driver
 Software that directly controls devices and inputs and outputs data
 There is a dedicated device driver for each device
 Generally written and distributed by the device manufacturer
 Cases
 Keyboard driver, disk driver, SCSI driver, mouse driver, graphic driver, network driver, USB driver, etc.
Tool Software Cases - Task Manager, Disk Cleanup Tool
35
Operating System Kernel Interface: System Calls and
Interrupts
36

 Two interfaces provided by the kernel: system calls and interrupts


 Acts as an intermediary between applications and hardware
 System calls
 Interface between the kernel and applications
 The only way for applications to use kernel functions
 Provides various system call functions through the system call library
 System call libraries are included in the operating system package
 Examples: reading files, allocating memory, viewing process information,
creating processes, etc.
 System call functions such as open(), close(), read(), write(), fork(), exit(), wait(), etc.

What is a standard library?


• Code with complex functions pre-written to make it easy to write applications
• Examples) printf(), abs(), strcmp(), etc.
• Tasks unrelated to the functions of the operating system kernel
• Application programs use standard library functions as function calls
Operating System Kernel Interface - Interrupts
37

 Interrupt
 Interface between kernel and hardware devices
 Hardware method for devices to notify CPU of I/O completion, timer
completion, etc.
 Hardware signals to notify interrupts are directly transmitted to CPU
 When an interrupt occurs
 The CPU stops what it is doing and executes an interrupt service routine
 Interrupt service routines are mostly located in device drivers
 For example, when a key is entered, the kernel executes a keyboard interrupt service routine, reads
the key, and stores it in the kernel buffer
 Interrupt service routines are loaded into the kernel area
 When the interrupt service routine is finished executing, the work being done
continues
 Interrupt utilization
 Completion of I/O tasks instructed by the operating system to the device, arrival
of unexpected network data, keyboard or mouse input, low battery warning, etc.
38 3. Kernel & System Call
Resource access issues in application
39

 Today's operating systems are multiprogramming operating systems


 Multiple applications can run simultaneously on one computer
 Problems
 If an application directly accesses computer resources, it can cause crashes and damage
 Memory loaded by other applications can be damaged
 Files created by other applications can be deleted and damaged
 Applications can damage areas loaded by the kernel
  Solutions
 Applications are not allowed to access resources
 All access to resources is granted only to the kernel
 Specific solutions
1) Separate memory space into user space and kernel space
 Applications are loaded into user space, and kernels are loaded only into kernel space
2) Separate CPU execution modes into user mode and kernel mode
 Applications are executed only in user mode, and kernel code is executed only in kernel mode
 To prevent user space from directly accessing code in kernel space
 Applications are forcibly terminated if they access kernel code in user mode
3) When an application wants to use kernel functions, use kernel code only through system
calls
User space and kernel space
40

 The operating system divides the computer memory into two spaces
 User space: Space shared by all application programs
  Space where application programs are loaded
 Kernel space: Space that only the kernel can use
 Space exclusively used by the kernel, such as kernel code and kernel data
 Includes device drivers

 Reason for separation


 To protect kernel code and data from malicious applications or coding mistakes
What does user space size mean?
41

 User space size


 Determining the maximum size of an application
 Program code + data (global variables) + heap (dynamic allocation) + stack
combined size
 Example) 2GB of user space in a 32-bit Windows operating system ->
Applications cannot be developed larger than 2GB

 Address range of user space


 Applications cannot exceed the address range of the user space set by
the operating system
 Example) In a 32-bit Windows operating system,
If an application accesses an address beyond the range of 0~7FFFFFFF,
it is immediately terminated (serious error)
Address space is a virtual address space
42

• Address space = User space + Kernel space


• Address space is virtual address space
- Independent of the address range of physical memory
• Virtual address space
- Address range from the user or application's perspective
- User thinks he is using all memory
• Each application
- Has 2GB of user address space
- Up to 2GB of user code and data
- Illusion of exclusive use of 2GB of memory from 0 to
7FFFFFFF
• Kernel space - Address range from 2GB to 4GB-1
- Address space in the range of 80000000~FFFFFFFF
- All applications share kernel space

• 2 questions
- User space conflicts between applications?
- What if the actual physical memory is less than
4GB?
Solution to two questions
43

 (Resolving conflicts in user space) Mapping virtual address space to physical


memory
 Mapping the virtual address space of each application to the physical address space
 The mapping table is owned and managed by the operating system
 The physical memory is divided and used by the user spaces of multiple applications
 In reality, each application uses only a part of the user space
 Kernel space is also mapped to physical memory
 Recorded in the mapping table of each application
 The mapping table part for the kernel space is the same for all applications

 Resolution for cases where physical memory is small) When physical memory is
insufficient,
 the operating system stores physical memory on the hard disk to secure empty areas of physical
memory (virtual memory technique)
Mapping of physical memory to virtual address space to avoid virtual address space conflicts

44
User mode and kernel mode
45

 CPU runs in one of two modes: user mode and kernel mode
 There is a ‘mode register’ inside the CPU that indicates the mode status
 User mode
 CPU mode bit = 1
 CPU is accessing code or data in user space
 CPU is not allowed to access kernel space -> protects kernel area from
application programs
 Privileged instructions are not allowed to be executed
 Privileged instructions – special instructions designed to process hardware such as
input/output devices or system-related processing such as system interrupts

 Kernel mode (supervisor mode)


 CPU mode bit = 0
 CPU is executing in kernel space or executing user code
 Privileged instructions can be used
Memory access in user mode and kernel mode
46
Switching from user mode to kernel mode
47

 When switching from user mode to kernel mode


 Only 2 cases - system call and interrupt occurrence

 System call
 Proceeded by a special machine instruction that executes a system call
 Ex) int 0x80/sysenter/trap/syscall, etc. are different for each CPU
 Machine instruction switches the CPU's mode bit to kernel mode
 Interrupt
 When the CPU receives an interrupt, it automatically switches to kernel
mode
 Because the interrupt service routine is in kernel space
 The CPU executes the interrupt service routine
 When the interrupt service routine is finished, the CPU automatically
switches to user mode
Switching from user mode to kernel mode with a system call
48
Comparison of user mode and kernel mode
49
Privilege Command
50

 Privileged Instructions
 CPU instructions designed for special purposes such as input/output (I/O) from
input/output devices, system shutdown, context switching, and interrupt suppression
 Executed only in kernel mode
 Types of privileged instructions
 I/O instructions
 Hardware control and input/output from devices
 Example) in eax, 300 ; Read value from I/O port address 300 and store it in eax register
out 301, eax ; Write value in eax register to I/O port address 301
 Halt instruction
 Instruction that stops CPU operation. Makes CPU idle
 Instruction that turns interrupt flag on and off
 Controls interrupt flag bits in CPU to instruct CPU to allow or ignore interrupts
 Example) cli/sti instructions
 Timer setting instructions
 Context switching instructions
 Memory clearing instructions
 Device status table modification instructions, etc.
Quiz - Understanding Privilege Commands
51

 Q. Which of the following commands is a privileged command? Explain


why.

 1) Command to switch from user mode to kernel mode


 Not a privileged command.
 Because it is a command that must be allowed to all applications for system calls.
 2) Read clock
 Not a privileged command.
 Because all applications must be able to read the clock.
 3) Clear memory in virtual memory
 Not a privileged command.
 A program clears its own memory without invading the area of other processes.
 4) Disable interrupts
 This is a privileged command.
 The act of turning off interrupts is the act of turning off the interrupt flag(IF) inside the CPU.
When interrupts are turned off, the CPU does not check for interrupts even if they occur
externally. When a program turns off interrupts, the CPU will remain in a state where
interrupts are turned off, and will not receive interrupts even if the CPU is executing other
programs. Since the CPU cannot be monopolized by a single program, this instruction is a
privileged instruction and cannot be executed by an application program.
Various issues related to execution mode
52

1) Are user mode and kernel mode implemented by the CPU or the operating system?
 Mode is implemented by the CPU and is utilized by the operating system
 There is a register inside the CPU that indicates the mode
 The operating system protects the kernel area using the CPU mode register
2) Why does the operating system operate in user mode and kernel mode?
 Security and protection of kernel space (kernel code and data)
 Protects kernel space from malicious users and error programs
 No matter how serious an error occurs in user mode, only the user program is terminated.
The system cannot be stopped
3) Do user applications ever call kernel code?
 User applications cannot directly call kernel code
 Only through system calls
4) In which mode does the CPU run more, kernel mode or user mode?
 When looking at the overall system statistics, it runs more in kernel mode
 If there are many cases of reading from the keyboard, display output, disk or network
operations, etc., the kernel mode time ratio is high
 This is because the system idle process that runs when there is no work is run in kernel
mode
View time spent in kernel mode out of total CPU
usage on Windows
53

전체 CPU 시간

커널 모드 시간
(진한 부분)

The main reason for the high percentage of time in kernel mode is that the system idle processes
run in kernel mode when no work is being done.
View CPU usage of system idle processes with Task
Manager
54

선택
The Reality of the Kernel (1)
55

 Kernel is a set of functions and data loaded into the kernel space at boot time
 Kernel is a compiled binary form, stored in a specific area of the hard disk, and loaded into the memory of the
kernel space at boot time
 Kernel code is a set of functions
 Existence of kernel - a set of functions and data executed in kernel mode

Who is currently executing kernel code? It's the app2 process. There is no such thing as a kernel process. The kernel is not a process..
The Reality of the Kernel (2)
56

 Is the kernel a self-executing process? NO


 The kernel is a simple set of functions, functions called through system calls
 The kernel schedules (x)
 As the kernel process runs, it periodically schedules (x)
 The scheduler function in the kernel is called and executed by the system call and interrupt service routine
(0)
 Is the kernel running? NO
 The kernel is neither a process nor a thread, so NO
 The kernel is running (x)
 An application program makes a system call and executes kernel code (0)
 An interrupt occurs and the interrupt service routine is executed (0)
 Does the kernel have a stack or a heap? NO
 The kernel does not have a stack or a heap. Therefore, NO
 The entity that has the stack or heap is a process or thread
 Refer to textbook P.75, P.134, P.205
 Each thread has a user stack and a kernel stack
 When a thread is created, a user stack is allocated to the user space of the process
 It is used while the user code is running
 When a thread is created, a kernel stack is allocated to the kernel space
 It is used as a stack when the thread executes kernel code through a system call
Applications
57

 Library
 Pre-written functions to be used in applications, Files provided in compiled
binary form
 Developers cannot write applications without using libraries

 There are two types of libraries used by applications


 Standard Library
 Provides functions that are difficult for users to write
 Same name and usage regardless of the operating system or computer hardware
 Compatible regardless of the operating system, hardware, or compiler
 System Call Library
 Contains system call functions
 System call functions perform a system call, change to kernel mode, enter the
kernel, and execute functions created in the kernel (perform various kernel
functions)
 The names of system call functions are different for each operating system
 Incompatible with the operating system
 System call functions are called kernel API (Application Programming Interface)
Linking user code and library code
58

 Process of creating an executable file


 Application code is linked with library code to create an executable file
 Application execution
 Application is loaded into user space
 Memory loading of user code and library code in executable file
 Memory loading of both user global variables and library global variables in
executable file
 Application starts execution in user mode
 Case) Next slide
User code, libraries, and kernel that make up the application
59
Function calls and system calls
60

 Function call usees library


 Function loaded in user space calls other functions loaded in user space (including functions in
standard library or system call library)
 Execution in user space, user mode
 Function call process
 Address to return to stack in user space, passing parameters, creating local variables of called
function
 Jump to address of function loaded in user space
 Return to the place where function was called when function is finished
 Kernel code execution with system call
 When application wants to use function of operating system, execute function written in kernel
 System call function included in system call library causes system call
 System call process
 Execution of special machine instruction causing system call
 This instruction switches from user mode to kernel mode, passing unique number assigned to each
kernel function
 Execution of kernel system call handler
 Analysis of unique number of kernel function passed by system call handler, calling corresponding
kernel function
 Switches to user mode when kernel function returns, returns to user program
Examples of calling libraries and kernel code from
applications
61
System call
62

 System call
 The process of requesting kernel services from user space code
 The process of user space code calling kernel functions
 Also called kernel call, trap
 Functions created to allow applications to utilize kernel functions
 The operating system provides a system call library
 Contains system call functions or kernel APIs
 Kernel APIs of Unix/Linux – open(), read(), write(), fork(), exit()
 Kernel APIs of Windows – CreateProcess(), WaitForSingleObject()
 There are approximately 200 or more system call functions
 Machine instructions that cause system calls
 Each CPU provides a special machine instruction that executes a system call
 System call CPU instructions
 Examples
 int 0x80 - Intel's x86 series CPUs, used in 32-bit
 syscall/sysret - First implemented in ADM 64-bit only
 sysenter/sysexit - Originally implemented by Intel, X86/64 CPUs, AMD
 System calls made indirectly through the standard library
 Application -> System call library's system call function -> System call CPU instruction
 Application -> Standard library function -> System call library's system call function -> System call CPU
instruction
The process in which
a system call occurs
by the read() function
Exploration 2-1: Does printf() output directly to
the display?
64
The printf() function is a standard library function.
Will calling the printf() function result in a system call?
• Only the kernel can access the display
• The printf() function cannot output directly to the display
• printf() outputs to the buffer in the C standard library
• If the buffer is full, printf() calls the system call function write()
• The write() function executes a ‘system call CPU instruction’
• A function written in the kernel outputs “hello” to the display
Exploration 2-2 Writing system call code using syscall
machine instruction
65

This is an example of making a system call directly using the syscall machine instruction using assembly language in Linux.
hello.s
$ gcc -c hello.s && ld hello.o # 화면에 "Hello, World"를 출력하는 어셈블리어 프로그램으로 hello.s에 저장
$ ./a.out # 64-bit 리눅스에서 실행
Hello world #
$ # 프로그램 시작
.global _start
.text Start running the program
_start:
# write(1, msg, 12) 시스템 호출, 화면 출력
mov $1, %rax # 1은 write 시스템 호출 번호, rax 레지스터에 저장
mov $1, %rdi # 1은 표준출력장치(디스플레이)의 파일 디스크립터 번호
mov $msg, %rsi # msg는 출력할 문자열의 주소
mov $12, %rdx # 12는 출력할 바이트 수
System call requesting syscall # 시스템 호출 기계 명령
screen output # 화면에 Hello world를 출력하는 write 시스템 호출 실행

# exit(0) 시스템 호출, 프로그램 종료


mov $60, %rax # 60은 exit 시스템 호출 번호
xor %rdi, %rdi # xor 명령 후 rdi 레지스터 값은 0이됨. 0은 종료 코드
System call requesting syscall # 시스템 호출 기계 명령
program termination
# 프로그램을 종료시키는 exit 시스템 호출 실행
msg:
.ascii "Hello world\n"
System call cost: fread() vs. read()
66

 System calls are more time-consuming than function calls


 The more system calls you make, the slower the program execution speed
 Two types of code that read 1000 bytes from a file. What are the execution comparison
results?
char buf[100]; char buf[100];
… …
for(i=1;i<=10; i++) vs. for(i=1;i<=10; i++)
fread(fp, buf, 100); read(fd, buf, 100);

C 표준 함수 fread() 사용. 시스템 호출 함수 read() 사용.


1번의 시스템 호출. 속도 빠름 10번의 시스템 호출. 느리고 비효율적

 Comparison of execution of the standard C library function fread() and the system call
read()
 The operation process of the standard C library function, fread(fp, buf, size)
 When fread() is called for the first time, the buffer in the library is empty
 Call read() to fill the buffer in the library. n = read(fd, buf, BLKSIZE);
 Copy the size requested by the application to the application's buf
 If the library buffer is empty or insufficient, then call read() again
 The operation process of the system call function, read(fd, buf, size)
 Executing kernel code using a system call
 Reading disk from kernel code
 Reading directly into buf without going through the library
Comparison of the operation process of fread
and read()

100
바이트
읽기
요청
4KB
읽기
요청

67
Comparison of time measurements of fread()
and read()
68

(출처 : http://arkanis.de/weblog/2017-01-05-measurements-of-system-call-performance-and-overhead의 그래프를 저자가 축소)

Results Analysis: fread() is about 8 times faster than read()


Cost summary for system calls
69

 The cost of a system call is very high


Save data to be passed to the system call function in the CPU registers
-> Switch from user mode to kernel mode
-> Execute the system call handler
-> Save on the stack to prevent the CPU's registers from being damaged
-> Find the system call function in the system call table
-> Execute the system call function
-> Restore the registers saved on the stack
-> Return to user mode
 System calls are inevitable, but if the number of system calls is reduced,
the application's execution time will be shortened, and the system will have
more time to execute programs -> Improve the system's processing rate
70 4. Operating System and Interrupts
Interrupt
71

 Interrupt
 The act of input/output devices notifying the CPU of asynchronous events
 Asynchronous means an event that is not scheduled or whose occurrence time cannot be predicted
 (keyboard input, data arrival from the network, etc.)
 Hardware interrupt
 A hardware signal that devices notify the CPU of the occurrence of a certain situation
 When the CPU receives an interrupt, it executes an interrupt service routine
 Software interrupt
 An interrupt generated by a CPU command
 Processed in the same way as receiving a hardware interrupt
 Interrupts are used in computers
 Mouse operations such as moving or clicking the mouse
 Keyboard input
 Data arrival from the network
 Hard disk write completion
 Notification at regular intervals from the system clock
 Pressing the computer's reset button
 Attaching or detaching a USB memory
Interrupt occurrence and processing
• IDTR(Interrupt Descriptor Table
Register) is a register in the CPU that
has the start address and size of the
interrupt vector table.

72
Interrupt service routines and the operating system
73

 Interrupt Service Routine


 Interrupt Service Routine, ISR, Interrupt Handler
 Location: Device Driver or Kernel Code, Embedded Computer ROM

 Device Driver, Interrupt Service Routine, and Kernel


Interrupts are the key to realizing multiprogramming
74

 Multiprogramming Review
 Execute multiple processes simultaneously
 When one process performs I/O, it is replaced by another process
 When an I/O is completed, a method is needed to receive an I/O completion
notification from the device -> That is interrupt
 Without interrupts, the CPU must continuously check for I/O completion by
polling, which is very inefficient
 Without interrupts
 Implementation of a multiprogramming operating system is virtually
impossible
 Effects of interrupts
 I/O devices and CPU execute their own tasks simultaneously
 I/O devices perform the instructed I/O, and the CPU executes another program
 The computer system operates efficiently
 CPU utilization increases and system processing rate improves

You might also like