Belajar
← All lessons

How the kernel works

Save a note to the disk

App
libc
Kernel
Disk
CPU modering 3 · userring 0 · kernel

app.c

// 1. talk to the disk controller yourselfoutsb(0x1f0, note, len);         // ring 3: fault // 2. ask the kernel to do itint fd = open("note.txt", O_WRONLY | O_CREAT, 0644);ssize_t n = write(fd, note, len); // inside libc, write() is a thin wrapperssize_t write(int fd, const void *buf, size_t len) {  long ret;  asm volatile ("syscall"    : "=a" (ret)    : "a" (1), "D" (fd), "S" (buf), "d" (len)    : "rcx", "r11", "memory");  return ret;}

fs/read_write.c

// ring 0. sys_call_table[1] points herelong sys_write(unsigned int fd, const char __user *buf, size_t n) {  struct file *f = fget(fd);  if (!f) return -EBADF;  if (!(f->f_mode & FMODE_WRITE)) return -EBADF;  if (!access_ok(buf, n)) return -EFAULT;  long ret = vfs_write(f, buf, n, &f->f_pos);  return ret;            // sysret, back to ring 3}

Rings keep apps off the hardware and the CPU enforces them

The app tries toAddOwn memoryKernel memoryDisk port
Ring 3 · user space
AppIts memory
Ring 0 · kernel
Kernel memoryDrivers
Hardware
CPUDisk

To reach the disk, an app has to ask the kernel with a system call

rings.c

int main(void) {  int sum = a + b;  char *buf = malloc(64);  buf[0] = 'h';  char *k = (char *)0xffffffff81000000;  char c = *k;             // page fault  outb(0x42, 0x1f0);       // #GP fault  return 0;}

Two programs, one CPU so the kernel takes turns

Music
CPU
Zip

programs.c

// music, process Afor (;;) { frame++; play(frame); } // zip, process Bfor (;;) { block++; pack(block); } // neither one ever gives the CPU back

kernel/sched.c

// the timer interrupts the CPU every 4 msvoid timer_interrupt(void) {  struct task *prev = current;  struct task *next = pick_next_task();  save_regs(&prev->regs);  // pc, sp, rbx, ...  load_regs(&next->regs);  current = next;  iret();                  // back to ring 3}

Open a file you don't own and the kernel says no

Run asanabudiguestrootOpen toreadwrite
$ ls -l notes.txt

strace

cat.c

int fd = open(path, flags);   // O_RDONLY or O_WRONLYif (fd == -1) {  perror(path);              // Permission denied  return 1;}read(fd, buf, sizeof buf);

fs/namei.c

// inside open(), before you get an fdif (uid == 0) return 0;          // root skips the bitsif (uid == inode->uid) bits = mode >> 6;    // ownerelse if (in_group(inode->gid)) bits = mode >> 3; // groupelse bits = mode;                           // otherif ((bits & want) != want) return -EACCES;return 0;

Topics

Next: How RAM works

Open lesson