use of use_mm and set_fs in the start of kernel thread
c, linux-kernel, memory-management, multithreading
Solution
`vhost_worker` is a kernel thread function, and kernel threads by default are not associated with a regular process address space. The purpose of `use_mm` and `set_fs` here is modify the current task (which is the kernel thread) to attach the vhost_worker kernel thread to a process, notably it is the QEMU process that emulates the VM, and `dev->mm` is a handle to that address space. `set_fs(USER_DS)` sets the maximum virtual address on which faults are allowed to occur, so that faults below the virtual address `USER_DS` (depending on the architecture) would be handled by the kernel like it is done for a normal process.
This allows the vhost kernel-side implementation to directly access QEMU's userspace mapping, which map the guest memory of the VM instance. Effectively this makes the vhost worker become an invisible running thread in QEMU.
Problem
Sometimes, when I read kernel source, I found something like this: ``` static int vhost_worker(void *data) { struct vhost_dev *dev = data; struct vhost_work *work = NULL; unsigned uninitialized_var(seq); mm_segment_t oldfs = get_fs(); set_fs(USER_DS); use_mm(dev->mm); for (;;) { ``` Here, it looks like they change the memory space to something. Could anyone explain the specifics about use_mm and set_fs and their relationship?