Sistem Operasi: Cheatsheet Komprehensif

Akmal
operating-system computer-science process memory kernel

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

TipeDeskripsiContohKelebihanKekurangan
MonolithicSemua layanan OS berjalan di kernel spaceLinux, UnixPerforma tinggiKurang modular, crash = sistem down
MicrokernelKernel minimal, layanan di user spaceMinix, QNX, L4Stabil, modularOverhead IPC
HybridKombinasi monolithic + microkernelWindows NT, macOSBalance performa & modularitasKompleksitas
ExokernelKernel sangat minimal, aplikasi kelola hardwareMIT ExokernelFleksibel, efisienSulit 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:

  1. User program memanggil library function (misal: write())
  2. Library wrapper menyiapkan parameter dan system call number
  3. Trap instruction (syscall, int 0x80, SVC) memicu mode switch
  4. Kernel menyimpan context user (registers, stack pointer)
  5. System call handler mengeksekusi fungsi kernel sesuai nomor
  6. Kernel mengembalikan hasil ke user space
  7. 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:

KategoriContohDeskripsi
Process Controlfork(), exec(), exit(), wait()Membuat, menghentikan, dan mengontrol proses
File Managementopen(), read(), write(), close(), stat()Operasi file dan direktori
Device Managementioctl(), read(), write()Mengakses dan mengontrol device
Information Maintenancegetpid(), gettimeofday(), sysinfo()Mendapatkan informasi sistem
Communicationpipe(), shmget(), msgget(), socket()IPC dan komunikasi jaringan
Protectionchmod(), 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:

OSInstructionCalling ConventionRegister untuk syscall number
Linux x86-64syscallRDI, RSI, RDX, R10, R8, R9RAX
Linux x86-32int 0x80Stack (EBX, ECX, EDX, …)EAX
Windows x64syscallRCX, RDX, R8, R9, stackRAX
macOS/BSDsyscallRDI, RSI, RDX, R10, R8, R9RAX
ARM64svc #0X0-X7X8

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, atau io_uring untuk mengurangi blocking

System Call vs Library Function:

System CallLibrary Function
Interface langsung ke kernelWrapper di atas system call
Harus melalui trapBisa 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:

ProgramProses
Passive entity (file di disk)Active entity (running)
Tidak punya statePunya state (running, waiting, etc.)
Tidak punya resourcesMemiliki 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)

NEW READY RUNNING WAITING TERMINATED admit dispatch preempt/timeout I/O wait I/O done exit
New (Created)
Ready (Waiting for CPU)
Running (Executing)
Waiting (Blocked)
Terminated (Exit)

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

Process P0 Kernel Process P1 Running interrupt/syscall Save P0 state to PCB₀ Schedule P1 Load P1 state from PCB₁ dispatch idle idle Running t₀ t₁ t₂ Overhead
Context Switch Overhead: Waktu untuk save/restore registers, flush cache (TLB, CPU cache), dan pipeline flush. Semakin sering context switch = semakin banyak overhead!

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)

MetodeDeskripsiUse Case
PipeUnidirectional byte streamParent-child communication
Named Pipe (FIFO)Pipe dengan nama di filesystemUnrelated processes
Message QueueAntrian pesan terstrukturProducer-consumer
Shared MemoryRegion memori yang di-shareHigh-speed data sharing
SemaphoreSignaling mechanismSynchronization
SocketNetwork-style communicationLocal or network IPC
SignalAsynchronous notificationEvent 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

AspekProcessThread
Address SpaceTerpisahShared
CommunicationIPC (mahal)Shared memory (murah)
Creation CostTinggiRendah
Context SwitchMahalMurah
IsolationTinggi (crash terpisah)Rendah (crash = semua mati)
OverheadLebih beratLebih 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:

FungsiDeskripsi
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:

  1. Proses switch dari running ke waiting (I/O)
  2. Proses switch dari running ke ready (interrupt)
  3. Proses switch dari waiting ke ready (I/O complete)
  4. Proses terminasi

Non-preemptive vs Preemptive:

Non-preemptivePreemptive
Proses jalan sampai selesai/blockProses bisa diinterupsi
SederhanaLebih kompleks
Response time burukResponse time baik
Contoh: FCFS, SJFContoh: Round Robin, SRTF

Kriteria Scheduling

KriteriaDefinisiGoal
CPU Utilization% waktu CPU sibukMaximize
ThroughputJumlah proses selesai/waktuMaximize
Turnaround TimeWaktu dari submit sampai selesaiMinimize
Waiting TimeWaktu menunggu di ready queueMinimize
Response TimeWaktu dari submit sampai response pertamaMinimize

Algoritma Scheduling

1. First-Come First-Served (FCFS)

Ready Queue: P1 → P2 → P3 → CPU

Urutan kedatangan = urutan eksekusi

Contoh:

ProcessBurst Time
P124
P23
P33
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)

FCFS:
P1 (24)
P2
P3
0 24 27 30
SJF:
P2
P3
P1 (24)
0 3 6 30
FCFS Avg Wait
(0+24+27)/3 = 17
SJF Avg Wait
(0+3+6)/3 = 3

2. Shortest Job First (SJF)

Proses dengan burst time terpendek dieksekusi duluan.

Non-preemptive SJF:

ProcessArrivalBurst
P107
P224
P341
P454
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:

ProcessBurst Time
P124
P23
P33
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:

  1. Mutual Exclusion: Hanya satu proses di critical section
  2. Progress: Jika tidak ada di CS, proses yang mau masuk tidak boleh diblock selamanya
  3. 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

Producer in A B C out Consumer Bounded Buffer (size = 8) wait(empty) signal(full) wait(full) signal(empty) full = 3, empty = 5
Semaphore: 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

P0 P1 P2 P3 P4 F0 F1 F2 F3 F4
Thinking
Eating
Waiting
Problem: 5 philosopher, 5 fork. Untuk makan, philosopher butuh 2 fork (kiri & kanan). Jika semua ambil fork kiri bersamaan → Deadlock!

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:

KondisiDeskripsi
1. Mutual ExclusionResource hanya bisa digunakan satu proses pada satu waktu
2. Hold and WaitProses memegang resource sambil menunggu resource lain
3. No PreemptionResource tidak bisa diambil paksa dari proses
4. Circular WaitAda rantai circular: P1→P2→P3→…→P1

Resource Allocation Graph (RAG)

Resource Allocation Graph - Contoh Deadlock

R1 R2 P1 P2 ⚠ CYCLE DETECTED = DEADLOCK
Process
Resource
Assignment
Request
Deadlock: P1 holds R1, waits for R2. P2 holds R2, waits for R1 → Circular wait!

Strategi Penanganan Deadlock

1. Deadlock Prevention

Cegah salah satu dari 4 kondisi:

KondisiCara Mencegah
Mutual ExclusionGunakan sharable resources (jarang bisa)
Hold and WaitRequest semua resource sekaligus
No PreemptionPaksa release jika request gagal
Circular WaitOrder 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 tersedia
  • Max[n][m]: Maximum demand setiap proses
  • Allocation[n][m]: Resource yang sudah dialokasi
  • Need[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)

~1 ns Registers bytes
~2 ns L1 Cache 64 KB
~7 ns L2 Cache 256 KB
~20 ns L3 Cache 8+ MB
~100 ns Main Memory (RAM) GB
~100 µs SSD / NVMe TB
~10 ms HDD (Hard Disk) TB
Faster Smaller Expensive
Slower Larger Cheaper

Address Binding

Kapan address ditentukan:

TahapDeskripsiFlexibility
Compile TimeAddress absolut di-generate saat compileHarus recompile jika pindah
Load TimeAddress ditentukan saat program di-loadRelocatable code
Execution TimeAddress ditentukan saat runtimePerlu 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:

StrategyDeskripsiPros/Cons
First FitCari hole pertama yang cukupCepat
Best FitCari hole terkecil yang cukupMinimize waste, tapi banyak small holes
Worst FitCari hole terbesarLeave 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)

Logical:
Page Number
20 bits
Offset
12 bits
Page Table
Page 0 → Frame 5
Page 1 → Frame 2
Page 2 → Frame 7
Page 3 → Frame 1
Physical:
Frame Number
dari table
Offset
tetap sama
Contoh: Jika Page Number = 2, lookup di Page Table → Frame 7. Offset tetap sama, sehingga Physical Address = Frame 7 + Offset.

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

AspekPagingSegmentation
Unit SizeFixed (4KB, dll)Variable
VisibilityInvisible to programmerVisible (code, data, stack)
FragmentationInternalExternal
SharingPage-levelSegment-level (lebih natural)
ProtectionPer pagePer 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)DescriptionPriority
0(0, 0)Not recently used, not modifiedBest victim
1(0, 1)Not recently used, modifiedNeed write to disk
2(1, 0)Recently used, not modifiedMight be used again
3(1, 1)Recently used, modifiedWorst victim

Perbandingan FIFO vs LRU (3 Frames, Reference: 1,2,3,4,1,2,5,1,2,3)

FIFO
1
1
-
-
F
2
1
2
-
F
3
1
2
3
F
4
4
2
3
F
1
4
1
3
F
2
4
1
2
F
5
5
1
2
F
1
5
1
2
2
5
1
2
3
5
3
2
F
Page Faults: 8
LRU
1
1
-
-
F
2
1
2
-
F
3
1
2
3
F
4
4
2
3
F
1
4
1
3
F
2
4
1
2
F
5
5
1
2
F
1
5
1
2
2
5
1
2
3
3
1
2
F
Page Faults: 8

Thrashing

Thrashing terjadi ketika sistem menghabiskan lebih banyak waktu untuk paging daripada eksekusi.

Thrashing: CPU Utilization vs Degree of Multiprogramming

Degree of Multiprogramming CPU Utilization 100% 50% 0% Optimal Peak Thrashing! ↓ CPU drops due to page faults
⚠ Thrashing: Terlalu banyak proses → tidak cukup frame per proses → page fault terus-menerus → CPU sibuk swap bukan eksekusi → performa anjlok!

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:

AttributeDeskripsi
NameHuman-readable identifier
TypeExtension (OS-dependent)
LocationPointer ke lokasi di disk
SizeUkuran dalam bytes
ProtectionAccess rights (rwx)
TimeCreated, modified, accessed
OwnerUser 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      │
└──────┴───────┴────────────┴────────┴────────────────┘
BlockDeskripsi
Boot BlockBootstrap code untuk boot OS
Super BlockMetadata filesystem (size, #blocks, #inodes)
Free SpaceBitmap atau linked list untuk free blocks
Inode TableArray of inodes (file metadata)
Data BlocksActual 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)

INODE Direct 0-11 Single Ind. Double Ind. Triple Ind. Data ← 12 blocks = 48KB Ptrs Data ← 1024 blocks = 4MB Ptrs Ptrs Data ← 4GB Ptrs Ptrs Ptrs Data ← 4TB
Inode
Pointer Block
Data Block

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)
ProsCons
SimpleExternal fragmentation
Sequential access cepatSulit grow file
Random access cepatPerlu 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)
ProsCons
No external fragmentationRandom access lambat
File bisa grow easilyPointer 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
ProsCons
Random access cepatIndex block overhead
No external fragmentationLimited 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:

ModeJournal ContainsConsistencyPerformance
WritebackMetadata onlyLowFast
OrderedMetadata (data first)MediumMedium
JournalMetadata + DataHighSlow

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 SystemOSMax File SizeMax VolumeFeatures
ext4Linux16 TB1 EBJournaling, extents
XFSLinux8 EB8 EBHigh performance
BtrfsLinux16 EB16 EBCOW, snapshots
NTFSWindows16 EB16 EBJournaling, ACL
APFSmacOS8 EB8 EBCOW, encryption
FAT32All4 GB2 TBSimple, compatible
exFATAll16 EB128 PBFlash optimized

10. Sistem I/O

I/O Hardware

Device Categories:

CategoryExamplesCharacteristics
Block DevicesHDD, SSD, USB driveFixed-size blocks, seekable
Character DevicesKeyboard, mouse, serialStream of characters
Network DevicesEthernet, WiFiPacket-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:

  1. CPU programs DMA: source, destination, count
  2. DMA takes over bus, transfers data
  3. DMA interrupts CPU when complete
  4. CPU handles interrupt

Perbandingan I/O Methods: CPU Utilization

Time → Polling CPU busy-waiting... I/O Interrupt req CPU free (other work) int DMA set CPU free (DMA handles transfer) i Low Medium High Efficiency
CPU I/O work
CPU waiting
CPU free
Data transfer

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)

0 53 100 199 Start: 53
FCFS
SSTF
SCAN
Request
FCFS: 640 cylinders
SSTF: 236 cylinders
SCAN: 236 cylinders

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)

LevelDescriptionRedundancyPerformanceCapacity
RAID 0StripingNoneRead/Write ↑↑N disks
RAID 1Mirroring1 disk failRead ↑N/2 disks
RAID 5Striping + Distributed Parity1 disk failRead ↑, Write ↓N-1 disks
RAID 6Double Parity2 disk failRead ↑, Write ↓↓N-2 disks
RAID 10Mirror + Stripe1 per mirrorRead/Write ↑↑N/2 disks

Perbandingan RAID Levels

RAID 0 - Striping
Disk 0
A1
B1
C1
Disk 1
A2
B2
C2
✓ Performa tinggi | ✗ No redundancy
RAID 1 - Mirroring
Disk 0
A
B
C
Disk 1
A'
B'
C'
✓ Full redundancy | ✗ 50% kapasitas
RAID 5 - Distributed Parity
D0
A1
B1
C1
Dp
D1
A2
B2
Cp
D1
D2
A3
Bp
C2
D2
D3
Ap
B3
C3
D3
✓ 1 disk fail OK | Capacity: N-1
RAID 10 - Mirror + Stripe
D0
A1
B1
D1
A1'
B1'
D2
A2
B2
D3
A2'
B2'
✓ Performa + Redundancy | 50% kapasitas

Recovery pada RAID 5: Jika Disk 1 gagal, data dapat direkonstruksi: D1 = Dp XOR D2 XOR D3


11. Security dan Protection

Protection vs Security

ProtectionSecurity
Internal mechanismExternal threats
Control access to resourcesDefend against attacks
Policies and mechanismsConfidentiality, Integrity, Availability
Who can do whatHow 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:

BitNameEffect on FileEffect on Directory
SetUID (4)Set User IDRun as owner-
SetGID (2)Set Group IDRun as groupInherit 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:

ACLCapability
Easy to see who has access to objectEasy to see what subject can access
Easy to revoke all access to objectEasy to transfer access rights
Hard to revoke user’s access to allHard 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

Normal Stack
High Addr Return Addr Saved EBP buffer[64] Local vars Low Addr ↑ write
After Overflow!
High Addr 0xDEADBEEF AAAA... AAAA... Local vars Low Addr Overflow!
⚠ Danger: Attacker overwrites Return Address dengan alamat malicious code → CPU jump ke kode attacker saat function return!
// 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:

AspectVirtual MachineContainer
IsolationFull (separate kernel)Process-level (shared kernel)
StartupMinutesSeconds
SizeGBsMBs
PerformanceNear-nativeNative
SecurityStrong isolationWeaker isolation

Arsitektur: Virtual Machine vs Container

Virtual Machine
App A
Guest OS
App B
Guest OS
App C
Guest OS
Hypervisor (Type 1 or 2)
Host OS (optional for Type 1)
Hardware
Each VM has its own OS kernel (GBs)
Container
App A
Libs
App B
Libs
App C
Libs
Container Runtime (Docker)
Host OS (Shared Kernel)
Hardware
Containers share host kernel (MBs)

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:

AlgorithmPreemptiveStarvationOverhead
FCFSNoNoLow
SJFNoYesMedium
SRTFYesYesHigh
PriorityBothYesMedium
Round RobinYesNoHigh
MLFQYesNoHigh

Page Replacement:

AlgorithmOptimalPracticalBelady’s Anomaly
FIFONoYesYes
OPTYesNoNo
LRUNear-optimalExpensiveNo
ClockApproximationYesNo

Key Concepts Summary

  1. Kernel Mode vs User Mode: Privilege separation
  2. Process vs Thread: Heavyweight vs lightweight execution
  3. Deadlock Conditions: Mutual exclusion, hold & wait, no preemption, circular wait
  4. Virtual Memory: Address abstraction, demand paging
  5. File System: Hierarchy, inodes, journaling
  6. Security: Authentication, authorization, encryption
  7. Virtualization: Hypervisors, containers, isolation