Skip to content

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 LinuxTác dụng
Bitmaskinclude/uapi/linux/stat.hBit phân quyền file (rwxrwxrwx)
Min Heapkernel/sched/fair.c (CFS)Completely Fair Scheduler — chọn task có vruntime thấp nhất
Ring Bufferinclude/linux/ring_buffer.hGhi log event ftrace, buffer lock-free theo từng CPU
State Machinenet/ipv4/tcp_input.cState machine kết nối TCP (SYN_SENT → ESTABLISHED → FIN_WAIT)
Semaphoreinclude/linux/semaphore.hCounting semaphore của kernel với down()/up()
Backpressurenet/ipv4/tcp_output.cCửa sổ tắc nghẽn TCP (cwnd) — backpressure kiểm soát luồng
Free Listmm/slub.cSlab allocator SLUB — free list xen với con trỏ được làm cứng bằng XOR
Trienet/ipv4/fib_trie.cBảng định tuyến IP dưới dạng trie nén (LC-trie)
Vtableinclude/linux/fs.hStruct file_operations — vtable con trỏ hàm cho dispatch VFS (.read, .write, .open)
Batch Processingblock/blk-merge.cBlock layer gộp request I/O liền kề để phân bổ thời gian seek
Rate Limiternet/sched/sch_tbf.cBộ lọc token bucket cho kiểm soát traffic kernel
Reference Countinglib/kobject.ckref 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)
1
Vtable

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.

2
Bitmask

The kernel checks file permission bits (rwxrwxrwx) against the process's UID/GID. A single AND operation decides access.

3
Reference Counting

Opening the file incremented its inode refcount. The kernel won't free the inode while any fd references it.

4
Batch Processing

If the read triggers disk I/O, the block layer merges adjacent requests to minimize seek time before dispatching.

5
Ring Buffer

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.

Đọc thêm

Released under the MIT License.