Chapter 02
Chapter 02
3
4 1. Computer System & Hardware
Layers Comprising a Computer System
5
Scope of a Computer System
6
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
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;
; 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 : }
_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
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
고
돈세는 기 객 직원
계를 서로
송 대 적
사용하려 금고 금 출 금
고 충돌
고
객
고
객 인쇄 금고
송금
• Customer: Application program
inefficiency, errors due to crashes, delays, • Employee: Various functions of the operating system
security vulnerabilities, chaos!!! (kernel functions)
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
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
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
• 2 questions
- User space conflicts between applications?
- What if the actual physical memory is less than
4GB?
Solution to two questions
43
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
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
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
Library
Pre-written functions to be used in applications, Files provided in compiled
binary form
Developers cannot write applications without using libraries
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 시스템 호출 실행
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
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
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