본 게시글은 OLC의 강좌 Kernel of Linux를 수강한 내용 중 본인에게 필요한 정리한 글입니다.
오래된 강의임에도 불구하고 교수님이 강의를 굉장히 이해하기 쉽게 해주시기 때문에 필요하다면 강의를 들어보시는 것을 추천합니다.
Terminology
Operating System
A Program that acts as an intermediary between a user of computer and the computer hardware
Kernel
컴퓨터가 부팅한 이후 종료될 때까지 계속 메모리에 상주하는 프로그램 (Memory Resident Part of OS, Just C Program.)
* consists of functions
- other programs can call (some of) these functions
- called "system call function"
* 3 parts
- process management
- file sytstem
- I/O system
Utility : Command, Disk resident part os OS (loaded on-demand)
Shell : Special Utility, it's mission is Job Control
File : sequence of bytes, I/O devices are treated as files. (special files, like /dev/sda)
Standard File : stdout, stdin, stderr
System Call
Protection & Prevention
Multiuser System에서는 Protection, 특히 Prevention이 중요 (예 : P2가 불법적으로 P1에 Read/Write하는 것 차단 필요)
이를 위해서 Linux에서는 I/O 연산이 무조건 Kernel을 통해서 수행되도록 구현하여 Kernel에 들어온 연산이 합법적인 지를 먼저 확인하게 된다.
Kernel Mode와 User Mode
CPU에 Binary Bit 1개를 사용하여 Kernel이 수행될 때와 수행되지 않을 때를 구분한다. CPU에서 Kernel이 수행될 때는 Kernel Mode로, 이 때는 CPU가 모든 메모리 영역에 액세스가 가능하며 모든 op code(instruction)이 가능하다. 반면, user mode일 경우에는 실행중인 Process 자신의 메모리 영역에만 액세스가 가능하며 I/O 및 Priviliged op code (eg specical instruction)의 수행이 불가하다.
Source Program에서의 I/O 연산
read(file)과 같은 명령어는 위의 다이어그램과 같이 컴파일이 수행될 때 chmodk로 변경이 된다. 이것이 실행되면 trap이 발생하며, 이후 kernel로 제어권이 넘어가며 kernel에서 실제 I/O 연산을 수행한다. 즉,
read next byte from disk file X into my variable Y (compile changes I/O statement to following)
(1) prepare all parameters → execute "chmodk" instruction.
(2) I/O와 관련된 파라미터를 확인 후 System Call 수행 (Kernel read() checks permission first.)
※ chmodk : privileged instruction. 수행되면 CPU를 뺏김 (HW trap)
Alternating User mode & kernel mode
위에서 본 것처럼, 결국 Program은 User Mode에서 Running하다가 I/O 연산이 필요할 때마다 Kernel Mode로 Running하며 이 동작을 계속 반복하게 된다.
(1) P1 is executing in user mode → invokes a kernel function (system call)
(2) causes HW trap (in kernel mode) call appropriate kernel function → kernel returns to P1's a.out
Program에서 콜 스택(call stack)이 있는 것과 같이, Kernel Mode에서 실행 중인 서브루틴에 관한 정보를 저장하기 위한 스택이 필요하다. 이 때문에 모든 프로그램에서는 User Stack과 Kernel Stack 두 개의 스택이 생성된다.
Invoking a System Call
in linux, system call interface is provided by the C Library.
즉, printf(), fprintf(), puts()... 와 같은 모든 Library는 결국 I/O Instruction이 수행될 시점에는 write()라는 단 하나의 system call을 수행하게 된다.
system_call()
User Program에서 실행한 I/O 연산의 수행부터 리턴까지의 과정
1. User program makes system call - eg write(2)
2. HW trap
3. HW switches CPU mode from user to kernel
4. HW jumps to sys_call()
5. It is an assembly function in kernel
6. Save context of the current process
7. Is system call # vaild?
8. Get address of sys call function from table
9. Invoke sys call function (eg sys_write())
10. Return to user after system call
※ system call function은 전부 Naming Rule이 sys_xxx와 같다.