Pattern trong nhân Linux
Nhân Linux đã được tinh chỉnh qua 30+ năm. Các pattern này đã sống sót qua hàng thập kỷ sử dụng thực tế trên hàng triệu thiết bị.
| Pattern | Ở đâu trong Linux | Tác dụng |
|---|---|---|
| Bitmask | include/uapi/linux/stat.h | Bit phân quyền file (rwxrwxrwx) |
| Min Heap | kernel/sched/fair.c (CFS) | Completely Fair Scheduler — chọn task có vruntime thấp nhất |
| Ring Buffer | include/linux/ring_buffer.h | Ghi log event ftrace, buffer lock-free theo từng CPU |
| State Machine | net/ipv4/tcp_input.c | State machine kết nối TCP (SYN_SENT → ESTABLISHED → FIN_WAIT) |
| Semaphore | include/linux/semaphore.h | Counting semaphore của kernel với down()/up() |
| Backpressure | net/ipv4/tcp_output.c | Cửa sổ tắc nghẽn TCP (cwnd) — backpressure kiểm soát luồng |
| Free List | mm/slub.c | Slab allocator SLUB — free list xen với con trỏ được làm cứng bằng XOR |
| Trie | net/ipv4/fib_trie.c | Bảng định tuyến IP dưới dạng trie nén (LC-trie) |
| Vtable | include/linux/fs.h | Struct file_operations — vtable con trỏ hàm cho dispatch VFS (.read, .write, .open) |
| Batch Processing | block/blk-merge.c | Block layer gộp request I/O liền kề để phân bổ thời gian seek |
| Rate Limiter | net/sched/sch_tbf.c | Bộ lọc token bucket cho kiểm soát traffic kernel |
| Reference Counting | lib/kobject.c | kref cung cấp reference counting cho object kernel |
Cách chúng kết hợp: Đọc một file
Khi một process gọi read(), nhiều pattern kích hoạt trong một syscall duy nhất:
read(fd, buf, count)▼The VFS layer looks up the file's file_operations struct and calls .read(). ext4, NFS, procfs each provide their own implementation behind the same interface.
The kernel checks file permission bits (rwxrwxrwx) against the process's UID/GID. A single AND operation decides access.
Opening the file incremented its inode refcount. The kernel won't free the inode while any fd references it.
If the read triggers disk I/O, the block layer merges adjacent requests to minimize seek time before dispatching.
ftrace logs the syscall entry/exit into a per-CPU ring buffer for tracing.
Trừu tượng "mọi thứ đều là file" hoạt động được vì vtable dispatch cho phép kernel xử lý file ext4, network socket và entry /proc như nhau. Kiểm tra phân quyền bằng bitmask diễn ra một lần bất kể loại filesystem. Và reference counting đảm bảo không tài nguyên nào bị giải phóng khi đang dùng — kể cả khi process khác xoá file.