# 作業系統 Operating System (CSIE-2B)
###### tags: `courses meow` `CSIE-2B` `Operating System` `2021 Spring`
:::info
:::spoiler click to open the TOC
[TOC]
:::
:::success
## Relative info
- [有趣的東西](https://hackmd.io/oMUSeWAQSRCG8PEKDW1MEQ)
- [違反著作權的禁忌連結](https://www.os-book.com/OS10/slide-dir/index.html)
- [神的翻譯by laimo](https://hackmd.io/@Pl-eQT9CQaS0jhExKqL8_w/BkhOSR4jW)
- [某人寫的酷酷筆記](https://hackmd.io/@Chang-Chia-Chi/OS/https%3A%2F%2Fhackmd.io%2F%40Chang-Chia-Chi%2FOS-CH5)
:::
:::info
- 一些展覽
- CES: 線上展覽
:::
## 課程資訊
### 課本
#### 聖經本
- Operating System Concepts
![Operating System Concepts](https://i.imgur.com/wrp1I5L.png =250x)
<!--這本我在先人的智慧上有找到電子檔-->
<!--https://os.ecci.ucr.ac.cr/slides/Abraham-Silberschatz-Operating-System-Concepts-10th-2018.pdf-->
- Morden Operating System
![Morden Operating System](https://i.imgur.com/bJuS5Jt.png =250x)
- understanding operating system
![](https://i.imgur.com/AFjiX92.jpg =250x)
### 評分標準
#### 出席(10~15%)
#### 期中(25~30%)
#### 期末(25~35%)
#### 作業(20~35%)
- 預計兩次
- 課本勾習題
- 一些程式作業
#### 加分作業
- 展覽心得
- 辯論比賽
- TED Talk
> 不用求情了,老師會先自己齋戒三天,假設大家都有求情[name=教授]
:::info
### 助教資料
#### 實驗室位置 : 工程五館E6-B324-1
#### 陳宗琪 : e-mail : jeffzxx@g.ncu.edu.tw
#### 張晁誌 : e-mail : george.ccc@g.ncu.edu.tw
#### 實驗室電話 : 03-4227151 # 35361
> 聯絡時請用信件副本寄給兩位助教
:::
## outline
- part3
- sync
- deadlock
- part4
- Main memory
- virtual memory
- part5
- mass-Storge Structure
- part6
- file system
- part7
- security
- part8 advence
- VM
- network
- part 9
> virtual是作業系統很重要的精隨,我翻譯為"假"[name=教授]
## Chapter 1 : Introduction
> 電腦的資源有限,如何有效分配東西很重要![name=教授]
- What Operating System
- Computer System Operating
- Computer System Archtecture
- Resource Management
- Security and Proteccccc
### What does the Term Operating System Mean ?
>作業系統是一組主管並控制電腦操作、運用和執行硬體、軟體資源和提供公共服務來組織使用者互動的相互關聯的系統軟體程式,同時也是電腦系統的核心與基石。[name=Wikipedia]
- An operating system is "Fill in the blanks"
- What about?
- Car
- EX:自動駕駛、導航、跟車系統、自動煞車防撞
- Airplane
- Printer
- Washing Machine
- Toaster
- Complier
- Etc.
> 電腦在人們的生活中扮演的角色越大,資安的問題也隨著一起產生[name=教授]
### What is an Operating System ?
> 作業系統就像是一個總管的角色,要負責處理電腦資源與硬體的調配,讓人們更容易解決問題[name=教授]
- A Program that acts AS an intermedary between a user of a computer and the computer hardware
- Operating system goals:
- Execute user program and make solving user problems easier
- Make the computer syetem convenient to use
- Use the computerhardware in an efficient manner
- 四元素
- Hardware : 提供作業系統基本的運算資源(CPU、Memory等)
- OS : 負責協調、控制對硬體的使用調度
- 好的OS應能確保資源的使用平均且有效率,並可以避免錯誤或不正確的使用
- :::info
Kernel(核心):用來管理軟體所發出的I/O,並將它轉譯為資訊處理的指 令,交由CPU等其他硬體設備處理
![](https://i.imgur.com/W0qb6de.png =300x)
:::
- Application : 決定使用者如何運用硬體來解決問題
- User : 使用者,人或機器等
![作業系統四元素](https://i.imgur.com/AOTf2EJ.png =500x)
### Computer system structure
> 論文的秘訣就是圖片一定要用文字來說明[name=教授]
### What Operating Systems Do
- Depends on the point of view
- User want convenience, **ease to use** and **good performance**
- Don't care about resource utilization
- But shared computer such as machine or minicomputer must keep al users happy
- Operating system is a resource allocator and control program making efficient use of HW and managing execution of user programs
- Users of dedicate systems such as **workstations** have dedicated resources but frequently use shared resources from servers
- Mobile devices like smartphones and tables are resource poor, optimized for usability
:::info
站在使用者的角度,只會在意是否方便使用、達到目的,但對管理者來說,使用過多的資源、資源未被妥善運用都會使成本上升,因此作業系統應想辦法使的管理者可以使用最少的資源讓使用者最方便
:::
### Define Operating Systems
- Term OS covers many roles
- No universally accepted definition
- "Everything a vendor ships when you order an operating system" is a goood approximation
### Computer System Organization
- ![img-computer-system-organization](https://image.slidesharecdn.com/computersystemorganization-170503084734/95/computer-system-organization-1-638.jpg?cb=1493801509)
> deviceController( deviceType, deviceDriver, buffer)
> I/O <-> buffer
> device -interrupt-> CPU
- I/O and CPU can execote concurrently
- Each device controller is in charge of a particular device type
- Each device controler has a local buffer
- buffer 做為緩衝,作為設備計算輸出與顯示器輸出的中介、緩衝
- CPU moves data from(to) main memory to(from) local buffer
- Device controller informs CPU that it has finished its operation by causing an **Interrupt**
### Interupt Service Routine(ISR)
- `trap`/`exception`
- software-generated error or user request
- Interrupt handlers are initiated by hardware interrupts , software interrupt instructions, or software exceptions ,and it used to protect system
![](https://i.imgur.com/31PwiZ9.pngx)
> Process使用到I/O資源,發出I/O裝置請求,CPU將控制權將給I/O,I/O完成工作則發出interrupt訊號,CPU回來接收
> 橫軸是時間線嗎 應該是,然後上面是 CPU 狀態,下面是 IO device 狀態
### Interrupt handing
- ![img-interrupt-handing](https://i.imgur.com/wM2Rbvg.png)
> I/O不斷偵測是否有interrupt的訊號,偵測到interrupt以後,將系統權限交給interrupt handler進行停止動作
- After I/O starts, control returns to user program only upon I/O completion
- Wait instruction ideas the next interrupt
- Wait roop
### I/O Strcutre (Cont.)
- `system call`
- request to OS to wait for I/O
- `Device-status table`
- a contains entry for each I/O device indicating its type, address, and state
## Storge Structure
### Main Memory
- random access memory (RAM)
- SRAM
- DRAM
- Typical volatile (通常翻譯成:揮發性記憶體)
- 沒電時就資料就會失去
- Hard Disk Drives(HDD)
- Non-volatile Memory (NVM)
### Storage Hierarchy
- Storage systems organized in Hierarchy
- Speed
- Cost
- Voistillty
- Cashing
- copying information into faster storage system
![](https://i.imgur.com/1Snvgtp.png)
<!-- 我剛剛找到一個酷酷的筆記,我放在最上面,可以去參考一下 -->
<!--看起來酷酷的-->
> 要不要把每個章節分開,做成book模式
> 我覺得OK
## How a modern memory works ?
## How a Modern Computer works
- Direct Memory Access Structure
- one interrupt per block.
- rather than interrupt per byte
### Operating-System Operations
- Bootstraps program
- a simple code help you initialize the system ,load the kernal
- system demon
- Kernel interrupt driven
- hardware
- software (exception or trap)
- software error
- system call
- infinity loop
### Multiprogramming (Batch system)
- job scheduling
- to select job based on priority
- > job := (code + data)
- when job_a switch to IO, switch job_b to CPU, and vice versa
### multitask (timesharing)
- A logical extension of Batch system - the CPU switches jobs so frequenthy that users can interract with each job while it is running ,creating interactive computing
- Responsing time should be < 1 second
- **Virtual Memory**
### Dual-mode Opeartion
- Dual-mode operation protect OS and other system
- **User mode** & **kernel mode**
- Mode bit provided by harware
- > 硬體上有保留 1 bit 在紀錄目前的 mode
- > 0 -> user mode
- > 1-> kernel mode
```
user process executing
call system_call
set mode bit to 1
execute system_call
set mod bit to 0
```
### Timer
- to prevent infinite loop (or process hogging resources)
> xxx 程式沒有回應. 請問要結束此程式嗎? [Y/N]
### Process Management
- def:
- a `Process` is a program in ==execution==
- > a `Program` is a **Passive entity**
- > a `Process` is a **Active entity**
- program counter
- single-thread process has one program counter
- multiy-thread process has a program counter per thread
- > process has a **program counter** per **thread**
### Process Management Activity
- creating and deleting both user and system processes
- suspending and resumeing processes
- Providing mechanisms for ...
### Memory Management
- To execute a program all(or part) of the instructions must be in memory
- (Data + Program) must be in memory
- Activities
- Keeping track of which parts of memory are currently uses and by whom
- Deciding which processes and data to move into and out of memory
- Allocating and deallcating memory space as needed
> 作業系統可以想像成以前要人工的東西都自動化了[name=教授]
### File-system Management
- OSprovides uniform ,logical view of information storage
- File usually organized into direction
### Mass-Storage Management
- Usuallydata used to save data that does not fit in a main memory
### Caching
- 以下是記憶體的階層(越上層越快、越貴,通常儲存空間也較小)
- register
- cache
- memory
- disk
- 光碟
- 磁帶
- 資料最終點通常會位於下層,使用時再從下層搬到上層,這個資料搬動的動作即為Cashing
## I/O Subsystem
- One purpose if OS is to hide hardware device(from user)
- Protection
- Security
- Huge range ,including denial of service
- System among users ,decide who and (can) do what
- Thus ,we need user ID and password
- and group ID...
## Virtualize
- Allows you to run some application on other OSes
- EX : Use linix on Windows ,play games on mac
- Emulation
- used when source CPU type different from target type
- VMwares ESX and Citrix XenService
## Distributed System
- Network, TCP/IP
- LAN (Local Area Network)
- WAN (Wide Area Network)
- MAN (Metropolitan Area Network)
- PAN (Personal Area Network)
- Network operating system
- Connecting each system through Network
- Web clipping
- Only a part of web information send to the device
## Computer -System Arch
### Dual-Coer Design
- Muti-chip and multicode
- Muti-CPU connect to the same memory
### Clustered Syetems
- a lot of computer work together,they depend on the common storage and the syetem work together
- we together , we strong
## Computer Environment
### Mobile
- more OS feature
- GPS, gyroscope
-
### Peer to Peer
- A computer as server and client at the same time
- 有資料當 server ,沒資料當 client
- All the nodes are considered as "Peer"
<!-- LBRY 感覺應該是用 P2P 的架構,但我不太確定 -->
<!-- LBRY應該是用P2P + block chain(是這樣拚嗎?XD)的架構? 我也不確定-->
<!-- 或是block chain本身也就是用P2P的架構?>
<!-- 我也是這麼覺得,應該是用 P2P 實現的 -->
### Cloud Computing
---
## Chapter 2 Operating-System Services
### Operaint System Service
- Allow user to excute progerm
- An environment of progrem and service
:::info
~~不知道要放在哪裡~~
> 超級電腦的 know how 不在硬體,重點是 OS,如何管理數百顆 CPU 和 Memory[name=教授]
:::
#### Microkernels
- 把更多的功能放在 User space
- Benefits:
- Easier to extend a microkernel
- Easie to port the poerating system to new architecture
- More reliable
- More secure
- Detriments:
- Performance overhead of user space to kernel space communication
## Chapter3
### Process Concept
> OS就是好多好多程式的組合
- An Operating system excuted a variety of program that run as a process
- **Process** - a program in executing
- Multiple parts
- The program code, also called text section
- program counter
- **Stack** containing temporary data
- Function parameter...
- Data section
- **Global variable** 放的位置
- Heap containing memory dynamically allocated during run time
- `malloc()` 出來的記憶體放的位置
- Program is passive(stored on disk) and process is active
- Program becomes process when an executable file is loaded into memory
- One program can be several processes
- Consider multiple users executing the same program
### Process Control Block (PCB)
- process state
- Program counter
- CPU reg
- CPU scheduling info
- mem management info
- accounting info
- I/O status info
- next pointer
> PCB 通常是 doubly linked list
> 每一個 PCB 儲存著一份 process
### Process Representation in Linux
```c
// 一些東西
```
### CPU Switch from Process process
> P_0 與 P_1 兩者做切換
>
![](https://i.imgur.com/6mb2vz1.png)
> Context Switch: 也是一種 overhead,CPU 欄位愈多,overhead 愈高
### Process image
Process image is an executable file required while executing the program.
A process image contains
- Code segment
- Data segment
- Stack segment
- Heap segment
![](https://i.imgur.com/b2Enk9y.png)
> 這裡老師沒有提到
### Interprocess communication
Ther are two ways to implement interprocess communication
- Shared memory
- Message passing
- 不會有衝突,對於小資料有效率
- Use send/recv message
- 用system call實做,速度較慢
### Race condition
- Producer
```c=
/* Producer code */
while (true) {
while (counter == BUFFER_SIZE); //Do nothing
buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
counter++;
}
```
- Consumer
```c=
/* Consumer code */
while (true) {
while (counter == 0); //Do nothing
next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
}
```
- counter++ & counter-\-
```c=
register1 = counter;
register1 = register1 + 1;
counter = register1;
```
```c=
register2 = counter;
register2 = register2 - 1;
counter = regfister2;
```
- Consider this execution interleaving with `counter = 5` intially.
```c=
register1 = counter; //Producer
register1 = register1 + 1; //Producer
register2 = counter; //Consumer
register2 = register2 - 1; //Consumer
counter = register1; //Producer -> counter = 6
counter = register2; //Consumer -> counter = 4
//counter = 4
```
## Ch4 Threads & Concurrency
> Thread 可以當作是輕量的 Process。
> 當你在瀏覽網頁的時候,網頁可能就會文字用一個 Thread 處理、圖片用一個Thread 處理。[name=教授]
### Advantages of using thread programming
- Responsiveness
- Allow executing process to **continue responsing user's requests**, and **don't need to wait** for the previous request done.
- Improve efficiency
<!-- 還有其他的,但我來不及整理 -->
e.g.
![](https://i.imgur.com/dwQxYau.png)
> Multi-threaded Server Architecture
### Multithread Model
- Many to one
- Many user threads map to one kernel thread.
- One to One
- One user thread maps to one kernel thread.
- Many to Many
### Thread
#### Thread Pools
- Creating a number of threads in a pool
- Benefits
- Response time is lower since some threads are created and awaited for use
### Semantics of fork() and exec()
- Does `fork()` duplicate only thr calling thread or all threads?
- Some UNIXes have two versions of fork
- `exec()` usually work as normal - replacing the running process including all threads
### etc
:::info
助教說:「推薦使用 python 寫作業」 :+1:
:::
## 我不知道到第幾章了....
---
<!--
笑死現在是在推銷大會ㄇ
結果C2我們也沒做筆記
我就懶
阿可是就挺無聊的,他就感覺好像也是講過去?<-同意
我就在睡覺...
我比較好奇 這樣他考試到底要考什麼
名詞解釋?
也有可能因為第一章是 introduction ㄅ
現在是第二章啦~
我覺得第二章也差不多...
而且圖片字都好小看不到
可是第二章好像還算是overview,所以還是帶過而已
可惡 這樣還要聽Overview聽好久
剛剛看了一下第三章,好像就有 code 要看了
水喔,第三章終於有點東西了
那現在還是大概聽一下好了
度
-->
<!--
哈喽鐘安大大
-->