Sistem Operasi: Cheatsheet Komprehensif
Cheatsheet lengkap untuk memahami Sistem Operasi (Operating System) dari konsep fundamental hingga implementasi modern.
1. Pengantar Sistem Operasi
Definisi Sistem Operasi
Sistem Operasi (OS) adalah perangkat lunak sistem yang bertindak sebagai perantara antara pengguna dan perangkat keras komputer. OS mengelola sumber daya hardware dan menyediakan layanan untuk program aplikasi.
Fungsi Utama:
- Resource Manager: Mengelola CPU, memori, storage, dan I/O devices
- Extended Machine: Menyediakan abstraksi untuk menyembunyikan kompleksitas hardware
- Control Program: Mengontrol eksekusi program dan mencegah error
Arsitektur Sistem Operasi
┌─────────────────────────────────────────────────-┐
│ User Programs │
├─────────────────────────────────────────────────-┤
│ System Libraries (libc) │
├─────────────────────────────────────────────────-┤
│ System Call Interface (API ke Kernel) │
├─────────────────────────────────────────────────-┤
│ KERNEL │
│ ┌───────────┬───────────┬───────────────────┐ │
│ │ Process │ Memory │ File System │ │
│ │ Manager │ Manager │ Manager │ │
│ ├───────────┼───────────┼───────────────────┤ │
│ │ Device │ Network │ Security │ │
│ │ Drivers │ Stack │ Module │ │
│ └───────────┴───────────┴───────────────────┘ │
├─────────────────────────────────────────────────-┤
│ Hardware (CPU, RAM, Disk) │
└─────────────────────────────────────────────────-┘
Tipe Kernel
| Tipe | Deskripsi | Contoh | Kelebihan | Kekurangan |
|---|---|---|---|---|
| Monolithic | Semua layanan OS berjalan di kernel space | Linux, Unix | Performa tinggi | Kurang modular, crash = sistem down |
| Microkernel | Kernel minimal, layanan di user space | Minix, QNX, L4 | Stabil, modular | Overhead IPC |
| Hybrid | Kombinasi monolithic + microkernel | Windows NT, macOS | Balance performa & modularitas | Kompleksitas |
| Exokernel | Kernel sangat minimal, aplikasi kelola hardware | MIT Exokernel | Fleksibel, efisien | Sulit diprogram |
Mode Eksekusi
Dual Mode Operation:
┌────────────────────────────────────────────┐
│ USER MODE (Ring 3) │
│ • Aplikasi user berjalan di sini │
│ • Akses hardware terbatas │
│ • Tidak bisa eksekusi privileged instr. │
└──────────────────┬─────────────────────────┘
│ System Call (trap)
▼
┌────────────────────────────────────────────┐
│ KERNEL MODE (Ring 0) │
│ • Kernel dan driver berjalan di sini │
│ • Akses penuh ke hardware │
│ • Bisa eksekusi semua instruksi │
└────────────────────────────────────────────┘
Privileged Instructions (hanya di kernel mode):
- I/O instructions
- Memory management (page table manipulation)
- Interrupt management
- Halt instruction
System Calls
System Call adalah mekanisme yang memungkinkan program user mode untuk meminta layanan dari kernel. System call adalah satu-satunya cara legal untuk aplikasi mengakses sumber daya sistem yang dilindungi.
Mengapa System Call Diperlukan?
Aplikasi user tidak bisa langsung mengakses hardware karena:
- Keamanan: Mencegah aplikasi merusak sistem atau mengakses data aplikasi lain
- Abstraksi: Menyembunyikan kompleksitas hardware dari programmer
- Portabilitas: Aplikasi bisa berjalan di hardware berbeda tanpa modifikasi
Mekanisme System Call:
┌─────────────────────────────────────────────┐
│ User Program │
│ printf("Hello"); │
│ │ │
│ ▼ │
│ C Library (libc) │
│ write(fd, buf, size) │
│ │ │
│ ▼ │
│ System Call Wrapper │
│ mov $1, %rax # syscall number │
│ mov $fd, %rdi # arg1 │
│ mov $buf, %rsi # arg2 │
│ mov $size, %rdx # arg3 │
│ syscall # interrupt ke kernel │
│ │ │
│ ▼ │
└───────┼─────────────────────────────────────┘
│ Trap/Interrupt
▼
┌─────────────────────────────────────────────┐
│ Kernel Mode │
│ System Call Handler │
│ sys_write() { │
│ // validasi parameter │
│ // eksekusi operasi I/O │
│ // return hasil │
│ } │
│ │ │
│ ▼ │
│ Return ke User Mode │
└─────────────────────────────────────────────┘
Langkah-langkah System Call:
- User program memanggil library function (misal:
write()) - Library wrapper menyiapkan parameter dan system call number
- Trap instruction (
syscall,int 0x80,SVC) memicu mode switch - Kernel menyimpan context user (registers, stack pointer)
- System call handler mengeksekusi fungsi kernel sesuai nomor
- Kernel mengembalikan hasil ke user space
- Context switch kembali ke user mode dengan hasil
System Call Number:
Setiap system call memiliki nomor unik yang digunakan untuk mengidentifikasi layanan yang diminta:
// Linux x86-64 system call numbers
#define __NR_read 0
#define __NR_write 1
#define __NR_open 2
#define __NR_close 3
#define __NR_fork 57
#define __NR_execve 59
#define __NR_exit 60
Kategori System Calls:
| Kategori | Contoh | Deskripsi |
|---|---|---|
| Process Control | fork(), exec(), exit(), wait() | Membuat, menghentikan, dan mengontrol proses |
| File Management | open(), read(), write(), close(), stat() | Operasi file dan direktori |
| Device Management | ioctl(), read(), write() | Mengakses dan mengontrol device |
| Information Maintenance | getpid(), gettimeofday(), sysinfo() | Mendapatkan informasi sistem |
| Communication | pipe(), shmget(), msgget(), socket() | IPC dan komunikasi jaringan |
| Protection | chmod(), chown(), setuid() | Kontrol akses dan keamanan |
Contoh System Call di Linux:
#include <unistd.h>
#include <sys/syscall.h>
// Direct system call (tidak direkomendasikan)
long result = syscall(SYS_write, STDOUT_FILENO, "Hello\n", 6);
// Via library wrapper (direkomendasikan)
write(STDOUT_FILENO, "Hello\n", 6);
System Call Interface di Berbagai OS:
| OS | Instruction | Calling Convention | Register untuk syscall number |
|---|---|---|---|
| Linux x86-64 | syscall | RDI, RSI, RDX, R10, R8, R9 | RAX |
| Linux x86-32 | int 0x80 | Stack (EBX, ECX, EDX, …) | EAX |
| Windows x64 | syscall | RCX, RDX, R8, R9, stack | RAX |
| macOS/BSD | syscall | RDI, RSI, RDX, R10, R8, R9 | RAX |
| ARM64 | svc #0 | X0-X7 | X8 |
Error Handling:
System call mengembalikan nilai negatif atau -1 jika terjadi error, dan errno di-set dengan kode error:
ssize_t bytes = write(fd, buffer, size);
if (bytes == -1) {
// Error occurred
perror("write"); // prints: write: Bad file descriptor
// atau
fprintf(stderr, "Error: %s\n", strerror(errno));
}
Overhead System Call:
System call memiliki overhead karena:
- Context switch (user ↔ kernel mode)
- Parameter validation di kernel
- Security checks (permissions, capabilities)
- Interrupt handling
Optimasi:
- VDSO (Virtual Dynamic Shared Object): System call tertentu (seperti
gettimeofday()) diimplementasikan di user space untuk menghindari context switch - Batching: Menggabungkan multiple system calls menjadi satu
- Async I/O: Menggunakan
epoll,kqueue, atauio_uringuntuk mengurangi blocking
System Call vs Library Function:
| System Call | Library Function |
|---|---|
| Interface langsung ke kernel | Wrapper di atas system call |
| Harus melalui trap | Bisa di user space |
| Lebih lambat (context switch) | Lebih cepat (no trap) |
Contoh: read(), write() | Contoh: printf(), strlen() |
Contoh: Perjalanan printf() ke System Call
printf("Hello World\n");
│
▼
// Di libc: printf() memformat string
fprintf(stdout, "Hello World\n");
│
▼
// Di libc: write() adalah wrapper
write(STDOUT_FILENO, "Hello World\n", 12);
│
▼
// Assembly: setup system call
mov $1, %rax // __NR_write = 1
mov $1, %rdi // fd = STDOUT_FILENO
mov $string, %rsi // buffer address
mov $12, %rdx // size
syscall // Trap ke kernel
│
▼
// Kernel: sys_write()
sys_write(fd, buf, count) {
// Validasi fd, buffer, permissions
// Copy data dari user space ke kernel
// Panggil device driver
// Return jumlah bytes written
}
Security Implications:
- Sandboxing: Membatasi system calls yang bisa dipanggil (seccomp, AppArmor, SELinux)
- Capabilities: Memberikan privilege tanpa full root
- System call filtering: Memblokir system calls berbahaya (seperti
ptrace,mount)
2. Manajemen Proses
Konsep Proses
Proses adalah program yang sedang dieksekusi. Proses adalah unit dasar dari eksekusi dalam sistem operasi.
Process vs Program:
| Program | Proses |
|---|---|
| Passive entity (file di disk) | Active entity (running) |
| Tidak punya state | Punya state (running, waiting, etc.) |
| Tidak punya resources | Memiliki resources (memory, files) |
Process Control Block (PCB)
PCB menyimpan semua informasi tentang proses:
┌─────────────────────────────────────┐
│ PROCESS CONTROL BLOCK │
├─────────────────────────────────────┤
│ Process ID (PID) │
│ Process State │
│ Program Counter │
│ CPU Registers │
│ CPU Scheduling Info (priority) │
│ Memory Management Info │
│ Accounting Info (CPU time used) │
│ I/O Status Info │
│ List of Open Files │
└─────────────────────────────────────┘
Process State Diagram
Diagram State Proses (Process State Diagram)
State Transitions:
- New → Ready: Proses diadmit ke antrian ready
- Ready → Running: Scheduler memilih proses (dispatch)
- Running → Ready: Preemption (time slice habis)
- Running → Waiting: Menunggu I/O atau event
- Waiting → Ready: I/O selesai
- Running → Terminated: Proses selesai atau kill
Context Switch
Context Switch adalah proses menyimpan state dari proses yang sedang berjalan dan memuat state proses lain.
Context Switch: Proses P0 → P1
Overhead Context Switch:
- Waktu untuk save/restore registers
- Cache flush (TLB, CPU cache)
- Pipeline flush
Process Creation
Fork-Exec Model (Unix/Linux):
pid_t pid = fork(); // Duplikasi proses
if (pid == 0) {
// Child process
exec("/bin/ls", args); // Replace dengan program baru
} else if (pid > 0) {
// Parent process
wait(NULL); // Tunggu child selesai
} else {
// Fork failed
perror("fork");
}
Process Tree:
init (PID 1)
├── systemd
│ ├── sshd
│ │ └── bash
│ │ └── vim
│ └── nginx
│ ├── nginx worker
│ └── nginx worker
└── cron
Inter-Process Communication (IPC)
| Metode | Deskripsi | Use Case |
|---|---|---|
| Pipe | Unidirectional byte stream | Parent-child communication |
| Named Pipe (FIFO) | Pipe dengan nama di filesystem | Unrelated processes |
| Message Queue | Antrian pesan terstruktur | Producer-consumer |
| Shared Memory | Region memori yang di-share | High-speed data sharing |
| Semaphore | Signaling mechanism | Synchronization |
| Socket | Network-style communication | Local or network IPC |
| Signal | Asynchronous notification | Event notification |
3. Thread
Konsep Thread
Thread adalah unit terkecil dari eksekusi dalam proses. Thread berbagi address space dan resources dengan thread lain dalam proses yang sama.
┌─────────────────────────────────────────────────────┐
│ PROSES │
│ ┌─────────────────────────────────────────────────┐│
│ │ Shared Resources ││
│ │ • Code Section • Open Files ││
│ │ • Data Section • Heap Memory ││
│ │ • Global Variables • Signal Handlers ││
│ └─────────────────────────────────────────────────┘│
│ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Thread 1│ │ Thread 2│ │ Thread 3│ │
│ ├─────────┤ ├─────────┤ ├─────────┤ │
│ │ Stack │ │ Stack │ │ Stack │ │
│ │ Regs │ │ Regs │ │ Regs │ │
│ │ PC │ │ PC │ │ PC │ │
│ │ ThreadID│ │ ThreadID│ │ ThreadID│ │
│ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────────────────┘
Thread vs Process
| Aspek | Process | Thread |
|---|---|---|
| Address Space | Terpisah | Shared |
| Communication | IPC (mahal) | Shared memory (murah) |
| Creation Cost | Tinggi | Rendah |
| Context Switch | Mahal | Murah |
| Isolation | Tinggi (crash terpisah) | Rendah (crash = semua mati) |
| Overhead | Lebih berat | Lebih ringan |
Model Threading
1. User-Level Threads (ULT):
┌────────────────────────────────────┐
│ User Space │
│ ┌──────────────────────────────┐ │
│ │ Thread Library (pthreads) │ │
│ │ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │ │
│ │ │ T1│ │ T2│ │ T3│ │ T4│ │ │
│ │ └───┘ └───┘ └───┘ └───┘ │ │
│ └──────────────────────────────┘ │
├────────────────────────────────────┤
│ Kernel Space │
│ (1 Kernel Thread) │
└────────────────────────────────────┘
- Kernel tidak tahu tentang user threads
- Context switch cepat (tidak perlu syscall)
- Jika satu thread block, semua thread block
2. Kernel-Level Threads (KLT):
┌────────────────────────────────────┐
│ User Space │
│ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │
│ │ T1│ │ T2│ │ T3│ │ T4│ │
│ └─┬─┘ └─┬─┘ └─┬─┘ └─┬─┘ │
├────────┼─────┼─────┼─────┼─────────┤
│ ▼ ▼ ▼ ▼ │
│ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │
│ │KT1│ │KT2│ │KT3│ │KT4│ │
│ └───┘ └───┘ └───┘ └───┘ │
│ Kernel Space │
└────────────────────────────────────┘
- Kernel manage semua threads
- Satu thread block tidak mempengaruhi yang lain
- Overhead lebih tinggi
3. Hybrid (Many-to-Many):
┌────────────────────────────────────┐
│ User Threads: T1 T2 T3 T4 T5 T6 │
│ \ | / \ | / │
│ \ |/ \|/ │
├────────────────────────────────────┤
│ Kernel Threads: KT1 KT2 │
└────────────────────────────────────┘
- Fleksibel: banyak user thread ke beberapa kernel thread
- Digunakan oleh Solaris, older Windows
POSIX Threads (pthreads)
#include <pthread.h>
void* thread_function(void* arg) {
int* num = (int*)arg;
printf("Thread received: %d\n", *num);
return NULL;
}
int main() {
pthread_t thread_id;
int arg = 42;
// Create thread
pthread_create(&thread_id, NULL, thread_function, &arg);
// Wait for thread to finish
pthread_join(thread_id, NULL);
return 0;
}
Fungsi pthreads penting:
| Fungsi | Deskripsi |
|---|---|
pthread_create() | Buat thread baru |
pthread_join() | Tunggu thread selesai |
pthread_exit() | Terminasi thread |
pthread_cancel() | Batalkan thread |
pthread_mutex_lock() | Lock mutex |
pthread_cond_wait() | Wait pada condition variable |
4. CPU Scheduling
Konsep Scheduling
CPU Scheduler memilih proses dari ready queue untuk dieksekusi di CPU.
Kapan scheduling terjadi:
- Proses switch dari running ke waiting (I/O)
- Proses switch dari running ke ready (interrupt)
- Proses switch dari waiting ke ready (I/O complete)
- Proses terminasi
Non-preemptive vs Preemptive:
| Non-preemptive | Preemptive |
|---|---|
| Proses jalan sampai selesai/block | Proses bisa diinterupsi |
| Sederhana | Lebih kompleks |
| Response time buruk | Response time baik |
| Contoh: FCFS, SJF | Contoh: Round Robin, SRTF |
Kriteria Scheduling
| Kriteria | Definisi | Goal |
|---|---|---|
| CPU Utilization | % waktu CPU sibuk | Maximize |
| Throughput | Jumlah proses selesai/waktu | Maximize |
| Turnaround Time | Waktu dari submit sampai selesai | Minimize |
| Waiting Time | Waktu menunggu di ready queue | Minimize |
| Response Time | Waktu dari submit sampai response pertama | Minimize |
Algoritma Scheduling
1. First-Come First-Served (FCFS)
Ready Queue: P1 → P2 → P3 → CPU
Urutan kedatangan = urutan eksekusi
Contoh:
| Process | Burst Time |
|---|---|
| P1 | 24 |
| P2 | 3 |
| P3 | 3 |
Gantt Chart:
| P1 (24) | P2(3)| P3(3)|
0 24 27 30
Waiting Time: P1=0, P2=24, P3=27
Average WT = (0+24+27)/3 = 17
Convoy Effect: Proses pendek menunggu proses panjang.
Gantt Chart: FCFS vs SJF (P1=24, P2=3, P3=3)
2. Shortest Job First (SJF)
Proses dengan burst time terpendek dieksekusi duluan.
Non-preemptive SJF:
| Process | Arrival | Burst |
|---|---|---|
| P1 | 0 | 7 |
| P2 | 2 | 4 |
| P3 | 4 | 1 |
| P4 | 5 | 4 |
Gantt Chart:
| P1 (7) | P3(1)| P2 (4) | P4 (4) |
0 7 8 12 16
Average WT = (0+6+3+7)/4 = 4
Preemptive SJF (SRTF - Shortest Remaining Time First): Jika proses baru datang dengan burst lebih pendek dari remaining time proses yang sedang jalan, switch!
3. Priority Scheduling
Setiap proses punya priority. CPU diberikan ke proses dengan priority tertinggi.
Masalah: Starvation - Proses low priority mungkin tidak pernah jalan. Solusi: Aging - Tingkatkan priority proses yang sudah lama menunggu.
Priority(t) = BasePriority + (WaitingTime × AgingFactor)
4. Round Robin (RR)
Setiap proses dapat time quantum (q) untuk eksekusi. Setelah q habis, proses dipindah ke belakang antrian.
Contoh dengan q = 4:
| Process | Burst Time |
|---|---|
| P1 | 24 |
| P2 | 3 |
| P3 | 3 |
Gantt Chart:
|P1(4)|P2(3)|P3(3)|P1(4)|P1(4)|P1(4)|P1(4)|P1(4)|
0 4 7 10 14 18 22 26 30
Queue evolution:
t=0: [P1, P2, P3]
t=4: [P2, P3, P1]
t=7: [P3, P1]
t=10: [P1]
...
Time Quantum Selection:
- q terlalu besar → jadi FCFS
- q terlalu kecil → overhead context switch tinggi
- Rule of thumb: 80% CPU bursts < q
5. Multilevel Queue
┌─────────────────────────────────────┐
│ Highest Priority │
│ ┌───────────────────────────────┐ │
│ │ System Processes [RR] │ │
│ └───────────────────────────────┘ │
│ ┌───────────────────────────────┐ │
│ │ Interactive Processes [RR] │ │
│ └───────────────────────────────┘ │
│ ┌───────────────────────────────┐ │
│ │ Batch Processes [FCFS] │ │
│ └───────────────────────────────┘ │
│ Lowest Priority │
└─────────────────────────────────────┘
6. Multilevel Feedback Queue (MLFQ)
Proses bisa berpindah antar queue berdasarkan perilaku:
- CPU-bound → turun ke queue priority rendah
- I/O-bound → naik ke queue priority tinggi
Queue 0 (q=8): [Interactive jobs] ←── New process
↓ timeout
Queue 1 (q=16): [Mixed jobs]
↓ timeout
Queue 2 (FCFS): [CPU-bound jobs]
5. Sinkronisasi Proses
Race Condition
Race Condition terjadi ketika hasil eksekusi bergantung pada urutan eksekusi thread yang tidak terprediksi.
Contoh:
// Shared variable
int counter = 0;
// Thread 1 // Thread 2
counter++; counter++;
// Expected: counter = 2
// Possible: counter = 1 (race condition!)
Kenapa bisa salah?
counter++ sebenarnya adalah:
1. LOAD counter → register
2. ADD register, 1
3. STORE register → counter
Thread 1: Thread 2:
LOAD (0)
LOAD (0)
ADD (1)
ADD (1)
STORE (1)
STORE (1) ← overwrites!
Hasil: counter = 1 (seharusnya 2)
Critical Section Problem
Critical Section adalah bagian kode yang mengakses shared resource.
Requirements untuk solusi:
- Mutual Exclusion: Hanya satu proses di critical section
- Progress: Jika tidak ada di CS, proses yang mau masuk tidak boleh diblock selamanya
- Bounded Waiting: Ada batas waktu tunggu untuk masuk CS
Peterson’s Solution
Solusi software untuk 2 proses:
// Shared variables
bool flag[2] = {false, false};
int turn;
// Process i (i = 0 atau 1, j = 1-i)
void enter_critical_section(int i) {
int j = 1 - i;
flag[i] = true; // Saya mau masuk
turn = j; // Tapi beri kesempatan dia dulu
while (flag[j] && turn == j)
; // busy wait
}
void exit_critical_section(int i) {
flag[i] = false;
}
Hardware Support
1. Test-and-Set (TAS):
// Atomic instruction
bool test_and_set(bool *target) {
bool old = *target;
*target = true;
return old; // Return nilai lama
}
// Penggunaan
bool lock = false;
void enter_cs() {
while (test_and_set(&lock))
; // busy wait
}
void exit_cs() {
lock = false;
}
2. Compare-and-Swap (CAS):
// Atomic instruction
int compare_and_swap(int *ptr, int expected, int new_value) {
int old = *ptr;
if (old == expected)
*ptr = new_value;
return old;
}
Mutex (Mutual Exclusion)
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* thread_func(void* arg) {
pthread_mutex_lock(&mutex);
// Critical Section
counter++;
pthread_mutex_unlock(&mutex);
return NULL;
}
Semaphore
Semaphore adalah variabel integer dengan operasi atomic:
- wait(S) atau P(S): Decrement, block jika ≤ 0
- signal(S) atau V(S): Increment, wake up waiting process
// Binary Semaphore (Mutex)
sem_t mutex;
sem_init(&mutex, 0, 1); // Initial value = 1
sem_wait(&mutex); // P(mutex)
// Critical Section
sem_post(&mutex); // V(mutex)
// Counting Semaphore (Resource pool)
sem_t resources;
sem_init(&resources, 0, 5); // 5 resources available
Classic Synchronization Problems
1. Producer-Consumer (Bounded Buffer)
Bounded Buffer: Producer-Consumer Problem
full = jumlah item di buffer, empty = slot kosong. Producer menunggu jika buffer penuh, Consumer menunggu jika buffer kosong.
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
sem_t empty, full;
pthread_mutex_t mutex;
void init() {
sem_init(&empty, 0, BUFFER_SIZE); // Buffer slots available
sem_init(&full, 0, 0); // Items in buffer
}
void* producer(void* arg) {
int item;
while (1) {
item = produce_item();
sem_wait(&empty); // Wait for empty slot
pthread_mutex_lock(&mutex);
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&full); // Signal item available
}
}
void* consumer(void* arg) {
int item;
while (1) {
sem_wait(&full); // Wait for item
pthread_mutex_lock(&mutex);
item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&empty); // Signal empty slot
consume_item(item);
}
}
2. Readers-Writers Problem
sem_t rw_mutex; // For writers
sem_t mutex; // For read_count
int read_count = 0;
void* reader(void* arg) {
while (1) {
sem_wait(&mutex);
read_count++;
if (read_count == 1)
sem_wait(&rw_mutex); // First reader locks
sem_post(&mutex);
// Reading...
sem_wait(&mutex);
read_count--;
if (read_count == 0)
sem_post(&rw_mutex); // Last reader unlocks
sem_post(&mutex);
}
}
void* writer(void* arg) {
while (1) {
sem_wait(&rw_mutex);
// Writing...
sem_post(&rw_mutex);
}
}
3. Dining Philosophers
Dining Philosophers Problem
Solusi dengan asymmetric pickup:
sem_t fork[5]; // All initialized to 1
void philosopher(int id) {
while (1) {
think();
if (id % 2 == 0) {
sem_wait(&fork[id]);
sem_wait(&fork[(id + 1) % 5]);
} else {
sem_wait(&fork[(id + 1) % 5]);
sem_wait(&fork[id]);
}
eat();
sem_post(&fork[id]);
sem_post(&fork[(id + 1) % 5]);
}
}
Monitor
Monitor adalah high-level synchronization construct yang menggabungkan data, procedures, dan synchronization.
┌────────────────────────────────────────┐
│ MONITOR │
│ ┌──────────────────────────────────┐ │
│ │ Shared Data │ │
│ │ (private) │ │
│ └──────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────┐ │
│ │ Condition Variables │ │
│ │ x.wait() x.signal() │ │
│ └──────────────────────────────────┘ │
│ │
│ ┌────────────┐ ┌────────────────────┐ │
│ │ Procedure 1│ │ Procedure 2 │ │
│ │ (public) │ │ (public) │ │
│ └────────────┘ └────────────────────┘ │
│ ↑ │
│ Only one thread at a time │
│ (implicit mutual exclusion) │
│ │
│ ╔════════════════════════════════════╗│
│ ║ Entry Queue ║│
│ ║ [T3] [T2] [T1] → enter ║│
│ ╚════════════════════════════════════╝│
└────────────────────────────────────────┘
6. Deadlock
Definisi Deadlock
Deadlock adalah situasi dimana dua atau lebih proses saling menunggu resource yang dipegang oleh proses lain, sehingga tidak ada yang bisa melanjutkan.
┌───────────┐ ┌───────────┐
│ Process A │◀──holds─│ Resource 1│
│ │ └───────────┘
│ │ ▲
│ waits │ │ waits
│ for │ │ for
│ ▼ │ │
│ Resource 2│─────holds────▶│ Process B │
└───────────┘ └───────────┘
A holds R1, waits for R2
B holds R2, waits for R1
→ DEADLOCK!
Kondisi Deadlock (Coffman Conditions)
Deadlock terjadi jika dan hanya jika keempat kondisi ini terpenuhi secara bersamaan:
| Kondisi | Deskripsi |
|---|---|
| 1. Mutual Exclusion | Resource hanya bisa digunakan satu proses pada satu waktu |
| 2. Hold and Wait | Proses memegang resource sambil menunggu resource lain |
| 3. No Preemption | Resource tidak bisa diambil paksa dari proses |
| 4. Circular Wait | Ada rantai circular: P1→P2→P3→…→P1 |
Resource Allocation Graph (RAG)
Resource Allocation Graph - Contoh Deadlock
Strategi Penanganan Deadlock
1. Deadlock Prevention
Cegah salah satu dari 4 kondisi:
| Kondisi | Cara Mencegah |
|---|---|
| Mutual Exclusion | Gunakan sharable resources (jarang bisa) |
| Hold and Wait | Request semua resource sekaligus |
| No Preemption | Paksa release jika request gagal |
| Circular Wait | Order resources, request sesuai urutan |
Contoh Circular Wait Prevention:
// Resource ordering: R1 < R2 < R3
// Selalu request dengan urutan ascending
// Correct:
lock(R1); lock(R2); lock(R3);
// Incorrect (bisa deadlock):
lock(R3); lock(R1); // Violates ordering
2. Deadlock Avoidance
Sistem mengevaluasi setiap request untuk memastikan tidak menuju unsafe state.
Banker’s Algorithm:
State aman jika ada urutan eksekusi $\langle P_1, P_2, …, P_n \rangle$ dimana setiap $P_i$ bisa selesai.
Data Structures:
Available[m]: Resource tersediaMax[n][m]: Maximum demand setiap prosesAllocation[n][m]: Resource yang sudah dialokasiNeed[n][m] = Max - Allocation: Kebutuhan sisa
Safety Algorithm:
1. Work = Available, Finish[i] = false
2. Find i where Finish[i] = false AND Need[i] ≤ Work
3. If found:
Work = Work + Allocation[i]
Finish[i] = true
Goto step 2
4. If all Finish[i] = true → SAFE STATE
Contoh:
Proses Allocation Max Need Available
A B C A B C A B C A B C
P0 0 1 0 7 5 3 7 4 3 3 3 2
P1 2 0 0 3 2 2 1 2 2
P2 3 0 2 9 0 2 6 0 0
P3 2 1 1 2 2 2 0 1 1
P4 0 0 2 4 3 3 4 3 1
Safe sequence: <P1, P3, P4, P2, P0>
3. Deadlock Detection
Izinkan deadlock terjadi, lalu deteksi dan recover.
Detection Algorithm (mirip safety algorithm):
- Jalankan periodically
- Cari cycle di wait-for graph
Recovery:
- Process Termination: Kill proses di cycle
- Resource Preemption: Ambil resource dari proses
4. Ignore (Ostrich Algorithm)
Abaikan deadlock karena:
- Jarang terjadi
- Cost prevention/detection tinggi
- Restart lebih murah
Digunakan oleh: Unix, Linux, Windows (untuk sebagian resource)
7. Manajemen Memori
Memory Hierarchy
Hierarki Memori (Memory Hierarchy)
Address Binding
Kapan address ditentukan:
| Tahap | Deskripsi | Flexibility |
|---|---|---|
| Compile Time | Address absolut di-generate saat compile | Harus recompile jika pindah |
| Load Time | Address ditentukan saat program di-load | Relocatable code |
| Execution Time | Address ditentukan saat runtime | Perlu hardware support (MMU) |
Logical vs Physical Address
┌─────────────────┐ ┌─────────────────┐
│ CPU (Process) │ │ Physical Memory │
│ │ │ │
│ Logical Address │ MMU │ Physical Address│
│ (Virtual) │─────────▶│ │
│ 0x1234 │ Mapping │ 0xABCD │
└─────────────────┘ └─────────────────┘
- Logical/Virtual Address: Dilihat oleh CPU/process
- Physical Address: Address sebenarnya di RAM
- MMU (Memory Management Unit): Hardware yang melakukan translasi
Contiguous Memory Allocation
Setiap proses mendapat blok memori yang berurutan.
Fixed Partitioning:
┌────────────────────┐
│ OS (Reserved) │
├────────────────────┤
│ Partition 1 (2MB) │ ← Process A (1.5MB) + 0.5MB fragmentation
├────────────────────┤
│ Partition 2 (4MB) │ ← Process B (3MB) + 1MB fragmentation
├────────────────────┤
│ Partition 3 (4MB) │ ← Empty
├────────────────────┤
│ Partition 4 (6MB) │ ← Process C (6MB)
└────────────────────┘
- Internal Fragmentation: Ruang tidak terpakai di dalam partisi
Variable Partitioning:
┌────────────────────┐
│ OS (Reserved) │
├────────────────────┤
│ Process A (1.5MB) │
├────────────────────┤
│ Hole (2MB) │ ← External fragmentation
├────────────────────┤
│ Process B (3MB) │
├────────────────────┤
│ Hole (1MB) │ ← External fragmentation
├────────────────────┤
│ Process C (4MB) │
└────────────────────┘
- External Fragmentation: Lubang-lubang kecil antar partisi
Allocation Strategies:
| Strategy | Deskripsi | Pros/Cons |
|---|---|---|
| First Fit | Cari hole pertama yang cukup | Cepat |
| Best Fit | Cari hole terkecil yang cukup | Minimize waste, tapi banyak small holes |
| Worst Fit | Cari hole terbesar | Leave larger remaining hole |
Paging
Paging membagi memori menjadi fixed-size blocks:
- Frame: Fixed-size block di physical memory
- Page: Fixed-size block di logical memory
- Ukuran umum: 4KB, 2MB, 1GB (huge pages)
Logical Memory Physical Memory
┌────────────┐ ┌────────────┐
│ Page 0 │──────────────▶│ Frame 2 │
├────────────┤ ├────────────┤
│ Page 1 │───┐ │ Frame 0 │◀──┐
├────────────┤ │ ├────────────┤ │
│ Page 2 │ │ │ Frame 1 │◀──┼──┐
├────────────┤ │ ├────────────┤ │ │
│ Page 3 │ └─────────▶│ Frame 5 │ │ │
└────────────┘ ├────────────┤ │ │
│ Frame 3 │ │ │
Page Table ├────────────┤ │ │
┌───┬───────┐ │ Frame 4 │ │ │
│ 0 │ 2 │ └────────────┘ │ │
├───┼───────┤ │ │
│ 1 │ 5 │─────────────────────────────┘ │
├───┼───────┤ │
│ 2 │ 1 │────────────────────────────────┘
├───┼───────┤
│ 3 │ 0 │
└───┴───────┘
Address Translation:
Translasi Alamat dengan Paging (Page Size = 4KB)
20 bits
12 bits
dari table
tetap sama
Page Table Entry (PTE):
┌─────────────────────────────────────────────────────┐
│ Valid │ Read │ Write │ Exec │ Dirty │ Accessed │ Frame │
│ (V) │ (R) │ (W) │ (X) │ (D) │ (A) │ No. │
└─────────────────────────────────────────────────────┘
Translation Lookaside Buffer (TLB)
TLB adalah cache untuk page table entries.
┌───────────────────────────────────────────────────────────┐
│ CPU │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Logical Address │ │
│ │ Page | Offset │ │
│ └─────────────────────────┬────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ TLB │ │
│ │ Page │ Frame │ │
│ │ 3 │ 7 ← TLB Hit! (fast) │ │
│ │ 5 │ 2 │ │
│ └─────────┬────────────────────────────────────────────┘ │
│ │ TLB Miss? │
│ ▼ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Page Table (in RAM) │ │
│ │ (slower, update TLB) │ │
│ └──────────────────────────────────────────────────────┘ │
└───────────────────────────────────────────────────────────┘
Effective Access Time (EAT): $$\text{EAT} = h \times (t_{TLB} + t_{mem}) + (1-h) \times (t_{TLB} + 2 \times t_{mem})$$
Dimana:
- $h$ = TLB hit ratio
- $t_{TLB}$ = TLB access time
- $t_{mem}$ = Memory access time
Multi-level Page Tables
Untuk menghemat memori page table:
Two-Level Paging (x86):
┌───────────────┬───────────────┬────────────────┐
│ Directory │ Page Table │ Offset │
│ (10 bits) │ (10 bits) │ (12 bits) │
└───────┬──────┴───────┬───────┴────────────────┘
│ │
▼ │
┌─────────┐ │
│ Page │ ▼
│Directory│ ┌─────────┐
│ │───▶│ Page │
│ Entry │ │ Table │───▶ Physical Frame
└─────────┘ └─────────┘
Four-Level Paging (x86-64):
PML4 (9 bits) → PDPT (9 bits) → PD (9 bits) → PT (9 bits) → Offset (12 bits)
↓ ↓ ↓ ↓
512 entries 512 entries 512 entries 512 entries 4KB page
Segmentation
Segmentation membagi program berdasarkan logical divisions:
Logical View: Physical Memory:
┌────────────────┐ ┌────────────────────────┐
│ Code │──────────▶│ Code (at base 0x1000) │
│ Segment │ │ limit 0x500 │
├────────────────┤ ├────────────────────────┤
│ Data │──────────▶│ Data (at base 0x5000) │
│ Segment │ │ limit 0x300 │
├────────────────┤ ├────────────────────────┤
│ Stack │──────────▶│ Stack (at base 0x8000) │
│ Segment │ │ limit 0x1000 │
├────────────────┤ └────────────────────────┘
│ Heap │
│ Segment │
└────────────────┘
Segment Table:
┌─────────┬──────────┬─────────┐
│ Segment │ Base │ Limit │
├─────────┼──────────┼─────────┤
│ Code │ 0x1000 │ 0x500 │
│ Data │ 0x5000 │ 0x300 │
│ Stack │ 0x8000 │ 0x1000 │
│ Heap │ 0x9000 │ 0x2000 │
└─────────┴──────────┴─────────┘
Paging vs Segmentation
| Aspek | Paging | Segmentation |
|---|---|---|
| Unit Size | Fixed (4KB, dll) | Variable |
| Visibility | Invisible to programmer | Visible (code, data, stack) |
| Fragmentation | Internal | External |
| Sharing | Page-level | Segment-level (lebih natural) |
| Protection | Per page | Per segment |
8. Virtual Memory
Konsep Virtual Memory
Virtual Memory memungkinkan eksekusi proses yang tidak sepenuhnya ada di memori fisik. Bagian yang tidak dipakai disimpan di disk.
Keuntungan:
- Program bisa lebih besar dari RAM fisik
- Lebih banyak proses bisa berjalan bersamaan
- Efisiensi memori (hanya load yang diperlukan)
┌─────────────────────────────────────────────────────────┐
│ Virtual Address Space │
│ ┌──────────────────────────────────────────────────┐ │
│ │ Program besar (4GB) │ │
│ │ Hanya sebagian di RAM │ │
│ └──────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
│ │
│ Pages in RAM │ Pages on Disk
▼ ▼
┌──────────┐ ┌──────────────┐
│ Physical │ │ Swap Space │
│ Memory │ │ (Disk) │
│ (1GB) │ │ │
└──────────┘ └──────────────┘
Demand Paging
Hanya load page ketika diperlukan (on-demand).
Page Fault Handling:
1. CPU generates virtual address
│
▼
2. Check page table
┌───────────────────────┐
│ Valid bit = 0? │──── No ──▶ Access memory normally
└───────────┬───────────┘
│ Yes (Page Fault!)
▼
3. Trap to OS (page fault handler)
│
▼
4. Find page on disk (swap space)
│
▼
5. Find free frame in memory
(may need page replacement)
│
▼
6. Load page from disk to frame
│
▼
7. Update page table (valid = 1)
│
▼
8. Restart instruction
Effective Access Time dengan Page Fault: $$\text{EAT} = (1-p) \times t_{mem} + p \times t_{page_fault}$$
Dimana:
- $p$ = page fault rate
- $t_{page_fault}$ ≈ 10ms (disk access)
- $t_{mem}$ ≈ 100ns
Contoh: Jika p = 0.001: $\text{EAT} = 0.999 \times 100\text{ns} + 0.001 \times 10\text{ms} = 100\text{ns} + 10\mu\text{s} ≈ 10.1\mu\text{s}$
Page fault sangat mahal! Harus diminimalkan.
Page Replacement Algorithms
Ketika RAM penuh dan perlu load page baru, pilih victim page untuk di-swap out.
1. FIFO (First-In First-Out)
Replace page yang paling lama di memori.
Reference String: 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2
Frames: 3
Step Ref Frame State Fault?
1 7 [7, -, -] ✓
2 0 [7, 0, -] ✓
3 1 [7, 0, 1] ✓
4 2 [2, 0, 1] ✓ (replace 7)
5 0 [2, 0, 1]
6 3 [2, 3, 1] ✓ (replace 0)
7 0 [2, 3, 0] ✓ (replace 1)
8 4 [4, 3, 0] ✓ (replace 2)
...
Total Page Faults: 15
Belady’s Anomaly: FIFO bisa menghasilkan MORE page faults dengan MORE frames!
2. Optimal (OPT)
Replace page yang tidak akan digunakan untuk waktu terlama.
Reference String: 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2
Frames: 3
Step Ref Frame State Fault? Next Use
4 2 [2, 0, 1] ✓ 7 never used again
6 3 [2, 0, 3] ✓ 1 not used until later
8 4 [2, 4, 3] ✓ 0 not used until later
Total Page Faults: 9 (minimum possible)
- Optimal tapi tidak bisa diimplementasi (perlu future knowledge)
- Digunakan sebagai benchmark
3. LRU (Least Recently Used)
Replace page yang paling lama tidak diakses.
Reference String: 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2
Frames: 3
Menggunakan timestamp atau stack
Step Ref Frame State Fault? LRU victim
4 2 [2, 0, 1] ✓ 7 (oldest access)
6 3 [2, 0, 3] ✓ 1 (oldest access)
8 4 [4, 0, 3] ✓ 2 (oldest access)
Total Page Faults: 12
Implementasi LRU:
- Counter-based: Setiap page punya timestamp
- Stack-based: Page diakses → pindah ke top of stack
- Approximation: Reference bit (cheaper)
4. LRU Approximation Algorithms
Second Chance (Clock) Algorithm:
┌───────────────────────────────────────┐
│ Circular Buffer │
│ │
│ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │
│ │ A │ ─ │ B │ ─ │ C │ ─ │ D │ │
│ │R=1│ │R=0│ │R=1│ │R=0│ │
│ └───┘ └─▲─┘ └───┘ └───┘ │
│ │ │
│ pointer │
│ │
│ Algorithm: │
│ 1. If R=0: Replace this page │
│ 2. If R=1: Set R=0, move pointer │
│ 3. Repeat until victim found │
└───────────────────────────────────────┘
Enhanced Second Chance: Menggunakan (Reference bit, Modified bit):
| Class | (R, M) | Description | Priority |
|---|---|---|---|
| 0 | (0, 0) | Not recently used, not modified | Best victim |
| 1 | (0, 1) | Not recently used, modified | Need write to disk |
| 2 | (1, 0) | Recently used, not modified | Might be used again |
| 3 | (1, 1) | Recently used, modified | Worst victim |
Perbandingan FIFO vs LRU (3 Frames, Reference: 1,2,3,4,1,2,5,1,2,3)
Thrashing
Thrashing terjadi ketika sistem menghabiskan lebih banyak waktu untuk paging daripada eksekusi.
Thrashing: CPU Utilization vs Degree of Multiprogramming
Penyebab:
- Terlalu banyak proses
- Tidak cukup frame per proses
- Working set > available memory
Working Set Model: $$WS(t, \Delta) = \text{pages referenced in past } \Delta \text{ time units}$$
Jika $\sum WS_i > \text{total frames}$ → thrashing
Solusi:
- Suspend processes
- Increase RAM
- Use local replacement (proses hanya affect frame-nya sendiri)
Memory-Mapped Files
Map file langsung ke virtual address space:
// Memory-mapped file I/O
int fd = open("file.txt", O_RDWR);
char *addr = mmap(NULL, file_size, PROT_READ|PROT_WRITE,
MAP_SHARED, fd, 0);
// Access file like memory
addr[0] = 'H';
addr[1] = 'i';
// Changes automatically written to file
munmap(addr, file_size);
close(fd);
Keuntungan:
- No explicit read/write system calls
- Shared memory between processes
- Efficient for random access
Copy-on-Write (COW)
Optimisasi untuk fork():
Before fork():
┌─────────────┐ ┌─────────────┐
│ Parent │────▶│ Pages │
│ Process │ │ (shared) │
└─────────────┘ └─────────────┘
After fork() - COW:
┌─────────────┐ ┌─────────────┐
│ Parent │────▶│ Pages │◀───┐
│ Process │ │ (read-only) │ │
└─────────────┘ └─────────────┘ │
│
┌─────────────┐ │
│ Child │────────────────────────┘
│ Process │ (shares same pages)
└─────────────┘
After write by child:
┌─────────────┐ ┌─────────────┐
│ Parent │────▶│ Page A │
│ Process │ └─────────────┘
└─────────────┘
┌─────────────┐
┌─────────────┐ │ Page A' │ ← Copy created
│ Child │────▶│ (modified) │
│ Process │ └─────────────┘
└─────────────┘
Only copy page when modified → save memory and time!
9. File System
Konsep File
File adalah named collection of related information yang disimpan di secondary storage.
File Attributes:
| Attribute | Deskripsi |
|---|---|
| Name | Human-readable identifier |
| Type | Extension (OS-dependent) |
| Location | Pointer ke lokasi di disk |
| Size | Ukuran dalam bytes |
| Protection | Access rights (rwx) |
| Time | Created, modified, accessed |
| Owner | User ID |
File Operations:
- Create, Delete, Open, Close
- Read, Write, Seek (reposition)
- Truncate, Append
- Get/Set attributes
Directory Structure
Single-Level Directory:
┌─────────────────────────────────────────────┐
│ Root Directory │
├─────┬─────┬─────┬─────┬─────┬─────┬─────────┤
│file1│file2│file3│file4│file5│file6│ ... │
└─────┴─────┴─────┴─────┴─────┴─────┴─────────┘
- Sederhana, tapi naming collision
Two-Level Directory:
┌─────────────────────────────────────────────┐
│ Master Directory │
├─────────────────┬───────────────────────────┤
│ User 1 │ User 2 │
├─────┬─────┬─────┼─────┬─────┬───────────────┤
│file1│file2│file3│file1│file2│ ... │
└─────┴─────┴─────┴─────┴─────┴───────────────┘
Hierarchical (Tree) Directory:
/
┌─────────┼─────────┐
bin home etc
│ ┌───┴───┐ │
ls alice bob passwd
│ │
documents code
│ │
report.txt main.c
Acyclic-Graph Directory: Memungkinkan shared files/directories (hard links, symbolic links).
Path Names
Absolute Path: Dari root directory
/home/alice/documents/report.txt
Relative Path: Dari current directory
./documents/report.txt
../bob/code/main.c
File System Implementation
Disk Layout
┌──────────────────────────────────────────────────────┐
│ Boot │ Super │ Free Space │ Inode │ Data │
│ Block│ Block │ Management │ Table │ Blocks │
└──────┴───────┴────────────┴────────┴────────────────┘
| Block | Deskripsi |
|---|---|
| Boot Block | Bootstrap code untuk boot OS |
| Super Block | Metadata filesystem (size, #blocks, #inodes) |
| Free Space | Bitmap atau linked list untuk free blocks |
| Inode Table | Array of inodes (file metadata) |
| Data Blocks | Actual file contents |
Inode (Index Node)
┌────────────────────────────────────────────┐
│ INODE │
├────────────────────────────────────────────┤
│ Mode (permissions) : rwxr-xr-x │
│ Link count : 2 │
│ Owner UID : 1000 │
│ Group GID : 1000 │
│ File size : 4096 bytes │
│ Access time : ... │
│ Modify time : ... │
│ Change time : ... │
├────────────────────────────────────────────┤
│ Direct blocks (12) : [5,8,12,...] │
│ Single indirect : [ptr→block] │
│ Double indirect : [ptr→ptr→b] │
│ Triple indirect : [ptr→ptr→...]│
└────────────────────────────────────────────┘
Block Addressing:
Inode Block Addressing (Direct, Single, Double, Triple Indirect)
Maximum File Size (block = 4KB, pointer = 4 bytes):
- Direct: $12 \times 4\text{KB} = 48\text{KB}$
- Single: $1024 \times 4\text{KB} = 4\text{MB}$
- Double: $1024^2 \times 4\text{KB} = 4\text{GB}$
- Triple: $1024^3 \times 4\text{KB} = 4\text{TB}$
Directory Implementation
Directory adalah file khusus yang berisi list of (name, inode number):
┌──────────────────────────────────────┐
│ Directory File │
├──────────────────────┬───────────────┤
│ Name │ Inode Number │
├──────────────────────┼───────────────┤
│ "." │ 42 │ (current dir)
│ ".." │ 15 │ (parent dir)
│ "report.txt" │ 128 │
│ "code" │ 89 │ (subdirectory)
│ "image.png" │ 156 │
└──────────────────────┴───────────────┘
File Allocation Methods
1. Contiguous Allocation
┌────┬────┬────┬────┬────┬────┬────┬────┬────┬────┐
│ │ A │ A │ A │ │ B │ B │ │ C │ C │
└────┴────┴────┴────┴────┴────┴────┴────┴────┴────┘
0 1 2 3 4 5 6 7 8 9
Directory: file → (start, length)
A → (1, 3)
B → (5, 2)
C → (8, 2)
| Pros | Cons |
|---|---|
| Simple | External fragmentation |
| Sequential access cepat | Sulit grow file |
| Random access cepat | Perlu compaction |
2. Linked Allocation
┌────┬────┬────┬────┬────┬────┬────┬────┬────┬────┐
│ A3 │ │ B2 │ │ A1 │ B1 │ │ │ A2 │ │
│→8 │ │→-1 │ │→0 │→2 │ │ │→4 │ │
└────┴────┴────┴────┴────┴────┴────┴────┴────┴────┘
0 1 2 3 4 5 6 7 8 9
Directory: file → start
A → 4 (4→8→0→end)
B → 5 (5→2→end)
| Pros | Cons |
|---|---|
| No external fragmentation | Random access lambat |
| File bisa grow easily | Pointer overhead |
| Reliability (broken link = lost data) |
FAT (File Allocation Table):
FAT Table Disk Blocks
┌─────┬─────┐ ┌─────┐
│ 0 │ 8 │──────────│ A3 │
│ 1 │ -1 │ ├─────┤
│ 2 │ EOF │ │ B2 │
│ 3 │ -1 │ ├─────┤
│ 4 │ 0 │──────────│ │
│ 5 │ 2 │ ├─────┤
│ 6 │ -1 │ │ A1 │
│ 7 │ -1 │ ├─────┤
│ 8 │ 4 │──────────│ B1 │
└─────┴─────┘ └─────┘
3. Indexed Allocation
Index Block for File A: Data Blocks:
┌─────┐ ┌─────┐
│ 4 │───────────────────▶│Data0│ block 4
│ 8 │───────────────────▶│Data1│ block 8
│ 0 │───────────────────▶│Data2│ block 0
│ -1 │ └─────┘
└─────┘
Directory: file → index block
| Pros | Cons |
|---|---|
| Random access cepat | Index block overhead |
| No external fragmentation | Limited file size per index block |
Free Space Management
1. Bitmap (Bit Vector):
Block: 0 1 2 3 4 5 6 7 8 9
Bitmap: 0 1 1 1 0 1 1 0 1 1
│ │ │
free free free
2. Linked List:
Free List Head → Block 0 → Block 4 → Block 7 → NULL
Journaling File System
Problem: Crash during write → inconsistent state
Solution: Write-ahead logging
Transaction:
1. Write to journal (log):
"Delete file X from directory Y"
"Mark blocks 5,6,7 as free"
2. Apply changes to disk
3. Mark transaction as complete in journal
4. (Periodically) Clear old journal entries
Recovery:
- Replay uncommitted transactions from journal
- Or rollback incomplete transactions
Journaling Modes:
| Mode | Journal Contains | Consistency | Performance |
|---|---|---|---|
| Writeback | Metadata only | Low | Fast |
| Ordered | Metadata (data first) | Medium | Medium |
| Journal | Metadata + Data | High | Slow |
Virtual File System (VFS)
VFS adalah abstraction layer yang menyediakan interface seragam untuk berbagai filesystem.
┌─────────────────────────────────────────────────────┐
│ User Applications │
└───────────────────────┬─────────────────────────────┘
│ POSIX API (open, read, write)
▼
┌─────────────────────────────────────────────────────┐
│ Virtual File System (VFS) │
│ ┌──────────────────────────────────────────────┐ │
│ │ vnode, dentry, superblock, file operations │ │
│ └──────────────────────────────────────────────┘ │
└───────────┬──────────────┬──────────────┬───────────┘
│ │ │
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ ext4 │ │ NTFS │ │ NFS │
│ driver │ │ driver │ │ driver │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
┌────▼────┐ ┌────▼────┐ ┌────▼────┐
│ Disk │ │ Disk │ │ Network │
└─────────┘ └─────────┘ └─────────┘
Common File Systems
| File System | OS | Max File Size | Max Volume | Features |
|---|---|---|---|---|
| ext4 | Linux | 16 TB | 1 EB | Journaling, extents |
| XFS | Linux | 8 EB | 8 EB | High performance |
| Btrfs | Linux | 16 EB | 16 EB | COW, snapshots |
| NTFS | Windows | 16 EB | 16 EB | Journaling, ACL |
| APFS | macOS | 8 EB | 8 EB | COW, encryption |
| FAT32 | All | 4 GB | 2 TB | Simple, compatible |
| exFAT | All | 16 EB | 128 PB | Flash optimized |
10. Sistem I/O
I/O Hardware
Device Categories:
| Category | Examples | Characteristics |
|---|---|---|
| Block Devices | HDD, SSD, USB drive | Fixed-size blocks, seekable |
| Character Devices | Keyboard, mouse, serial | Stream of characters |
| Network Devices | Ethernet, WiFi | Packet-based |
I/O Port vs Memory-Mapped I/O:
Port-Mapped I/O: Memory-Mapped I/O:
┌────────────────┐ ┌────────────────┐
│ CPU │ │ CPU │
└───────┬────────┘ └───────┬────────┘
│ │
┌────┴────┐ ┌──────┴──────┐
│ I/O Bus │ │ Memory Bus │
└────┬────┘ └──────┬──────┘
│ │
┌───────┴───────┐ ┌────────┴────────┐
│ Device Ports │ │ Memory │
│ (0x60, 0x64) │ │ ┌────────────┐ │
└───────────────┘ │ │ RAM │ │
│ ├────────────┤ │
Special I/O instructions │ │ Device Regs│ │
(IN, OUT) │ │ 0xF0000000 │ │
│ └────────────┘ │
└─────────────────┘
Normal memory instructions
I/O Methods
1. Polling (Programmed I/O)
CPU terus-menerus check device status.
// Write character to device
while (status_register & BUSY)
; // Busy wait
data_register = character;
command_register = WRITE;
CPU Device
│ │
│──check status│
│◀────busy─────│
│──check status│
│◀────busy─────│
│──check status│
│◀────ready────│
│──write data──│▶
│ │
Pros: Simple, low latency untuk fast devices Cons: CPU waste time waiting
2. Interrupt-Driven I/O
CPU melakukan kerja lain, device interrupt ketika siap.
CPU Device
│ │
│──start I/O──────│▶
│ │ (device working)
│ (do other work) │
│ │
│◀───interrupt────│
│──read data──────│
│ │
Interrupt Handling:
1. Device raises interrupt (IRQ)
2. CPU finishes current instruction
3. CPU saves state (registers, PC)
4. CPU jumps to Interrupt Handler
5. Handler processes interrupt
6. Handler acknowledges interrupt
7. CPU restores state
8. CPU resumes execution
3. Direct Memory Access (DMA)
DMA controller transfers data directly between device and memory.
┌─────────────────────────────────────────┐
│ CPU │
│ 1. Setup DMA 4. Handle interrupt │
└────────┬────────────────┬───────────────┘
│ ▲
Setup│ Interrupt
▼ │
┌────────────────────────────────────────┐
│ DMA Controller │
│ │
│ 2. Transfer data (no CPU involvement) │
│ Device ←→ Memory │
│ │
│ 3. Raise interrupt when done │
└────────┬────────────────┬──────────────┘
│ │
▼ ▼
┌──────────┐ ┌──────────┐
│ Device │ │ Memory │
└──────────┘ └──────────┘
DMA Transfer Steps:
- CPU programs DMA: source, destination, count
- DMA takes over bus, transfers data
- DMA interrupts CPU when complete
- CPU handles interrupt
Perbandingan I/O Methods: CPU Utilization
Device Drivers
Driver adalah software yang mengontrol specific device.
┌─────────────────────────────────────────────────┐
│ Application │
└────────────────────┬────────────────────────────┘
│ System Call (read, write)
▼
┌─────────────────────────────────────────────────┐
│ Kernel I/O Subsystem │
│ • Buffering • Caching • Scheduling │
└────────────────────┬────────────────────────────┘
│ Uniform Driver Interface
▼
┌───────────────┬───────────────┬─────────────────┐
│ Disk Driver │ Network Driver│ Keyboard Driver │
└───────┬───────┴───────┬───────┴────────┬────────┘
│ │ │
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Disk │ │ NIC │ │ Keyboard│
└─────────┘ └─────────┘ └─────────┘
Disk Scheduling
Untuk HDD dengan mechanical arm, urutan akses mempengaruhi performance.
Disk Structure:
┌──────────────────────────────────────┐
│ Disk Platter │
│ │
│ ╭────────────────────────────╮ │
│ │ Track 0 (outermost) │ │
│ │ ╭──────────────────────╮ │ │
│ │ │ Track 1 │ │ │
│ │ │ ╭──────────────╮ │ │ │
│ │ │ │ Track 2 │ │ │ │
│ │ │ │ ... │ │ │ │
│ │ ╰───┴──────────────┴───╯ │ │
│ ╰────────────────────────────╯ │
│ │
│ ← Head movement → │
└──────────────────────────────────────┘
Disk Scheduling Algorithms:
Request Queue: 98, 183, 37, 122, 14, 124, 65, 67 Head starts at: 53
1. FCFS (First Come First Served)
Service order: 53→98→183→37→122→14→124→65→67
↓
|----45----|
|----85----|
|----146----|
|----85----|
|----108----|
|----110----|
|----59----|
|--2--|
Total head movement: 640 cylinders
2. SSTF (Shortest Seek Time First)
Pilih request terdekat dari posisi head saat ini.
53→65→67→37→14→98→122→124→183
Total head movement: 236 cylinders
Problem: Starvation untuk request jauh dari head
3. SCAN (Elevator Algorithm)
Head bergerak satu arah sampai ujung, lalu balik.
Direction: toward 0 first
53→37→14→0→65→67→98→122→124→183
│
0 ├───○───────────────────────────────────────────────────▶ 199
│ 14 37 53 65 67 98 122 124 183
│ ↑ ↑ │ ↓ ↓ ↓ ↓ ↓ ↓
│ └───┴────┘ │ │ │ │ │ │
│ └──┴──────┴──────┴───┴──────────┘
Total head movement: 236 cylinders
4. C-SCAN (Circular SCAN)
Saat sampai ujung, langsung jump ke ujung satunya.
53→65→67→98→122→124→183→199→0→14→37
────────────────────────▶
53 65 67 98 122 124 183 199
│ ↓ ↓ ↓ ↓ ↓ ↓ │
│ └──┴───┴─────┴───┴──────┴────┘
│ │
└──────────────────────────────┘ (jump back to 0)
0 14 37
↓ ↓ ↓
└────┴───┘
Total head movement: 183 + 199 + 37 = 382 cylinders (but uniform wait)
5. LOOK / C-LOOK
Sama seperti SCAN/C-SCAN tapi tidak pergi sampai ujung disk, hanya sampai request terjauh.
C-LOOK:
53→65→67→98→122→124→183→14→37
Total head movement: 130 + 169 + 23 = 322 cylinders
Perbandingan Disk Scheduling (Start: 53, Requests: 98, 183, 37, 122, 14, 124, 65, 67)
Buffering and Caching
Buffer: Temporary storage during transfer Cache: Fast storage for frequently accessed data
┌──────────────────────────────────────────────────────────┐
│ Application │
└─────────────────────────────┬────────────────────────────┘
│
┌───────────────▼───────────────┐
│ User Buffer │
└───────────────┬───────────────┘
│ copy_from_user()
┌───────────────▼───────────────┐
│ Kernel Buffer │
│ (Page Cache) │
└───────────────┬───────────────┘
│ DMA
┌───────────────▼───────────────┐
│ Device Controller │
│ Buffer │
└───────────────┬───────────────┘
│
┌───────────────▼───────────────┐
│ Disk │
└───────────────────────────────┘
Double Buffering:
Time 1: DMA fills Buffer A │ CPU processes Buffer B
Time 2: DMA fills Buffer B │ CPU processes Buffer A
Time 3: DMA fills Buffer A │ CPU processes Buffer B
...
RAID (Redundant Array of Independent Disks)
| Level | Description | Redundancy | Performance | Capacity |
|---|---|---|---|---|
| RAID 0 | Striping | None | Read/Write ↑↑ | N disks |
| RAID 1 | Mirroring | 1 disk fail | Read ↑ | N/2 disks |
| RAID 5 | Striping + Distributed Parity | 1 disk fail | Read ↑, Write ↓ | N-1 disks |
| RAID 6 | Double Parity | 2 disk fail | Read ↑, Write ↓↓ | N-2 disks |
| RAID 10 | Mirror + Stripe | 1 per mirror | Read/Write ↑↑ | N/2 disks |
Perbandingan RAID Levels
Recovery pada RAID 5: Jika Disk 1 gagal, data dapat direkonstruksi: D1 = Dp XOR D2 XOR D3
11. Security dan Protection
Protection vs Security
| Protection | Security |
|---|---|
| Internal mechanism | External threats |
| Control access to resources | Defend against attacks |
| Policies and mechanisms | Confidentiality, Integrity, Availability |
| Who can do what | How to ensure it |
Protection Domain
Domain = set of (object, access-rights) pairs
Domain D1: { (File1, read), (File2, read/write), (Printer1, print) }
Domain D2: { (File1, execute), (File3, read) }
Access Matrix:
│ File1 │ File2 │ File3 │ Printer1 │
──────────────┼──────────┼──────────┼──────────┼──────────┤
Domain 1 │ read │ read │ │ print │
│ │ write │ │ │
──────────────┼──────────┼──────────┼──────────┼──────────┤
Domain 2 │ execute │ │ read │ │
──────────────┼──────────┼──────────┼──────────┼──────────┤
Domain 3 │ read │ read │ execute │ print │
│ execute │ │ │ │
Access Control Implementation
1. Access Control List (ACL)
Per-object list of (subject, rights).
File1.acl:
┌────────────────────────────┐
│ User: alice │ rwx │
│ User: bob │ r-- │
│ Group: dev │ r-x │
│ Other │ --- │
└────────────────────────────┘
Unix Permissions:
-rwxr-xr-- 1 alice dev 4096 Jan 24 12:00 file.txt
│││ │││ │││
│││ │││ └┴┴─ Other: r--
│││ └┴┴───── Group: r-x
└┴┴───────── Owner: rwx
Octal: 754
Special Permissions:
| Bit | Name | Effect on File | Effect on Directory |
|---|---|---|---|
| SetUID (4) | Set User ID | Run as owner | - |
| SetGID (2) | Set Group ID | Run as group | Inherit group |
| Sticky (1) | Sticky Bit | - | Only owner can delete |
# SetUID example
-rwsr-xr-x root root /usr/bin/passwd
^
SetUID - runs as root regardless of who executes
2. Capability List
Per-subject list of (object, rights).
Alice's Capabilities:
┌─────────────────────────────────┐
│ Cap 1: (File1, rwx, key123) │
│ Cap 2: (Printer1, print, key456)│
│ Cap 3: (Process2, signal, key789)│
└─────────────────────────────────┘
ACL vs Capability:
| ACL | Capability |
|---|---|
| Easy to see who has access to object | Easy to see what subject can access |
| Easy to revoke all access to object | Easy to transfer access rights |
| Hard to revoke user’s access to all | Hard to revoke all access to object |
Authentication
Something you:
- Know: Password, PIN
- Have: Token, smart card, phone
- Are: Fingerprint, face, iris
Multi-Factor Authentication (MFA): Combine 2+ factors
Password Security:
Storage: hash(password + salt)
┌──────────────────────────────────────────────────┐
│ Password: "secret123" │
│ Salt: "x7Km2p" (random per user) │
│ Hash: bcrypt("secret123" + "x7Km2p") │
│ = "$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqh"│
└──────────────────────────────────────────────────┘
Common Security Threats
1. Buffer Overflow
Stack Buffer Overflow Attack
// Vulnerable code
void vulnerable(char *input) {
char buffer[64];
strcpy(buffer, input); // No bounds check!
}
Protections:
- Stack Canaries: Detect overflow before return
- ASLR: Randomize address layout
- DEP/NX: Non-executable stack
- Safe functions:
strncpy,snprintf
2. Privilege Escalation
Gaining higher privileges than authorized.
Normal User → Root/Admin access
Methods:
- Exploit SetUID binaries
- Kernel vulnerabilities
- Misconfigured services
3. SQL Injection
Input: ' OR '1'='1' --
Query: SELECT * FROM users WHERE name='' OR '1'='1' --'
^^^^^^^^^
Always true!
4. Race Condition (TOCTOU)
Time-of-Check to Time-of-Use vulnerability.
// Vulnerable pattern
if (access("file", W_OK) == 0) { // Check
// Window of vulnerability here!
// Attacker can swap "file" with symlink
file = open("file", O_WRONLY); // Use
write(file, data, len);
}
Security Mechanisms
Sandboxing
Isolate untrusted code:
┌─────────────────────────────────────────────┐
│ Host OS │
│ ┌───────────────────────────────────────┐ │
│ │ Sandbox │ │
│ │ ┌─────────────────────────────────┐ │ │
│ │ │ Untrusted Application │ │ │
│ │ │ │ │ │
│ │ │ Limited access to: │ │ │
│ │ │ - Filesystem (chroot/jail) │ │ │
│ │ │ - Network (filtered) │ │ │
│ │ │ - System calls (seccomp) │ │ │
│ │ └─────────────────────────────────┘ │ │
│ └───────────────────────────────────────┘ │
└─────────────────────────────────────────────┘
Technologies:
- chroot: Filesystem isolation
- seccomp: System call filtering
- Containers: Docker, LXC
- VMs: Full isolation
Mandatory Access Control (MAC)
System-enforced policies (vs discretionary/DAC).
SELinux/AppArmor:
# SELinux policy example
allow httpd_t httpd_content_t : file { read getattr };
^ ^ ^ ^
source target class permissions
domain type
Encryption
At Rest: Disk encryption (LUKS, BitLocker, FileVault) In Transit: TLS/SSL, VPN
Full Disk Encryption:
┌─────────────────────────────────────┐
│ Boot → Enter passphrase → Decrypt │
│ │
│ ┌────────────────────────────────┐ │
│ │ Encrypted Partition │ │
│ │ (all data encrypted with key) │ │
│ └────────────────────────────────┘ │
└─────────────────────────────────────┘
Principle of Least Privilege
“Every program and user should operate using the least set of privileges necessary to complete the job.”
Examples:
- Web server doesn’t need root
- User programs shouldn’t access kernel memory
- Services run as dedicated users, not root
12. Virtualisasi
Konsep Virtualisasi
Virtualisasi memungkinkan menjalankan beberapa OS/environment di satu hardware fisik.
┌─────────────────────────────────────────────────────────┐
│ Hardware │
├─────────────────────────────────────────────────────────┤
│ Hypervisor (VMM) │
├────────────────┬────────────────┬───────────────────────┤
│ VM 1 │ VM 2 │ VM 3 │
│ ┌───────────┐ │ ┌───────────┐ │ ┌───────────────────┐ │
│ │Guest OS │ │ │Guest OS │ │ │Guest OS │ │
│ │ (Linux) │ │ │ (Windows) │ │ │ (FreeBSD) │ │
│ ├───────────┤ │ ├───────────┤ │ ├───────────────────┤ │
│ │ Apps │ │ │ Apps │ │ │ Apps │ │
│ └───────────┘ │ └───────────┘ │ └───────────────────┘ │
└────────────────┴────────────────┴───────────────────────┘
Tipe Hypervisor
Type 1 (Bare-Metal)
Langsung di atas hardware.
┌───────────────────────────────────┐
│ VM 1 │ VM 2 │
├───────────────┴──────────────────┤
│ Type 1 Hypervisor │
│ (VMware ESXi, Xen, Hyper-V) │
├──────────────────────────────────┤
│ Hardware │
└──────────────────────────────────┘
Examples: VMware ESXi, Xen, Microsoft Hyper-V, KVM
Type 2 (Hosted)
Berjalan di atas Host OS.
┌───────────────────────────────────┐
│ VM 1 │ VM 2 │
├───────────────┴──────────────────┤
│ Type 2 Hypervisor │
│ (VirtualBox, VMware Workstation)│
├──────────────────────────────────┤
│ Host OS │
├──────────────────────────────────┤
│ Hardware │
└──────────────────────────────────┘
Examples: VirtualBox, VMware Workstation, Parallels
Virtualization Techniques
1. Full Virtualization
Guest OS tidak perlu dimodifikasi.
Guest OS instruction (privileged)
│
▼
┌─────────┐
│ VMM │─── Binary Translation atau
│ traps │ Hardware Virtualization
└────┬────┘
▼
Execute safely
Hardware Support:
- Intel VT-x
- AMD-V
2. Paravirtualization
Guest OS dimodifikasi untuk bekerja sama dengan hypervisor.
Guest OS (modified)
│
│ Hypercall (instead of privileged instruction)
▼
┌─────────┐
│ VMM │
└─────────┘
Examples: Xen (paravirtualized guests)
Pros: Better performance Cons: Need modified guest OS
Memory Virtualization
Guest Virtual → Guest Physical → Host Physical
(GVA) (GPA) (HPA)
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Guest Page │ │ Shadow Page │ │ Physical │
│ Table │───▶│ Table │───▶│ Memory │
│ │ │ (maintained │ │ │
│ │ │ by VMM) │ │ │
└─────────────┘ └─────────────┘ └─────────────┘
EPT/NPT (Extended/Nested Page Tables): Hardware support for two-level translation (GVA→GPA→HPA).
I/O Virtualization
Emulation:
Guest → Virtual Device → VMM → Real Device
(slow)
Paravirtualized I/O (virtio):
Guest (virtio driver) → VMM → Real Device
(faster)
Device Passthrough (SR-IOV):
Guest → Direct access to physical device
(native performance)
Container Virtualization
Containers share host kernel, isolate processes.
┌─────────────────────────────────────────────────────────┐
│ Host OS Kernel │
├──────────────┬──────────────┬──────────────┬────────────┤
│ Container 1 │ Container 2 │ Container 3 │ Container 4│
│ ┌──────────┐ │ ┌──────────┐ │ ┌──────────┐ │ ┌────────┐ │
│ │ App A │ │ │ App B │ │ │ App C │ │ │ App D │ │
│ ├──────────┤ │ ├──────────┤ │ ├──────────┤ │ ├────────┤ │
│ │ Libs │ │ │ Libs │ │ │ Libs │ │ │ Libs │ │
│ └──────────┘ │ └──────────┘ │ └──────────┘ │ └────────┘ │
└──────────────┴──────────────┴──────────────┴────────────┘
VM vs Container:
| Aspect | Virtual Machine | Container |
|---|---|---|
| Isolation | Full (separate kernel) | Process-level (shared kernel) |
| Startup | Minutes | Seconds |
| Size | GBs | MBs |
| Performance | Near-native | Native |
| Security | Strong isolation | Weaker isolation |
Arsitektur: Virtual Machine vs Container
Linux Container Technologies:
- Namespaces: Isolate system resources
- PID, Network, Mount, User, UTS, IPC, Cgroup
- cgroups: Limit and account resources
- CPU, Memory, I/O, Network
- UnionFS/OverlayFS: Layered filesystem
Docker Image Layers:
┌─────────────────────────┐
│ Writeable Layer │ ← Container changes
├─────────────────────────┤
│ Application Code │
├─────────────────────────┤
│ Dependencies │
├─────────────────────────┤
│ Base Image (Ubuntu) │
└─────────────────────────┘
13. Sistem Operasi Modern
Real-Time Operating Systems (RTOS)
Hard Real-Time: Deadline HARUS dipenuhi
- Contoh: Pacemaker, ABS brakes
- Missing deadline = catastrophic failure
Soft Real-Time: Deadline sebaiknya dipenuhi
- Contoh: Video streaming, gaming
- Missing deadline = degraded quality
RTOS Characteristics:
- Deterministic scheduling
- Priority-based preemption
- Minimal interrupt latency
- No virtual memory (usually)
Examples: FreeRTOS, VxWorks, QNX, RTLinux
Distributed Operating Systems
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Node 1 │ │ Node 2 │ │ Node 3 │
│ ┌───────┐ │ │ ┌───────┐ │ │ ┌───────┐ │
│ │ App │ │ │ │ App │ │ │ │ App │ │
│ └───────┘ │ │ └───────┘ │ │ └───────┘ │
│ ┌───────┐ │ │ ┌───────┐ │ │ ┌───────┐ │
│ │ OS │ │ │ │ OS │ │ │ │ OS │ │
│ └───┬───┘ │ │ └───┬───┘ │ │ └───┬───┘ │
└──────┼──────┘ └──────┼──────┘ └──────┼──────┘
│ │ │
└──────────────────┴──────────────────┘
Network
Challenges:
- No shared memory
- Network latency
- Partial failures
- Clock synchronization
Mobile Operating Systems
Characteristics:
- Power efficiency critical
- Touch interface
- Limited resources
- App sandboxing
Examples:
- Android: Linux kernel + ART runtime
- iOS: XNU kernel (Darwin-based)
Android Architecture:
┌───────────────────────────────────┐
│ Applications │
├───────────────────────────────────┤
│ Application Framework │
│ (Activity Manager, etc.) │
├───────────────────────────────────┤
│ Android Runtime (ART) │
│ Native Libraries (C/C++) │
├───────────────────────────────────┤
│ Hardware Abstraction Layer │
├───────────────────────────────────┤
│ Linux Kernel │
└───────────────────────────────────┘
Embedded Operating Systems
- Resource constrained (KB of RAM)
- Specific hardware
- Often no MMU
- Examples: Embedded Linux, Zephyr, NuttX
Cloud and Serverless
Cloud Computing Models:
┌─────────────────────────────────────────────────────────┐
│ IaaS (Infrastructure) │
│ Virtual Machines, Storage, Network │
│ (AWS EC2, Google Compute Engine) │
├─────────────────────────────────────────────────────────┤
│ PaaS (Platform) │
│ Runtime, Database, Development Tools │
│ (Heroku, Google App Engine) │
├─────────────────────────────────────────────────────────┤
│ FaaS/Serverless │
│ Function execution only │
│ (AWS Lambda, Cloud Functions) │
└─────────────────────────────────────────────────────────┘
14. Linux Commands Cheatsheet
Process Management
# View processes
ps aux # List all processes
top / htop # Interactive process viewer
pstree # Process tree
# Process control
kill PID # Send SIGTERM
kill -9 PID # Send SIGKILL (force)
killall name # Kill by name
nice -n 10 command # Run with priority
renice -n 5 -p PID # Change priority
# Background/Foreground
command & # Run in background
jobs # List background jobs
fg %1 # Bring job 1 to foreground
bg %1 # Resume job 1 in background
nohup command & # Run immune to hangups
Memory
free -h # Memory usage
vmstat 1 # Virtual memory stats
cat /proc/meminfo # Detailed memory info
pmap PID # Process memory map
Disk & File System
df -h # Disk space usage
du -sh directory # Directory size
lsblk # List block devices
mount /dev/sdb1 /mnt # Mount filesystem
umount /mnt # Unmount
fdisk -l # Partition table
# File permissions
chmod 755 file # rwxr-xr-x
chmod u+x file # Add execute for owner
chown user:group file # Change ownership
System Information
uname -a # Kernel info
cat /etc/os-release # OS info
uptime # System uptime
dmesg # Kernel messages
lscpu # CPU info
lspci # PCI devices
lsusb # USB devices
Network
ip addr # Network interfaces
ip route # Routing table
ss -tuln # Listening ports
netstat -tuln # (legacy) Listening ports
ping host # Test connectivity
traceroute host # Trace route
curl -I url # HTTP headers
Service Management (systemd)
systemctl start service # Start service
systemctl stop service # Stop service
systemctl restart service
systemctl status service # Check status
systemctl enable service # Enable at boot
journalctl -u service # Service logs
15. Rangkuman Cepat
Formula Penting
Effective Access Time (EAT): $$\text{EAT} = h \times t_{cache} + (1-h) \times t_{memory}$$
Page Fault EAT: $$\text{EAT} = (1-p) \times t_{mem} + p \times t_{page_fault}$$
Disk Access Time: $$T_{access} = T_{seek} + T_{rotation} + T_{transfer}$$
CPU Utilization (n processes, I/O wait = p): $$\text{Utilization} = 1 - p^n$$
Comparison Tables
Scheduling Algorithms:
| Algorithm | Preemptive | Starvation | Overhead |
|---|---|---|---|
| FCFS | No | No | Low |
| SJF | No | Yes | Medium |
| SRTF | Yes | Yes | High |
| Priority | Both | Yes | Medium |
| Round Robin | Yes | No | High |
| MLFQ | Yes | No | High |
Page Replacement:
| Algorithm | Optimal | Practical | Belady’s Anomaly |
|---|---|---|---|
| FIFO | No | Yes | Yes |
| OPT | Yes | No | No |
| LRU | Near-optimal | Expensive | No |
| Clock | Approximation | Yes | No |
Key Concepts Summary
- Kernel Mode vs User Mode: Privilege separation
- Process vs Thread: Heavyweight vs lightweight execution
- Deadlock Conditions: Mutual exclusion, hold & wait, no preemption, circular wait
- Virtual Memory: Address abstraction, demand paging
- File System: Hierarchy, inodes, journaling
- Security: Authentication, authorization, encryption
- Virtualization: Hypervisors, containers, isolation