Reading

Chapter 1: Operating system interfaces

  • the shell is a user program, and not part of the kernel
  • Although the child has the same memory contents as the parent initially, the parent and child are executing with different memory and different registers: changing a variable in one does not affect the other.

exec replaces the calling process’s memory but preserves its file table

exec replaces the memory and registers of the current process with a new program

I/O and File descriptors

  • The shell ensures that it always has three file descriptors open std input, std output, std error
  • 先close(0); 然后open, 让文件描述符与读相连接

read(fd, buf, n) write(fd, buf, n)

dup system call duplicates an existing file descriptor, returning a new one that refers to the same underlying I/O object. File descriptors are a powerful abstraction, because they hide the details of what they are connected to

1.3 Pipes

  • A pipe is a small kernel buffer exposed to processes as a pair of file descriptors, one for reading and one for writing.
  • 命令行pipe实例: grep fork sh.c wc -l 程序会分别为两个程序创建一个子进程,并递归地运行命令(可能会出现多管道的现象, a b c)
  • 与重定向的优势 会自动清理(重定向需要小心清理临时文件)
  • 能传入任意长的数据流(重定向需要足够的disk空间存储所有的数据)
  • 能够并行执行(重定向只能串行)

1.4 File system

  • chdir: change current directory
  • mkdir creates a new directory, open with the O_CREATE flag creates a new data file, and mknod creates a new device file
  • The link system call creates another file system name referring to the same inode as an existing file.
  • The fstat system call retrieves information from the inode that a file descriptor refers to. It fills in a struct stat, defined in stat.h Each inode is identified by a unique inode number.
  • The file’s inode and the disk space holding its content are only freed when the file’s link count is zero and no file descriptors refer to it(using unlink)

sum-up: 文件目录变换,文件的结构和信息,文件的创建和关闭,Unix中运行文件相关命令的方法

Chapter 2: Operating system organization

  • Thus an operating system must fulfill three requirements: multiplexing, isolation, and interaction.

2.1 Abstracting physical resources

通过函数结构访问disk的优势(让OS管理内存)

2.2 User mode, supervisor mode, and system calls

  • Machine mode have full privilege; a CPU starts in machine mode. Machine mode is mostly intended for configuring a computer.

Supervisor mode(Kernel space)

  • the CPU is allowed to execute privileged instructions If running privileged instructions in user mode, CPU wouldn’t execute it, but switch to the supervisor mode to terminate it

the kernel control the entry point for transitions to supervisor mode

User mode(User space) 实现程序之间隔离的方法

2.3 Kernel organization

monolithic kernel

The entire operating system resides in the kernel, so that the implementations of all system calls run in supervisor mode

Pros: Easy to cooperate, doesn’t have to decide which part of the operating system doesn’t need full hardware privileg

  • Cons: 1. the interfaces between different parts of the operating system are often complex 2. a mistake is fatal, because an error in supervisor mode will often cause the kernel to fail

microkernel

  • minimize the amount of operating system code that runs in supervisor mode
  • img
  • the kernel provides an inter-process communication mechanism to send messages from one user-mode process to another
  • OS services running as processes are called servers. it sends a message to the file server and waits for a response.

sum-up: 两种不同的内核设计方式

2.5 Process overview

  • The unit of isolation is a process.
  • The mechanisms used by the kernel to implement processes include the user/supervisor mode flag, address spaces, and time-slicing of threads

Xv6 maintains a separate page table for each process that defines that process’s address space

img

the trampoline page contains the code to transition in and out of the kernel

  • mapping the trapframe is necessary to save/restore the state of the user process

The xv6 kernel maintains many pieces of state for each process, which it gathers into a struct proc

  • most important pieces of kernel state are its page table, its kernel stack, and its run state.

Context switch between user space and kernel space

  • To switch transparently between processes, the kernel suspends the currently running thread and resumes another process’s thread.
  • Each process has two stacks: a user stack and a kernel stack (p->kstack) the kernel can execute even if a process has wrecked its user stack.

ecall: change to kernel space; sret: to user space

Sum-up

  • an address space to give a process the illusion of its own memory, and, a thread, to give the process the illusion of its own CPU
  • 如何利用进程实现隔离性的以及进程的工作方式

2.7 Security Model

  • Safeguards Assertions, type checking, stack guard pages, etc.

Chapter 3: Page tables

  • provides each process with its own private address space and memory
  • Xv6 performs a few tricks: mapping the same memory (a trampoline page) in several address spaces, and guarding kernel and user stacks with an unmapped page.

3.1 Paging hardware

The structure of page table

img

Address translation

  • A page table is stored in physical memory as a three-level tree. (first nine bits is used for indexing PPN of each page directory. and etc.)
  • If page is not found, raise page-fault exception

  • In the common case in which large ranges of virtual addresses have no mappings, the three-level structure can omit entire page directories.(Allocate pages when they are needed)
  • flag bits that tell the paging hardware how the associated virtual address is allowed to be used

每个PTE都包含标志位,说明虚拟地址的使用权限。

PTE_V表示 PTE 是否存在于页表中:如果未设置,那么一个对该页的引用会引发错误(也就是:不允许被使用( validity ))。

PTE_W控制着能否对页执行写操作;

  • PTE_R 控制是否允许使用指令读取页。
  • PTE_X控制CPU是否可以将页面内容解释为指令并执行它们。
  • PTE_U控制着用户程序能否使用该页;如果不能,则只有内核能够使用该页。

satp: the physical address of the root pagetable page

  • each CPU has its own satp(different CPUs can run different processes)

img

Translation Look-aside Buffer (TLB)

  • Motivation: To avoid the cost of loading PTEs from physical memory a potential downside of three levels is that the CPU must load three PTEs from memory to perform the translation of the virtual address in the load/store instruction to a physical address.

when xv6 changes a page table, it must tell the CPU to invalidate corresponding cached TLB entries.

3.2 Kernel address space

  • Xv6 maintains one page table per process, describing each process’s user address space, plus a single page table that describes the kernel’s address space
  • The kernel gets at RAM and memory-mapped device registers using “direct mapping; Direct mapping simplifies kernel code that reads or writes physical memory.

The guard page’s PTE is invalid (i.e.,PTE_V is not set), so that if the kernel overflows a kernel stack, it will likely cause an exception img

3.4 Physical memory allocation

  • The kernel must allocate and free physical memory at run-time for page tables, user memory, kernel stacks, and pipe buffers.
  • Allocation consists of removing a page from the linked list; freeing consists of adding the freed page to the list.

3.6 Process address space

  • img
  • A process’s user memory starts at virtual address zero and can grow up to MAXVA(The max bits the address can take)
  • Xv6 maps the data, stack, and heap with the permissions PTE_R, PTE_W, and PTE_U. Avoid the program modifies the unexpected regions.(the hardware will refuse to execute the store and raises a page fault)
Lecture Note
  • Address space pagetable implemented in hardware by the processor or by unit called MMU
  • CPU—VA—>MMU—-PA—->Memory

satp: In CPU, this register is used to specify where the map is(VA->PA). Each one process has unique address for the map(This is writen by the kernel for isolation)

  • MMU: 读取内存并转换,不保存映射

The max bits of the virtual address is determined by the number of the registers

paging hardware(RISC-V) xv6 virtual memory code and layout of the kernel address spaces and user address spaces 多级页表中存储PPN是44位的,末尾加上12个0,得到56位物理地址,这就是下一级页表的物理地址

  • 多次访问耗费时间,所以使用TLB(快表)[VA, PA] mapping

MMU —-hardware

Chapter 4 Traps and system calls

CPU Interrupt

Cases

system call

  • exception
  • device interrupt While commonality among the three trap types suggests that a kernel could handle all traps with a single code path, it turns out to be convenient to have separate code for three distinct cases: traps from user space, traps from kernel space, and timer interrupts.

The usual sequence

  • a trap forces a transfer of control into the kernel
  • the kernel saves registers and other state
  • the kernel restores the saved state and returns from the trap
  • original code resumes where it left off

For what

  • isolation demands that only the kernel be allowed to use devices
  • the kernel is a convenient mechanism with which to share devices among multiple processes

4.1 RISC-V trap machinery

  • Each RISC-V CPU has a set of control registers that the kernel writes to tell the CPU how to handle traps, and that the kernel can read to find out about a trap that has occurred.
  • sum-up: CPU用专用的寄存器完成上下文转换。但为了trap的效率CPU并不会将所有任务都完成,剩余的工作需要由内核软件完成

4.2 Traps from user space

  • Occur if the user program makes a system call (ecall instruction), or does something illegal, or if a device interrupts
  • RISC-V hardware does not switch page tables when it forces a trap Things need to do trap handling code needs to switch to the kernel page table
  • the kernel page table must also have a mapping for the handler pointed to by stvec

Trampoline page

Trampoline page stores code to switch between user and kernel space. The code is mapped at the same virtual address (TRAMPOLINE) in user and kernel space so that it continues to work when it switches page tables.

TRAPFRAME

  • address of TRAPFRAME is stored in sscratch register. Saves all the user registers there, including the user’s a0, read back from sscratch.
  • TRAPFRAME also contain the kernel information and the address of usertrap function.

usertrap: The job of usertrap is to determine the cause of the trap, process it, and return

Pointer as argument on system call

  • Problems Invalid pointer
  • kernel page table mappings are not the same as the user page table mappings so the kernel cannot use ordinary instructions to load or store from user-supplied addresses.

Find PA by using user space page table and map it to the VA in the kernel space.

sum-up: 在用户空间中调用trap。

4.5 Traps from kernel space

4.6 Page-fault exceptions

Actions

In user space: kill the faulting process

  • In kernel space: kernel panics

内核错误 (Kernel panic )是指操作系统在监测到内部的致命错误,并无法安全处理此错误时采取的动作。

three kinds of page fault

  • load page faults (when a load instruction cannot translate its virtual address)
  • store page faults (when a store instruction cannot translate its virtual address)
  • instruction page faults (when the address in the program counter doesn’t translate)

The applications of page-fault exception

copy-on-write fork

Procedure the parent and child to initially share all physical pages, but for each to map them read-only

  • Write to that memory will raise a page-fault exception
  • The kernel’s trap handler responds by allocating a new page of physical memory and copying into it the physical page that the faulted address maps to.

Lazy allocation

  • Procedure application asks for more memory by calling sbrk

  • The kernel notes the increase in size, but does not allocate memory or create PTEs
  • When page-fault occurs in those address, the kernel allocates a page of physical memory and maps it into the page table

Since applications often ask for more memory than they need Problem

  • The extra overhead introduced by kernel/user transition reduce this cost by allocating a batch of consecutive pages per page fault instead of one page
  • specializing the kernel entry/exit code for such page-faults.

demand paging(需求分页)

Problem

Since applications can be large and reading from disk is expensive, this startup cost may be noticeable to users

Solution

  • a modern kernel creates the page table for the user address space, but marks the PTEs for the pages invalid
  • On a page fault, the kernel reads the content of the page from disk and maps it into the user address space

paging to disk

Problem

The programs running on a computer may need more memory than the computer has RAM

Solution

  • to store only a fraction of user pages in RAM, and to store the rest on disk in a paging area.
  • The memory stored in the paging area is set as invalid.
  • Access paging area will incur a page fault. The kernel trap handler will allocate a page of physical RAM, read the page from disk into the RAM, and modify the relevant PTE to point to the RAM

Chapter5 Interrupts and device drivers

  • A driver is the code in an operating system that manages a particular device: it configures the device hardware tells the device to perform operations
  • handles the resulting interrupts
  • interacts withprocesses that may be waiting for I/O from the device.

device drivers execute code in two contexts

  • top half that runs in a process’s kernel thread ask the hardware to start an operation
  • wait for the operation complete
  • raise an interrupt when the code is completed

a bottom half that executes at interrupt time.

  • what operation has completed, wakes up a waiting process if appropriate
  • tells the hardware to start work on any waiting next operation

A general pattern to note is the decoupling of device activity from process activity via buffering and interrupts. (This idea is sometimes called I/O concurrency.)

  • This decoupling can increase performance by allowing processes to execute concurrently with device I/O

驱动程序完全禁用中断,并定期检查设备是否需要注意。这种技术被称为轮询(polling)

  • 如果设备执行操作非常快,轮询是有意义的,但是如果设备大部分空闲,轮询会浪费CPU时间。一些驱动程序根据当前设备负载在轮询和中断之间动态切换。

程序I/O很简单,但速度太慢,无法在高数据速率下使用。需要高速移动大量数据的设备通常使用直接内存访问(DMA)

  • DMA设备硬件直接将传入数据写入内存,并从内存中读取传出数据。
  • 一些操作系统能够直接在用户空间缓冲区和设备硬件之间移动数据,通常带有DMA。

lock

  • 锁的缺点是它们会扼杀性能,因为它们会串行化并发操作

竞态条件是指多个进程读写某些共享数据(至少有一个访问是写入)的情况

在内存池中,两个进程并行地释放内存,那么可能会导致释放的内存被放到同一个地址中,从而变成了覆盖

acquire和 release之间的指令序列通常被称为临界区域(critical section)。(加锁的区域)

  • 代码在执行的时候,依托一些 不变量(相当于一些条件),但是其他进程对这个变量的操作暂时改变了这种不变量,所以导致代码运行错误。(上面就是链表头部指针有一个时间段中不是指向链表头部的,这时候其他进程的操作就可能导致竞态)
  • 以将锁视为串行化(serializing)并发的临界区域,以便同时只有一个进程在运行这部分代码,从而维护不变量(假设临界区域设定了正确的隔离性)

冲突

  • 如果多个进程同时想要相同的锁或者锁经历了争用,则称之为发生冲突(conflict)

要使用多少锁,以及每个锁应该保护哪些数据和不变量

  • 任何时候可以被一个CPU写入,同时又可以被另一个CPU读写的变量,都应该使用锁来防止两个操作重叠
  • 锁保护不变量(invariants):如果一个不变量涉及多个内存位置,通常所有这些位置都需要由一个锁来保护,以确保不变量不被改变。
  • 大内核锁(big kernel lock) 如果并行性不重要,那么可以安排只拥有一个线程,而不用担心锁。一个简单的内核可以在多处理器上做到这一点,方法是拥有一个锁,这个锁必须在进入内核时获得,并在退出内核时释放

死锁和锁排序

  • 如果在内核中执行的代码路径必须同时持有数个锁,那么所有代码路径以相同的顺序获取这些锁是很重要的(否则有死锁的风险)
  • 全局锁获取顺序的需求意味着锁实际上是每个函数规范的一部分:调用者必须以一种使锁按照约定顺序被获取的方式调用函数。

锁和中断处理函数

  • 一个进程中持有一个变量,在执行过程中出现了中断,而中断处理函数可能又会需要访问这个变量,这时候处理函数就会等待这个变量被释放,这时候就产生了死锁 如果一个自旋锁被中断处理程序所使用,那么CPU必须保证在启用中断的情况下永远不能持有该锁。

Re-entrant locks

  • It might appear that some deadlocks and lock-ordering challenges could be avoided by using re-entrant locks, which are also called recursive locks. if the lock is held by a process and if that process attempts to acquire the lock again, then the kernel could just allow this

指令和内存访问顺序

  • 规则确实允许重新排序后改变并发代码的结果,并且很容易导致多处理器上的不正确行为。CPU的排序规则称为内存模型(memory model)。
  • __sync_synchronize()是一个内存障碍:它告诉编译器和CPU不要跨障碍重新排序 load或 store指令。

睡眠锁

  • 因为等待会浪费CPU时间,所以自旋锁最适合短的临界区域;睡眠锁对于冗长的操作效果很好。

调度

任何操作系统都可能运行比CPU数量更多的进程,所以需要一个进程间分时共享CPU的方案

通过将进程多路复用到硬件CPU上,使每个进程产生一种错觉,即它有自己的虚拟CPU

多路复用

  • 情景 进程等待设备或管道I/O完成,或等待子进程退出,或在 sleep系统调用中等待时,xv6使用睡眠(sleep)和唤醒(wakeup)机制切换
  • xv6周期性地强制切换以处理长时间计算而不睡眠的进程。

协程

  • 在两个线程之间进行这种样式化切换的过程有时被称为协程(coroutines) 协程运行在线程之上,当一个协程执行完成后,可以选择主动让出,让另一个协程运行在当前线程之上。 协程并没有增加线程数量,只是在线程的基础之上通过分时复用的方式运行多个协程 ,而且协程的切换在用户态完成,切换的代价比线程从用户态到内核态的代价小很多。
  • img
  • 每个线程中运行多个协程
  • 协程只有和异步IO结合起来才能发挥出最大的威力。 假设协程运行在线程之上,并且协程调用了一个阻塞IO操作,这时候会发生什么?实际上操作系统并不知道协程的存在,它只知道线程,因此在协程调用阻塞IO操作的时候,操作系统会让线程进入阻塞状态,当前的协程和其它绑定在该线程之上的协程都会陷入阻塞而得不到调度,这往往是不能接受的。

sleep 和 wakeup

  • Xv6使用了一种称为 sleep和 wakeup的方法,它允许一个进程在等待事件时休眠,而另一个进程在事件发生后将其唤醒。睡眠和唤醒通常被称为序列协调(sequence coordination)或条件同步机制(conditional synchronization mechanisms)。

Sleep(chan)在任意值 chan上睡眠,称为等待通道(wait channel)。 释放CPU用于其他任务

Wakeup(chan)唤醒所有在 chan上睡眠的进程(如果有),使其 sleep调用返回。

  • 为了防止死锁,使用 条件锁,让进程在睡眠之后释放锁

条件锁就是所谓的条件变量,某一个线程因为某个条件为满足时可以使用条件变量使该程序处于阻塞状态。一旦条件满足以“信号量”的方式唤醒一个因为该条件而被阻塞的线程。

文件

  • 文件系统的目的是组织和存储数据
  • 解决的问题 文件系统需要磁盘上的数据结构来表示目录和文件名称树,记录保存每个文件内容的块的标识,以及记录磁盘的哪些区域是空闲的。
  • 文件系统必须支持崩溃恢复(crash recovery)。
  • 文件系统代码必须协调以保持不变量(不同的进程可能在相同的文件系统上运行)
  • 文件系统必须保持常用块的内存缓存(访问磁盘慢)

文件描述符(File descriptor)

路径名(Pathname)

目录(Directory)

索引结点(Inode)

日志(Logging)

缓冲区高速缓存(Buffer cache)

磁盘(Disk)

  • 日志 日志驻留在超级块中指定的未知。
  • 事务中途奔溃将导致日志头块中的计数为0,提交后奔溃将导致非零计数

Notes

Lecture 3: OS design

Lecture Topic:

OS design system calls

  • micro/monolithic kernel

First system call in xv6

OS picture

  • apps: sh, echo, …
  • system call interface (open, close,…) OS

Goal of OS

  • run multiple applications
  • isolate them
  • multiplex them
  • share

Strawman design: No OS

  • Application directly interacts with hardware CPU cores & registers
  • DRAM chips
  • Disk blocks
  • …

OS library perhaps abstracts some of it

Strawman design not conducive to multiplexing

  • each app periodically must give up hardware
  • BUT, weak isolation app forgets to give up, no other app runs
  • apps has end-less loop, no other app runs
  • you cannot even kill the badly app from another app

but used by real-time OSes

  • “cooperative scheduling”

Strawman design not conducive to memory isolation

  • all apps share physical memory
  • one app can overwrites another apps memory
  • one app can overwrite OS library

Unix interface conducive to OS goals

  • abstracts the hardware in way that achieves goals
  • processes (instead of cores): fork OS transparently allocates cores to processes Saves and restore registers

Enforces that processes give them up

  • Periodically re-allocates cores

memory (instead of physical memory): exec

  • Each process has its “own” memory
  • OS can decide where to place app in memory
  • OS can enforce isolation between memory of different apps
  • OS allows storing image in file system

files (instead of disk blocks)

  • OS can provide convenient names
  • OS can allow sharing of files between processes/users

pipes (instead of shared physical mem)

  • OS can stop sender/receiver

OS must be defensive

  • an application shouldn’t be able to crash OS
  • an application shouldn’t be able to break out of its isolation
  • => need strong isolation between apps and OS
  • approach: hardware support

user/kernel mode virtual memory

Processors provide user/kernel mode

  • kernel mode: can execute “privileged” instructions e.g., setting kernel/user bit
  • e.g., reprogramming timer chip

user mode: cannot execute privileged instructions Run OS in kernel mode, applications in user mode [RISC-V has also an M mode, which we mostly ignore]

Processors provide virtual memory

  • Hardware provides page tables that translate virtual address to physical
  • Define what physical memory an application can access
  • OS sets up page tables so that each application can access only its memory

Apps must be able to communicate with kernel

  • Write to storage device, which is shared => must be protected => in kernel
  • Exit app
  • …

Solution: add instruction to change mode in controlled way

  • ecall <n>

  • enters kernel mode at a pre-agreed entry point

Modify OS picture

  • user / kernel (redline)
  • app -> printf() -> write() -> SYSTEM CALL -> sys_write() -> … user-level libraries are app’s private business
  • kernel internal functions are not callable by user
  • other way of drawing picture:
  • syscall 1 -> system call stub -> kernel entry -> syscall -> fs
  • syscall 2 -> proc
  • system call stub executes special instruction to enter kernel hardware switches to kernel mode but only at an entry point specified by the kernel
  • syscall need some way to get at arguments of syscall
  • [syscalls the topic of this week’s lab]

Kernel is the Trusted Computing Base (TCB)

  • Kernel must be “correct” Bugs in kernel could allow user apps to circumvent kernel/user Happens often in practice, because kernels are complex See CVEs

Kernel must treat user apps as suspect User app may trick kernel to do the wrong thing Kernel must check arguments carefully Setup user/kernel correctly Etc. Kernel in charge of separating applications too One app may try to read/write another app’s memory => Requires a security mindset Any bug in kernel may be a security exploit

Aside: can one have process isolation WITHOUT h/w-supported kernel/user mode and virtual memory?

  • yes! use a strongly-typed programming language

For example, see Singularity O/S the compiler is then the trust computing base (TCB) but h/w user/kernel mode is the most popular plan Monolothic kernel OS runs in kernel space Xv6 does this. Linux etc. too. kernel interface == system call interface one big program with file system, drivers, &c good: easy for subsystems to cooperate one cache shared by file system and virtual memory bad: interactions are complex leads to bugs no isolation within

Microkernel design

  • many OS services run as ordinary user programs file system in a file server

kernel implements minimal mechanism to run services in user space

  • processes with memory
  • inter-process communication (IPC)

kernel interface != system call interface

good: more isolation bad: may be hard to get good performance both monolithic and microkernel designs widely used

Xv6 case study

  • Monolithic kernel Unix system calls == kernel interface

Source code reflects OS organization (by convention)

  • user/ apps in user mode
  • kernel/ code in kernel mode

Kernel has several parts

  • kernel/defs.h proc
  • fs ..

Goal: read source code and understand it (without consulting book)

The RISC-V computer

  • A very simple board (e.g., no display)

RISC-V processor with 4 cores RAM (128 MB) support for interrupts (PLIC, CLINT) support for UART allows xv6 to talk to console allows xv6 to read from keyboard support for e1000 network card (through PCIe) Qemu emulates several RISC-V computers we use the “virt” one https://github.com/riscv/riscv-qemu/wiki

close to the SiFive board (https://www.sifive.com/boards) but with virtio for disk

Boot xv6 (under gdb)

  • $ make CPUS=1 qemu-gdb runs xv6 under gdb (with 1 core)

Qemu starts xv6 in kernel/entry.S (see kernel/kernel.ld)

  • set breakpoint at _entry look at instruction
  • info reg

set breakpoint at main

  • Walk through main single step into userinit Walk through userinit show kalloc show proc.h show allocproc() show initcode.S/initcode.asm break forkret() walk to userret break syscall print num syscalls[num] exec “/init” points to be made: page table in userinit ecall: U -> K a7: syscall # exec: defensive

kernel

\text{proc.c} \stackrel{\text{gcc}}{\rightarrow} \text{proc.s} \stackrel{\text{assembler}}{\rightarrow} \text{proc.o} \rightarrow\text{link different .o file together}

6.S081 2020 Lecture 4: Virtual Memory

========================================

  • plan: address spaces paging hardware xv6 VM code

Virtual memory overview

  • today’s problem: [user/kernel diagram] [memory view: diagram with user processes and kernel in memory] suppose the shell has a bug: sometimes it writes to a random memory address how can we keep it from wrecking the kernel? and from wrecking other processes?
  • we want isolated address spaces each process has its own memory it can read and write its own memory it cannot read or write anything else challenge: how to multiplex several memories over one physical memory? while maintaining isolation between memories
  • xv6 uses RISC-V’s paging hardware to implement AS’s ask questions! this material is important topic of next lab (and shows up in several other labs)

paging provides a level of indirection for addressing CPU -> MMU -> RAM VA PA

\[\text{CPU}\stackrel{\text{VA}}{\rightarrow}MMU\stackrel{\text{PA}}{\rightarrow}\text{RAM}\]

s/w can only ld/st to virtual addresses, not physical kernel tells MMU how to map each virtual address to a physical address MMU essentially has a table, indexed by va, yielding pa called a “page table” one page table per address space MMU can restrict what virtual addresses user code can use By programming the MMU, the kernel has complete control over va->pa mapping Allows for many interesting OS features/tricks

  • RISC-V maps 4-KB “pages” and aligned — start on 4 KB boundaries 4 KB = 12 bits the RISC-V used in xv6 has 64-bit for addresses thus page table index is top 64-12 = 52 bits of VA except that the top 25 of the top 52 are unused no RISC-V has that much memory now can grow in future so, index is 27 bits.
  • MMU translation see Figure 3.1 of book use index bits of VA to find a page table entry (PTE) construct physical address using PPN from PTE + offset of VA
  • what is in PTE? each PTE is 64 bits, but only 54 are used top 44 bits of PTE are top bits of physical address “physical page number” low 10 bits of PTE flags Present, Writeable, &c note: size virtual addresses != size physical addresses
  • where is the page table stored? in RAM — MMU loads (and stores) PTEs o/s can read/write PTEs read/write memory location corresponding to PTEs
  • would it be reasonable for page table to just be an array of PTEs? how big is it? 2^27 is roughly 134 million 64 bits per entry 134*8 MB for a full page table wasting roughly 1GB per page table one page table per address space one address space per application would waste lots of memory for small programs! you only need mappings for a few hundred pages so the rest of the million entries would be there but not needed
  • RISC-V 64 uses a “three-level page table” to save space see figure 3.2 from book page directory page (PD) PD has 512 PTEs PTEs point to another PD or is a leaf so 512512512 PTEs in total PD entries can be invalid those PTE pages need not exist so a page table for a small address space can be small
  • how does the mmu know where the page table is located in RAM? satp holds phys address of top PD pages can be anywhere in RAM — need not be contiguous rewrite satp when switching to another address space/application
  • how does RISC-V paging hardware translate a va? need to find the right PTE satp register points to PA of top/L2 PD top 9 bits index L2 PD to get PA of L1 PD next 9 bits index L1 PD to get PA of L0 PD next 9 bits index L0 PD to get PA of PTE PPN from PTE + low-12 from VA
  • flags in PTE V, R, W, X, U xv6 uses all of them
  • what if V bit not set? or store and W bit not set? “page fault” forces transfer to kernel trap.c in xv6 source kernel can just produce error, kill process in xv6: “usertrap(): unexpected scause … pid=… sepc=… stval=…” or kernel can install a PTE, resume the process e.g. after loading the page of memory from disk
  • indirection allows paging h/w to solve many problems e.g. phys memory doesn’t have to be contiguous avoids fragmentation e.g. lazy allocation (a lab) e.g. copy-on-write fork (another lab) many more techniques topic of next lecture

Q: why use virtual memory in kernel? it is clearly good to have page tables for user processes but why have a page table for the kernel? could the kernel run with using only physical addresses? top-level answer: yes most standard kernels do use virtual addresses why do standard kernels do so? some reasons are lame, some are better, none are fundamental

the hardware makes it difficult to turn it off e.g. on entering a system call, one would have to disable VM

  • the kernel itself can benefit from virtual addresses mark text pages X, but data not (helps tracking down bugs) unmap a page below kernel stack (helps tracking down bugs) map a page both in user and kernel (helps user/kernel transition)

Virtual memory in xv6

  • kernel page table See figure 3.3 of book simple maping mostly map virtual to physical one-on-one note double-mapping of trampoline note permissions why map devices?
  • each process has its own address space and its own page table see figure 3.4 of book note: trampoline and trapframe aren’t writable by user process kernel switches page tables (i.e. sets satp) when switching processes
  • Q: why this address space arrangement? user virtual addresses start at zero of course user va 0 maps to different pa for each process 16,777,216 GB for user heap to grow contiguously but needn’t have contiguous phys mem — no fragmentation problem both kernel and user map trampoline and trapframe page eases transition user -> kernel and back kernel doesn’t map user applications not easy for kernel to r/w user memory need translate user virtual address to kernel virtual address good for isolation (see spectre attacks) easy for kernel to r/w physical memory pa x mapped at va x
  • Q: does the kernel have to map all of phys mem into its virtual address space?

Code walk through

  • setup of kernel address space kvmmap() Q: what is address 0x10000000 (256M) Q: how much address space does 1 L2 entry cover? (1G) Q: how much address space does 1 L1 entry cover? (2MB) Q: how much address space does 1 L0 entry cover? (4096) print kernel page table Q: what is size of address space? (512G) Q: how much memory is used to represent it after 1rst kvmmap()? (3 pages) Q: how many entries is CLINT? (16 pages) Q: how many entries is PLIC? (1024 pages, two level 1 PDs) Q: how many pages is kernel text (8 pages) Q: how many pages is kernel total (128M = 64 * 2MB) Q: Is trampoline mapped twice? (yes, last entry and direct-mapped, entry [2, 3, 7]) kvminithart(); Q: after executing w_satp() why will the next instruction be sfence_vma()?
  • mappages() in vm.c arguments are top PD, va, size, pa, perm adds mappings from a range of va’s to corresponding pa’s rounds b/c some uses pass in non-page-aligned addresses for each page-aligned address in the range call walkpgdir to find address of PTE need the PTE’s address (not just content) b/c we want to modify put the desired pa into the PTE mark PTE as valid w/ PTE_P
  • walk() in vm.c mimics how the paging h/w finds the PTE for an address PX extracts the 9 bits at Level level &pagetable[PX(level, va)] is the address of the relevant PTE if PTE_V the relevant page-table page already exists PTE2PA extracts the PPN from the PDE if not PTE_V alloc a page-table page fill in pte with PPN (using PA2PTE) now the PTE we want is in the page-table page
  • procinit() in proc.c alloc a page for each kernel stack with a guard page
  • setup user address space allocproc(): allocates empty top-level page table fork(): uvmcopy() exec(): replace proc’s page table with a new one uvmalloc loadseg print user page table for sh Q: what is entry 2?
  • a process calls sbrk(n) to ask for n more bytes of heap memory user/umalloc.c calls sbrk() to get memory for the allocator each process has a size kernel adds new memory at process’s end, increases size sbrk() allocates physical memory (RAM) maps it into the process’s page table returns the starting address of the new memory
  • growproc() in proc.c proc->sz is the process’s current size uvmalloc() does most of the work when switching to user space satp will be loaded with updated page table
  • uvmalloc() in vm.c why PGROUNDUP? arguments to mappages()…