提交 6ae7d6f0 编写于 作者: L Linus Torvalds

Merge git://git.kernel.org/pub/scm/linux/kernel/git/rusty/linux-2.6-for-linus

* git://git.kernel.org/pub/scm/linux/kernel/git/rusty/linux-2.6-for-linus:
  lguest and virtio: cleanup struct definitions to Linux style.
  lguest: update commentry
  lguest: fix comment style
  virtio: refactor find_vqs
  virtio: delete vq from list
  virtio: fix memory leak on device removal
  lguest: fix descriptor corruption in example launcher
  lguest: dereferencing freed mem in add_eventfd()
此差异已折叠。
...@@ -17,8 +17,7 @@ ...@@ -17,8 +17,7 @@
/* Pages for switcher itself, then two pages per cpu */ /* Pages for switcher itself, then two pages per cpu */
#define TOTAL_SWITCHER_PAGES (SHARED_SWITCHER_PAGES + 2 * nr_cpu_ids) #define TOTAL_SWITCHER_PAGES (SHARED_SWITCHER_PAGES + 2 * nr_cpu_ids)
/* We map at -4M (-2M when PAE is activated) for ease of mapping /* We map at -4M (-2M for PAE) for ease of mapping (one PTE page). */
* into the guest (one PTE page). */
#ifdef CONFIG_X86_PAE #ifdef CONFIG_X86_PAE
#define SWITCHER_ADDR 0xFFE00000 #define SWITCHER_ADDR 0xFFE00000
#else #else
......
...@@ -30,27 +30,27 @@ ...@@ -30,27 +30,27 @@
#include <asm/hw_irq.h> #include <asm/hw_irq.h>
#include <asm/kvm_para.h> #include <asm/kvm_para.h>
/*G:030 But first, how does our Guest contact the Host to ask for privileged /*G:030
* But first, how does our Guest contact the Host to ask for privileged
* operations? There are two ways: the direct way is to make a "hypercall", * operations? There are two ways: the direct way is to make a "hypercall",
* to make requests of the Host Itself. * to make requests of the Host Itself.
* *
* We use the KVM hypercall mechanism. Seventeen hypercalls are * We use the KVM hypercall mechanism, though completely different hypercall
* available: the hypercall number is put in the %eax register, and the * numbers. Seventeen hypercalls are available: the hypercall number is put in
* arguments (when required) are placed in %ebx, %ecx, %edx and %esi. * the %eax register, and the arguments (when required) are placed in %ebx,
* If a return value makes sense, it's returned in %eax. * %ecx, %edx and %esi. If a return value makes sense, it's returned in %eax.
* *
* Grossly invalid calls result in Sudden Death at the hands of the vengeful * Grossly invalid calls result in Sudden Death at the hands of the vengeful
* Host, rather than returning failure. This reflects Winston Churchill's * Host, rather than returning failure. This reflects Winston Churchill's
* definition of a gentleman: "someone who is only rude intentionally". */ * definition of a gentleman: "someone who is only rude intentionally".
/*:*/ :*/
/* Can't use our min() macro here: needs to be a constant */ /* Can't use our min() macro here: needs to be a constant */
#define LGUEST_IRQS (NR_IRQS < 32 ? NR_IRQS: 32) #define LGUEST_IRQS (NR_IRQS < 32 ? NR_IRQS: 32)
#define LHCALL_RING_SIZE 64 #define LHCALL_RING_SIZE 64
struct hcall_args { struct hcall_args {
/* These map directly onto eax, ebx, ecx, edx and esi /* These map directly onto eax/ebx/ecx/edx/esi in struct lguest_regs */
* in struct lguest_regs */
unsigned long arg0, arg1, arg2, arg3, arg4; unsigned long arg0, arg1, arg2, arg3, arg4;
}; };
......
此差异已折叠。
...@@ -5,7 +5,8 @@ ...@@ -5,7 +5,8 @@
#include <asm/thread_info.h> #include <asm/thread_info.h>
#include <asm/processor-flags.h> #include <asm/processor-flags.h>
/*G:020 Our story starts with the kernel booting into startup_32 in /*G:020
* Our story starts with the kernel booting into startup_32 in
* arch/x86/kernel/head_32.S. It expects a boot header, which is created by * arch/x86/kernel/head_32.S. It expects a boot header, which is created by
* the bootloader (the Launcher in our case). * the bootloader (the Launcher in our case).
* *
...@@ -21,11 +22,14 @@ ...@@ -21,11 +22,14 @@
* data without remembering to subtract __PAGE_OFFSET! * data without remembering to subtract __PAGE_OFFSET!
* *
* The .section line puts this code in .init.text so it will be discarded after * The .section line puts this code in .init.text so it will be discarded after
* boot. */ * boot.
*/
.section .init.text, "ax", @progbits .section .init.text, "ax", @progbits
ENTRY(lguest_entry) ENTRY(lguest_entry)
/* We make the "initialization" hypercall now to tell the Host about /*
* us, and also find out where it put our page tables. */ * We make the "initialization" hypercall now to tell the Host about
* us, and also find out where it put our page tables.
*/
movl $LHCALL_LGUEST_INIT, %eax movl $LHCALL_LGUEST_INIT, %eax
movl $lguest_data - __PAGE_OFFSET, %ebx movl $lguest_data - __PAGE_OFFSET, %ebx
.byte 0x0f,0x01,0xc1 /* KVM_HYPERCALL */ .byte 0x0f,0x01,0xc1 /* KVM_HYPERCALL */
...@@ -33,13 +37,14 @@ ENTRY(lguest_entry) ...@@ -33,13 +37,14 @@ ENTRY(lguest_entry)
/* Set up the initial stack so we can run C code. */ /* Set up the initial stack so we can run C code. */
movl $(init_thread_union+THREAD_SIZE),%esp movl $(init_thread_union+THREAD_SIZE),%esp
/* Jumps are relative, and we're running __PAGE_OFFSET too low at the /* Jumps are relative: we're running __PAGE_OFFSET too low. */
* moment. */
jmp lguest_init+__PAGE_OFFSET jmp lguest_init+__PAGE_OFFSET
/*G:055 We create a macro which puts the assembler code between lgstart_ and /*G:055
* lgend_ markers. These templates are put in the .text section: they can't be * We create a macro which puts the assembler code between lgstart_ and lgend_
* discarded after boot as we may need to patch modules, too. */ * markers. These templates are put in the .text section: they can't be
* discarded after boot as we may need to patch modules, too.
*/
.text .text
#define LGUEST_PATCH(name, insns...) \ #define LGUEST_PATCH(name, insns...) \
lgstart_##name: insns; lgend_##name:; \ lgstart_##name: insns; lgend_##name:; \
...@@ -48,83 +53,103 @@ ENTRY(lguest_entry) ...@@ -48,83 +53,103 @@ ENTRY(lguest_entry)
LGUEST_PATCH(cli, movl $0, lguest_data+LGUEST_DATA_irq_enabled) LGUEST_PATCH(cli, movl $0, lguest_data+LGUEST_DATA_irq_enabled)
LGUEST_PATCH(pushf, movl lguest_data+LGUEST_DATA_irq_enabled, %eax) LGUEST_PATCH(pushf, movl lguest_data+LGUEST_DATA_irq_enabled, %eax)
/*G:033 But using those wrappers is inefficient (we'll see why that doesn't /*G:033
* matter for save_fl and irq_disable later). If we write our routines * But using those wrappers is inefficient (we'll see why that doesn't matter
* carefully in assembler, we can avoid clobbering any registers and avoid * for save_fl and irq_disable later). If we write our routines carefully in
* jumping through the wrapper functions. * assembler, we can avoid clobbering any registers and avoid jumping through
* the wrapper functions.
* *
* I skipped over our first piece of assembler, but this one is worth studying * I skipped over our first piece of assembler, but this one is worth studying
* in a bit more detail so I'll describe in easy stages. First, the routine * in a bit more detail so I'll describe in easy stages. First, the routine to
* to enable interrupts: */ * enable interrupts:
*/
ENTRY(lg_irq_enable) ENTRY(lg_irq_enable)
/* The reverse of irq_disable, this sets lguest_data.irq_enabled to /*
* X86_EFLAGS_IF (ie. "Interrupts enabled"). */ * The reverse of irq_disable, this sets lguest_data.irq_enabled to
* X86_EFLAGS_IF (ie. "Interrupts enabled").
*/
movl $X86_EFLAGS_IF, lguest_data+LGUEST_DATA_irq_enabled movl $X86_EFLAGS_IF, lguest_data+LGUEST_DATA_irq_enabled
/* But now we need to check if the Host wants to know: there might have /*
* But now we need to check if the Host wants to know: there might have
* been interrupts waiting to be delivered, in which case it will have * been interrupts waiting to be delivered, in which case it will have
* set lguest_data.irq_pending to X86_EFLAGS_IF. If it's not zero, we * set lguest_data.irq_pending to X86_EFLAGS_IF. If it's not zero, we
* jump to send_interrupts, otherwise we're done. */ * jump to send_interrupts, otherwise we're done.
*/
testl $0, lguest_data+LGUEST_DATA_irq_pending testl $0, lguest_data+LGUEST_DATA_irq_pending
jnz send_interrupts jnz send_interrupts
/* One cool thing about x86 is that you can do many things without using /*
* One cool thing about x86 is that you can do many things without using
* a register. In this case, the normal path hasn't needed to save or * a register. In this case, the normal path hasn't needed to save or
* restore any registers at all! */ * restore any registers at all!
*/
ret ret
send_interrupts: send_interrupts:
/* OK, now we need a register: eax is used for the hypercall number, /*
* OK, now we need a register: eax is used for the hypercall number,
* which is LHCALL_SEND_INTERRUPTS. * which is LHCALL_SEND_INTERRUPTS.
* *
* We used not to bother with this pending detection at all, which was * We used not to bother with this pending detection at all, which was
* much simpler. Sooner or later the Host would realize it had to * much simpler. Sooner or later the Host would realize it had to
* send us an interrupt. But that turns out to make performance 7 * send us an interrupt. But that turns out to make performance 7
* times worse on a simple tcp benchmark. So now we do this the hard * times worse on a simple tcp benchmark. So now we do this the hard
* way. */ * way.
*/
pushl %eax pushl %eax
movl $LHCALL_SEND_INTERRUPTS, %eax movl $LHCALL_SEND_INTERRUPTS, %eax
/* This is a vmcall instruction (same thing that KVM uses). Older /*
* This is a vmcall instruction (same thing that KVM uses). Older
* assembler versions might not know the "vmcall" instruction, so we * assembler versions might not know the "vmcall" instruction, so we
* create one manually here. */ * create one manually here.
*/
.byte 0x0f,0x01,0xc1 /* KVM_HYPERCALL */ .byte 0x0f,0x01,0xc1 /* KVM_HYPERCALL */
/* Put eax back the way we found it. */
popl %eax popl %eax
ret ret
/* Finally, the "popf" or "restore flags" routine. The %eax register holds the /*
* Finally, the "popf" or "restore flags" routine. The %eax register holds the
* flags (in practice, either X86_EFLAGS_IF or 0): if it's X86_EFLAGS_IF we're * flags (in practice, either X86_EFLAGS_IF or 0): if it's X86_EFLAGS_IF we're
* enabling interrupts again, if it's 0 we're leaving them off. */ * enabling interrupts again, if it's 0 we're leaving them off.
*/
ENTRY(lg_restore_fl) ENTRY(lg_restore_fl)
/* This is just "lguest_data.irq_enabled = flags;" */ /* This is just "lguest_data.irq_enabled = flags;" */
movl %eax, lguest_data+LGUEST_DATA_irq_enabled movl %eax, lguest_data+LGUEST_DATA_irq_enabled
/* Now, if the %eax value has enabled interrupts and /*
* Now, if the %eax value has enabled interrupts and
* lguest_data.irq_pending is set, we want to tell the Host so it can * lguest_data.irq_pending is set, we want to tell the Host so it can
* deliver any outstanding interrupts. Fortunately, both values will * deliver any outstanding interrupts. Fortunately, both values will
* be X86_EFLAGS_IF (ie. 512) in that case, and the "testl" * be X86_EFLAGS_IF (ie. 512) in that case, and the "testl"
* instruction will AND them together for us. If both are set, we * instruction will AND them together for us. If both are set, we
* jump to send_interrupts. */ * jump to send_interrupts.
*/
testl lguest_data+LGUEST_DATA_irq_pending, %eax testl lguest_data+LGUEST_DATA_irq_pending, %eax
jnz send_interrupts jnz send_interrupts
/* Again, the normal path has used no extra registers. Clever, huh? */ /* Again, the normal path has used no extra registers. Clever, huh? */
ret ret
/*:*/
/* These demark the EIP range where host should never deliver interrupts. */ /* These demark the EIP range where host should never deliver interrupts. */
.global lguest_noirq_start .global lguest_noirq_start
.global lguest_noirq_end .global lguest_noirq_end
/*M:004 When the Host reflects a trap or injects an interrupt into the Guest, /*M:004
* it sets the eflags interrupt bit on the stack based on * When the Host reflects a trap or injects an interrupt into the Guest, it
* lguest_data.irq_enabled, so the Guest iret logic does the right thing when * sets the eflags interrupt bit on the stack based on lguest_data.irq_enabled,
* restoring it. However, when the Host sets the Guest up for direct traps, * so the Guest iret logic does the right thing when restoring it. However,
* such as system calls, the processor is the one to push eflags onto the * when the Host sets the Guest up for direct traps, such as system calls, the
* stack, and the interrupt bit will be 1 (in reality, interrupts are always * processor is the one to push eflags onto the stack, and the interrupt bit
* enabled in the Guest). * will be 1 (in reality, interrupts are always enabled in the Guest).
* *
* This turns out to be harmless: the only trap which should happen under Linux * This turns out to be harmless: the only trap which should happen under Linux
* with interrupts disabled is Page Fault (due to our lazy mapping of vmalloc * with interrupts disabled is Page Fault (due to our lazy mapping of vmalloc
* regions), which has to be reflected through the Host anyway. If another * regions), which has to be reflected through the Host anyway. If another
* trap *does* go off when interrupts are disabled, the Guest will panic, and * trap *does* go off when interrupts are disabled, the Guest will panic, and
* we'll never get to this iret! :*/ * we'll never get to this iret!
:*/
/*G:045 There is one final paravirt_op that the Guest implements, and glancing /*G:045
* at it you can see why I left it to last. It's *cool*! It's in *assembler*! * There is one final paravirt_op that the Guest implements, and glancing at it
* you can see why I left it to last. It's *cool*! It's in *assembler*!
* *
* The "iret" instruction is used to return from an interrupt or trap. The * The "iret" instruction is used to return from an interrupt or trap. The
* stack looks like this: * stack looks like this:
...@@ -148,15 +173,18 @@ ENTRY(lg_restore_fl) ...@@ -148,15 +173,18 @@ ENTRY(lg_restore_fl)
* return to userspace or wherever. Our solution to this is to surround the * return to userspace or wherever. Our solution to this is to surround the
* code with lguest_noirq_start: and lguest_noirq_end: labels. We tell the * code with lguest_noirq_start: and lguest_noirq_end: labels. We tell the
* Host that it is *never* to interrupt us there, even if interrupts seem to be * Host that it is *never* to interrupt us there, even if interrupts seem to be
* enabled. */ * enabled.
*/
ENTRY(lguest_iret) ENTRY(lguest_iret)
pushl %eax pushl %eax
movl 12(%esp), %eax movl 12(%esp), %eax
lguest_noirq_start: lguest_noirq_start:
/* Note the %ss: segment prefix here. Normal data accesses use the /*
* Note the %ss: segment prefix here. Normal data accesses use the
* "ds" segment, but that will have already been restored for whatever * "ds" segment, but that will have already been restored for whatever
* we're returning to (such as userspace): we can't trust it. The %ss: * we're returning to (such as userspace): we can't trust it. The %ss:
* prefix makes sure we use the stack segment, which is still valid. */ * prefix makes sure we use the stack segment, which is still valid.
*/
movl %eax,%ss:lguest_data+LGUEST_DATA_irq_enabled movl %eax,%ss:lguest_data+LGUEST_DATA_irq_enabled
popl %eax popl %eax
iret iret
......
/*P:400 This contains run_guest() which actually calls into the Host<->Guest /*P:400
* This contains run_guest() which actually calls into the Host<->Guest
* Switcher and analyzes the return, such as determining if the Guest wants the * Switcher and analyzes the return, such as determining if the Guest wants the
* Host to do something. This file also contains useful helper routines. :*/ * Host to do something. This file also contains useful helper routines.
:*/
#include <linux/module.h> #include <linux/module.h>
#include <linux/stringify.h> #include <linux/stringify.h>
#include <linux/stddef.h> #include <linux/stddef.h>
...@@ -24,7 +26,8 @@ static struct page **switcher_page; ...@@ -24,7 +26,8 @@ static struct page **switcher_page;
/* This One Big lock protects all inter-guest data structures. */ /* This One Big lock protects all inter-guest data structures. */
DEFINE_MUTEX(lguest_lock); DEFINE_MUTEX(lguest_lock);
/*H:010 We need to set up the Switcher at a high virtual address. Remember the /*H:010
* We need to set up the Switcher at a high virtual address. Remember the
* Switcher is a few hundred bytes of assembler code which actually changes the * Switcher is a few hundred bytes of assembler code which actually changes the
* CPU to run the Guest, and then changes back to the Host when a trap or * CPU to run the Guest, and then changes back to the Host when a trap or
* interrupt happens. * interrupt happens.
...@@ -33,7 +36,8 @@ DEFINE_MUTEX(lguest_lock); ...@@ -33,7 +36,8 @@ DEFINE_MUTEX(lguest_lock);
* Host since it will be running as the switchover occurs. * Host since it will be running as the switchover occurs.
* *
* Trying to map memory at a particular address is an unusual thing to do, so * Trying to map memory at a particular address is an unusual thing to do, so
* it's not a simple one-liner. */ * it's not a simple one-liner.
*/
static __init int map_switcher(void) static __init int map_switcher(void)
{ {
int i, err; int i, err;
...@@ -47,8 +51,10 @@ static __init int map_switcher(void) ...@@ -47,8 +51,10 @@ static __init int map_switcher(void)
* easy. * easy.
*/ */
/* We allocate an array of struct page pointers. map_vm_area() wants /*
* this, rather than just an array of pages. */ * We allocate an array of struct page pointers. map_vm_area() wants
* this, rather than just an array of pages.
*/
switcher_page = kmalloc(sizeof(switcher_page[0])*TOTAL_SWITCHER_PAGES, switcher_page = kmalloc(sizeof(switcher_page[0])*TOTAL_SWITCHER_PAGES,
GFP_KERNEL); GFP_KERNEL);
if (!switcher_page) { if (!switcher_page) {
...@@ -56,8 +62,10 @@ static __init int map_switcher(void) ...@@ -56,8 +62,10 @@ static __init int map_switcher(void)
goto out; goto out;
} }
/* Now we actually allocate the pages. The Guest will see these pages, /*
* so we make sure they're zeroed. */ * Now we actually allocate the pages. The Guest will see these pages,
* so we make sure they're zeroed.
*/
for (i = 0; i < TOTAL_SWITCHER_PAGES; i++) { for (i = 0; i < TOTAL_SWITCHER_PAGES; i++) {
unsigned long addr = get_zeroed_page(GFP_KERNEL); unsigned long addr = get_zeroed_page(GFP_KERNEL);
if (!addr) { if (!addr) {
...@@ -67,19 +75,23 @@ static __init int map_switcher(void) ...@@ -67,19 +75,23 @@ static __init int map_switcher(void)
switcher_page[i] = virt_to_page(addr); switcher_page[i] = virt_to_page(addr);
} }
/* First we check that the Switcher won't overlap the fixmap area at /*
* First we check that the Switcher won't overlap the fixmap area at
* the top of memory. It's currently nowhere near, but it could have * the top of memory. It's currently nowhere near, but it could have
* very strange effects if it ever happened. */ * very strange effects if it ever happened.
*/
if (SWITCHER_ADDR + (TOTAL_SWITCHER_PAGES+1)*PAGE_SIZE > FIXADDR_START){ if (SWITCHER_ADDR + (TOTAL_SWITCHER_PAGES+1)*PAGE_SIZE > FIXADDR_START){
err = -ENOMEM; err = -ENOMEM;
printk("lguest: mapping switcher would thwack fixmap\n"); printk("lguest: mapping switcher would thwack fixmap\n");
goto free_pages; goto free_pages;
} }
/* Now we reserve the "virtual memory area" we want: 0xFFC00000 /*
* Now we reserve the "virtual memory area" we want: 0xFFC00000
* (SWITCHER_ADDR). We might not get it in theory, but in practice * (SWITCHER_ADDR). We might not get it in theory, but in practice
* it's worked so far. The end address needs +1 because __get_vm_area * it's worked so far. The end address needs +1 because __get_vm_area
* allocates an extra guard page, so we need space for that. */ * allocates an extra guard page, so we need space for that.
*/
switcher_vma = __get_vm_area(TOTAL_SWITCHER_PAGES * PAGE_SIZE, switcher_vma = __get_vm_area(TOTAL_SWITCHER_PAGES * PAGE_SIZE,
VM_ALLOC, SWITCHER_ADDR, SWITCHER_ADDR VM_ALLOC, SWITCHER_ADDR, SWITCHER_ADDR
+ (TOTAL_SWITCHER_PAGES+1) * PAGE_SIZE); + (TOTAL_SWITCHER_PAGES+1) * PAGE_SIZE);
...@@ -89,11 +101,13 @@ static __init int map_switcher(void) ...@@ -89,11 +101,13 @@ static __init int map_switcher(void)
goto free_pages; goto free_pages;
} }
/* This code actually sets up the pages we've allocated to appear at /*
* This code actually sets up the pages we've allocated to appear at
* SWITCHER_ADDR. map_vm_area() takes the vma we allocated above, the * SWITCHER_ADDR. map_vm_area() takes the vma we allocated above, the
* kind of pages we're mapping (kernel pages), and a pointer to our * kind of pages we're mapping (kernel pages), and a pointer to our
* array of struct pages. It increments that pointer, but we don't * array of struct pages. It increments that pointer, but we don't
* care. */ * care.
*/
pagep = switcher_page; pagep = switcher_page;
err = map_vm_area(switcher_vma, PAGE_KERNEL_EXEC, &pagep); err = map_vm_area(switcher_vma, PAGE_KERNEL_EXEC, &pagep);
if (err) { if (err) {
...@@ -101,8 +115,10 @@ static __init int map_switcher(void) ...@@ -101,8 +115,10 @@ static __init int map_switcher(void)
goto free_vma; goto free_vma;
} }
/* Now the Switcher is mapped at the right address, we can't fail! /*
* Copy in the compiled-in Switcher code (from <arch>_switcher.S). */ * Now the Switcher is mapped at the right address, we can't fail!
* Copy in the compiled-in Switcher code (from <arch>_switcher.S).
*/
memcpy(switcher_vma->addr, start_switcher_text, memcpy(switcher_vma->addr, start_switcher_text,
end_switcher_text - start_switcher_text); end_switcher_text - start_switcher_text);
...@@ -124,8 +140,7 @@ static __init int map_switcher(void) ...@@ -124,8 +140,7 @@ static __init int map_switcher(void)
} }
/*:*/ /*:*/
/* Cleaning up the mapping when the module is unloaded is almost... /* Cleaning up the mapping when the module is unloaded is almost... too easy. */
* too easy. */
static void unmap_switcher(void) static void unmap_switcher(void)
{ {
unsigned int i; unsigned int i;
...@@ -151,16 +166,19 @@ static void unmap_switcher(void) ...@@ -151,16 +166,19 @@ static void unmap_switcher(void)
* But we can't trust the Guest: it might be trying to access the Launcher * But we can't trust the Guest: it might be trying to access the Launcher
* code. We have to check that the range is below the pfn_limit the Launcher * code. We have to check that the range is below the pfn_limit the Launcher
* gave us. We have to make sure that addr + len doesn't give us a false * gave us. We have to make sure that addr + len doesn't give us a false
* positive by overflowing, too. */ * positive by overflowing, too.
*/
bool lguest_address_ok(const struct lguest *lg, bool lguest_address_ok(const struct lguest *lg,
unsigned long addr, unsigned long len) unsigned long addr, unsigned long len)
{ {
return (addr+len) / PAGE_SIZE < lg->pfn_limit && (addr+len >= addr); return (addr+len) / PAGE_SIZE < lg->pfn_limit && (addr+len >= addr);
} }
/* This routine copies memory from the Guest. Here we can see how useful the /*
* This routine copies memory from the Guest. Here we can see how useful the
* kill_lguest() routine we met in the Launcher can be: we return a random * kill_lguest() routine we met in the Launcher can be: we return a random
* value (all zeroes) instead of needing to return an error. */ * value (all zeroes) instead of needing to return an error.
*/
void __lgread(struct lg_cpu *cpu, void *b, unsigned long addr, unsigned bytes) void __lgread(struct lg_cpu *cpu, void *b, unsigned long addr, unsigned bytes)
{ {
if (!lguest_address_ok(cpu->lg, addr, bytes) if (!lguest_address_ok(cpu->lg, addr, bytes)
...@@ -181,9 +199,11 @@ void __lgwrite(struct lg_cpu *cpu, unsigned long addr, const void *b, ...@@ -181,9 +199,11 @@ void __lgwrite(struct lg_cpu *cpu, unsigned long addr, const void *b,
} }
/*:*/ /*:*/
/*H:030 Let's jump straight to the the main loop which runs the Guest. /*H:030
* Let's jump straight to the the main loop which runs the Guest.
* Remember, this is called by the Launcher reading /dev/lguest, and we keep * Remember, this is called by the Launcher reading /dev/lguest, and we keep
* going around and around until something interesting happens. */ * going around and around until something interesting happens.
*/
int run_guest(struct lg_cpu *cpu, unsigned long __user *user) int run_guest(struct lg_cpu *cpu, unsigned long __user *user)
{ {
/* We stop running once the Guest is dead. */ /* We stop running once the Guest is dead. */
...@@ -195,10 +215,17 @@ int run_guest(struct lg_cpu *cpu, unsigned long __user *user) ...@@ -195,10 +215,17 @@ int run_guest(struct lg_cpu *cpu, unsigned long __user *user)
if (cpu->hcall) if (cpu->hcall)
do_hypercalls(cpu); do_hypercalls(cpu);
/* It's possible the Guest did a NOTIFY hypercall to the /*
* Launcher, in which case we return from the read() now. */ * It's possible the Guest did a NOTIFY hypercall to the
* Launcher.
*/
if (cpu->pending_notify) { if (cpu->pending_notify) {
/*
* Does it just needs to write to a registered
* eventfd (ie. the appropriate virtqueue thread)?
*/
if (!send_notify_to_eventfd(cpu)) { if (!send_notify_to_eventfd(cpu)) {
/* OK, we tell the main Laucher. */
if (put_user(cpu->pending_notify, user)) if (put_user(cpu->pending_notify, user))
return -EFAULT; return -EFAULT;
return sizeof(cpu->pending_notify); return sizeof(cpu->pending_notify);
...@@ -209,29 +236,39 @@ int run_guest(struct lg_cpu *cpu, unsigned long __user *user) ...@@ -209,29 +236,39 @@ int run_guest(struct lg_cpu *cpu, unsigned long __user *user)
if (signal_pending(current)) if (signal_pending(current))
return -ERESTARTSYS; return -ERESTARTSYS;
/* Check if there are any interrupts which can be delivered now: /*
* Check if there are any interrupts which can be delivered now:
* if so, this sets up the hander to be executed when we next * if so, this sets up the hander to be executed when we next
* run the Guest. */ * run the Guest.
*/
irq = interrupt_pending(cpu, &more); irq = interrupt_pending(cpu, &more);
if (irq < LGUEST_IRQS) if (irq < LGUEST_IRQS)
try_deliver_interrupt(cpu, irq, more); try_deliver_interrupt(cpu, irq, more);
/* All long-lived kernel loops need to check with this horrible /*
* All long-lived kernel loops need to check with this horrible
* thing called the freezer. If the Host is trying to suspend, * thing called the freezer. If the Host is trying to suspend,
* it stops us. */ * it stops us.
*/
try_to_freeze(); try_to_freeze();
/* Just make absolutely sure the Guest is still alive. One of /*
* those hypercalls could have been fatal, for example. */ * Just make absolutely sure the Guest is still alive. One of
* those hypercalls could have been fatal, for example.
*/
if (cpu->lg->dead) if (cpu->lg->dead)
break; break;
/* If the Guest asked to be stopped, we sleep. The Guest's /*
* clock timer will wake us. */ * If the Guest asked to be stopped, we sleep. The Guest's
* clock timer will wake us.
*/
if (cpu->halted) { if (cpu->halted) {
set_current_state(TASK_INTERRUPTIBLE); set_current_state(TASK_INTERRUPTIBLE);
/* Just before we sleep, make sure no interrupt snuck in /*
* which we should be doing. */ * Just before we sleep, make sure no interrupt snuck in
* which we should be doing.
*/
if (interrupt_pending(cpu, &more) < LGUEST_IRQS) if (interrupt_pending(cpu, &more) < LGUEST_IRQS)
set_current_state(TASK_RUNNING); set_current_state(TASK_RUNNING);
else else
...@@ -239,8 +276,10 @@ int run_guest(struct lg_cpu *cpu, unsigned long __user *user) ...@@ -239,8 +276,10 @@ int run_guest(struct lg_cpu *cpu, unsigned long __user *user)
continue; continue;
} }
/* OK, now we're ready to jump into the Guest. First we put up /*
* the "Do Not Disturb" sign: */ * OK, now we're ready to jump into the Guest. First we put up
* the "Do Not Disturb" sign:
*/
local_irq_disable(); local_irq_disable();
/* Actually run the Guest until something happens. */ /* Actually run the Guest until something happens. */
...@@ -327,8 +366,10 @@ static void __exit fini(void) ...@@ -327,8 +366,10 @@ static void __exit fini(void)
} }
/*:*/ /*:*/
/* The Host side of lguest can be a module. This is a nice way for people to /*
* play with it. */ * The Host side of lguest can be a module. This is a nice way for people to
* play with it.
*/
module_init(init); module_init(init);
module_exit(fini); module_exit(fini);
MODULE_LICENSE("GPL"); MODULE_LICENSE("GPL");
......
/*P:500 Just as userspace programs request kernel operations through a system /*P:500
* Just as userspace programs request kernel operations through a system
* call, the Guest requests Host operations through a "hypercall". You might * call, the Guest requests Host operations through a "hypercall". You might
* notice this nomenclature doesn't really follow any logic, but the name has * notice this nomenclature doesn't really follow any logic, but the name has
* been around for long enough that we're stuck with it. As you'd expect, this * been around for long enough that we're stuck with it. As you'd expect, this
* code is basically a one big switch statement. :*/ * code is basically a one big switch statement.
:*/
/* Copyright (C) 2006 Rusty Russell IBM Corporation /* Copyright (C) 2006 Rusty Russell IBM Corporation
...@@ -28,30 +30,41 @@ ...@@ -28,30 +30,41 @@
#include <asm/pgtable.h> #include <asm/pgtable.h>
#include "lg.h" #include "lg.h"
/*H:120 This is the core hypercall routine: where the Guest gets what it wants. /*H:120
* Or gets killed. Or, in the case of LHCALL_SHUTDOWN, both. */ * This is the core hypercall routine: where the Guest gets what it wants.
* Or gets killed. Or, in the case of LHCALL_SHUTDOWN, both.
*/
static void do_hcall(struct lg_cpu *cpu, struct hcall_args *args) static void do_hcall(struct lg_cpu *cpu, struct hcall_args *args)
{ {
switch (args->arg0) { switch (args->arg0) {
case LHCALL_FLUSH_ASYNC: case LHCALL_FLUSH_ASYNC:
/* This call does nothing, except by breaking out of the Guest /*
* it makes us process all the asynchronous hypercalls. */ * This call does nothing, except by breaking out of the Guest
* it makes us process all the asynchronous hypercalls.
*/
break; break;
case LHCALL_SEND_INTERRUPTS: case LHCALL_SEND_INTERRUPTS:
/* This call does nothing too, but by breaking out of the Guest /*
* it makes us process any pending interrupts. */ * This call does nothing too, but by breaking out of the Guest
* it makes us process any pending interrupts.
*/
break; break;
case LHCALL_LGUEST_INIT: case LHCALL_LGUEST_INIT:
/* You can't get here unless you're already initialized. Don't /*
* do that. */ * You can't get here unless you're already initialized. Don't
* do that.
*/
kill_guest(cpu, "already have lguest_data"); kill_guest(cpu, "already have lguest_data");
break; break;
case LHCALL_SHUTDOWN: { case LHCALL_SHUTDOWN: {
/* Shutdown is such a trivial hypercall that we do it in four
* lines right here. */
char msg[128]; char msg[128];
/* If the lgread fails, it will call kill_guest() itself; the /*
* kill_guest() with the message will be ignored. */ * Shutdown is such a trivial hypercall that we do it in five
* lines right here.
*
* If the lgread fails, it will call kill_guest() itself; the
* kill_guest() with the message will be ignored.
*/
__lgread(cpu, msg, args->arg1, sizeof(msg)); __lgread(cpu, msg, args->arg1, sizeof(msg));
msg[sizeof(msg)-1] = '\0'; msg[sizeof(msg)-1] = '\0';
kill_guest(cpu, "CRASH: %s", msg); kill_guest(cpu, "CRASH: %s", msg);
...@@ -60,16 +73,17 @@ static void do_hcall(struct lg_cpu *cpu, struct hcall_args *args) ...@@ -60,16 +73,17 @@ static void do_hcall(struct lg_cpu *cpu, struct hcall_args *args)
break; break;
} }
case LHCALL_FLUSH_TLB: case LHCALL_FLUSH_TLB:
/* FLUSH_TLB comes in two flavors, depending on the /* FLUSH_TLB comes in two flavors, depending on the argument: */
* argument: */
if (args->arg1) if (args->arg1)
guest_pagetable_clear_all(cpu); guest_pagetable_clear_all(cpu);
else else
guest_pagetable_flush_user(cpu); guest_pagetable_flush_user(cpu);
break; break;
/* All these calls simply pass the arguments through to the right /*
* routines. */ * All these calls simply pass the arguments through to the right
* routines.
*/
case LHCALL_NEW_PGTABLE: case LHCALL_NEW_PGTABLE:
guest_new_pagetable(cpu, args->arg1); guest_new_pagetable(cpu, args->arg1);
break; break;
...@@ -112,15 +126,16 @@ static void do_hcall(struct lg_cpu *cpu, struct hcall_args *args) ...@@ -112,15 +126,16 @@ static void do_hcall(struct lg_cpu *cpu, struct hcall_args *args)
kill_guest(cpu, "Bad hypercall %li\n", args->arg0); kill_guest(cpu, "Bad hypercall %li\n", args->arg0);
} }
} }
/*:*/
/*H:124 Asynchronous hypercalls are easy: we just look in the array in the /*H:124
* Asynchronous hypercalls are easy: we just look in the array in the
* Guest's "struct lguest_data" to see if any new ones are marked "ready". * Guest's "struct lguest_data" to see if any new ones are marked "ready".
* *
* We are careful to do these in order: obviously we respect the order the * We are careful to do these in order: obviously we respect the order the
* Guest put them in the ring, but we also promise the Guest that they will * Guest put them in the ring, but we also promise the Guest that they will
* happen before any normal hypercall (which is why we check this before * happen before any normal hypercall (which is why we check this before
* checking for a normal hcall). */ * checking for a normal hcall).
*/
static void do_async_hcalls(struct lg_cpu *cpu) static void do_async_hcalls(struct lg_cpu *cpu)
{ {
unsigned int i; unsigned int i;
...@@ -133,22 +148,28 @@ static void do_async_hcalls(struct lg_cpu *cpu) ...@@ -133,22 +148,28 @@ static void do_async_hcalls(struct lg_cpu *cpu)
/* We process "struct lguest_data"s hcalls[] ring once. */ /* We process "struct lguest_data"s hcalls[] ring once. */
for (i = 0; i < ARRAY_SIZE(st); i++) { for (i = 0; i < ARRAY_SIZE(st); i++) {
struct hcall_args args; struct hcall_args args;
/* We remember where we were up to from last time. This makes /*
* We remember where we were up to from last time. This makes
* sure that the hypercalls are done in the order the Guest * sure that the hypercalls are done in the order the Guest
* places them in the ring. */ * places them in the ring.
*/
unsigned int n = cpu->next_hcall; unsigned int n = cpu->next_hcall;
/* 0xFF means there's no call here (yet). */ /* 0xFF means there's no call here (yet). */
if (st[n] == 0xFF) if (st[n] == 0xFF)
break; break;
/* OK, we have hypercall. Increment the "next_hcall" cursor, /*
* and wrap back to 0 if we reach the end. */ * OK, we have hypercall. Increment the "next_hcall" cursor,
* and wrap back to 0 if we reach the end.
*/
if (++cpu->next_hcall == LHCALL_RING_SIZE) if (++cpu->next_hcall == LHCALL_RING_SIZE)
cpu->next_hcall = 0; cpu->next_hcall = 0;
/* Copy the hypercall arguments into a local copy of /*
* the hcall_args struct. */ * Copy the hypercall arguments into a local copy of the
* hcall_args struct.
*/
if (copy_from_user(&args, &cpu->lg->lguest_data->hcalls[n], if (copy_from_user(&args, &cpu->lg->lguest_data->hcalls[n],
sizeof(struct hcall_args))) { sizeof(struct hcall_args))) {
kill_guest(cpu, "Fetching async hypercalls"); kill_guest(cpu, "Fetching async hypercalls");
...@@ -164,19 +185,25 @@ static void do_async_hcalls(struct lg_cpu *cpu) ...@@ -164,19 +185,25 @@ static void do_async_hcalls(struct lg_cpu *cpu)
break; break;
} }
/* Stop doing hypercalls if they want to notify the Launcher: /*
* it needs to service this first. */ * Stop doing hypercalls if they want to notify the Launcher:
* it needs to service this first.
*/
if (cpu->pending_notify) if (cpu->pending_notify)
break; break;
} }
} }
/* Last of all, we look at what happens first of all. The very first time the /*
* Guest makes a hypercall, we end up here to set things up: */ * Last of all, we look at what happens first of all. The very first time the
* Guest makes a hypercall, we end up here to set things up:
*/
static void initialize(struct lg_cpu *cpu) static void initialize(struct lg_cpu *cpu)
{ {
/* You can't do anything until you're initialized. The Guest knows the /*
* rules, so we're unforgiving here. */ * You can't do anything until you're initialized. The Guest knows the
* rules, so we're unforgiving here.
*/
if (cpu->hcall->arg0 != LHCALL_LGUEST_INIT) { if (cpu->hcall->arg0 != LHCALL_LGUEST_INIT) {
kill_guest(cpu, "hypercall %li before INIT", cpu->hcall->arg0); kill_guest(cpu, "hypercall %li before INIT", cpu->hcall->arg0);
return; return;
...@@ -185,32 +212,44 @@ static void initialize(struct lg_cpu *cpu) ...@@ -185,32 +212,44 @@ static void initialize(struct lg_cpu *cpu)
if (lguest_arch_init_hypercalls(cpu)) if (lguest_arch_init_hypercalls(cpu))
kill_guest(cpu, "bad guest page %p", cpu->lg->lguest_data); kill_guest(cpu, "bad guest page %p", cpu->lg->lguest_data);
/* The Guest tells us where we're not to deliver interrupts by putting /*
* the range of addresses into "struct lguest_data". */ * The Guest tells us where we're not to deliver interrupts by putting
* the range of addresses into "struct lguest_data".
*/
if (get_user(cpu->lg->noirq_start, &cpu->lg->lguest_data->noirq_start) if (get_user(cpu->lg->noirq_start, &cpu->lg->lguest_data->noirq_start)
|| get_user(cpu->lg->noirq_end, &cpu->lg->lguest_data->noirq_end)) || get_user(cpu->lg->noirq_end, &cpu->lg->lguest_data->noirq_end))
kill_guest(cpu, "bad guest page %p", cpu->lg->lguest_data); kill_guest(cpu, "bad guest page %p", cpu->lg->lguest_data);
/* We write the current time into the Guest's data page once so it can /*
* set its clock. */ * We write the current time into the Guest's data page once so it can
* set its clock.
*/
write_timestamp(cpu); write_timestamp(cpu);
/* page_tables.c will also do some setup. */ /* page_tables.c will also do some setup. */
page_table_guest_data_init(cpu); page_table_guest_data_init(cpu);
/* This is the one case where the above accesses might have been the /*
* This is the one case where the above accesses might have been the
* first write to a Guest page. This may have caused a copy-on-write * first write to a Guest page. This may have caused a copy-on-write
* fault, but the old page might be (read-only) in the Guest * fault, but the old page might be (read-only) in the Guest
* pagetable. */ * pagetable.
*/
guest_pagetable_clear_all(cpu); guest_pagetable_clear_all(cpu);
} }
/*:*/ /*:*/
/*M:013 If a Guest reads from a page (so creates a mapping) that it has never /*M:013
* If a Guest reads from a page (so creates a mapping) that it has never
* written to, and then the Launcher writes to it (ie. the output of a virtual * written to, and then the Launcher writes to it (ie. the output of a virtual
* device), the Guest will still see the old page. In practice, this never * device), the Guest will still see the old page. In practice, this never
* happens: why would the Guest read a page which it has never written to? But * happens: why would the Guest read a page which it has never written to? But
* a similar scenario might one day bite us, so it's worth mentioning. :*/ * a similar scenario might one day bite us, so it's worth mentioning.
*
* Note that if we used a shared anonymous mapping in the Launcher instead of
* mapping /dev/zero private, we wouldn't worry about cop-on-write. And we
* need that to switch the Launcher to processes (away from threads) anyway.
:*/
/*H:100 /*H:100
* Hypercalls * Hypercalls
...@@ -229,17 +268,22 @@ void do_hypercalls(struct lg_cpu *cpu) ...@@ -229,17 +268,22 @@ void do_hypercalls(struct lg_cpu *cpu)
return; return;
} }
/* The Guest has initialized. /*
* The Guest has initialized.
* *
* Look in the hypercall ring for the async hypercalls: */ * Look in the hypercall ring for the async hypercalls:
*/
do_async_hcalls(cpu); do_async_hcalls(cpu);
/* If we stopped reading the hypercall ring because the Guest did a /*
* If we stopped reading the hypercall ring because the Guest did a
* NOTIFY to the Launcher, we want to return now. Otherwise we do * NOTIFY to the Launcher, we want to return now. Otherwise we do
* the hypercall. */ * the hypercall.
*/
if (!cpu->pending_notify) { if (!cpu->pending_notify) {
do_hcall(cpu, cpu->hcall); do_hcall(cpu, cpu->hcall);
/* Tricky point: we reset the hcall pointer to mark the /*
* Tricky point: we reset the hcall pointer to mark the
* hypercall as "done". We use the hcall pointer rather than * hypercall as "done". We use the hcall pointer rather than
* the trap number to indicate a hypercall is pending. * the trap number to indicate a hypercall is pending.
* Normally it doesn't matter: the Guest will run again and * Normally it doesn't matter: the Guest will run again and
...@@ -248,13 +292,16 @@ void do_hypercalls(struct lg_cpu *cpu) ...@@ -248,13 +292,16 @@ void do_hypercalls(struct lg_cpu *cpu)
* However, if we are signalled or the Guest sends I/O to the * However, if we are signalled or the Guest sends I/O to the
* Launcher, the run_guest() loop will exit without running the * Launcher, the run_guest() loop will exit without running the
* Guest. When it comes back it would try to re-run the * Guest. When it comes back it would try to re-run the
* hypercall. Finding that bug sucked. */ * hypercall. Finding that bug sucked.
*/
cpu->hcall = NULL; cpu->hcall = NULL;
} }
} }
/* This routine supplies the Guest with time: it's used for wallclock time at /*
* initial boot and as a rough time source if the TSC isn't available. */ * This routine supplies the Guest with time: it's used for wallclock time at
* initial boot and as a rough time source if the TSC isn't available.
*/
void write_timestamp(struct lg_cpu *cpu) void write_timestamp(struct lg_cpu *cpu)
{ {
struct timespec now; struct timespec now;
......
...@@ -16,15 +16,13 @@ ...@@ -16,15 +16,13 @@
void free_pagetables(void); void free_pagetables(void);
int init_pagetables(struct page **switcher_page, unsigned int pages); int init_pagetables(struct page **switcher_page, unsigned int pages);
struct pgdir struct pgdir {
{
unsigned long gpgdir; unsigned long gpgdir;
pgd_t *pgdir; pgd_t *pgdir;
}; };
/* We have two pages shared with guests, per cpu. */ /* We have two pages shared with guests, per cpu. */
struct lguest_pages struct lguest_pages {
{
/* This is the stack page mapped rw in guest */ /* This is the stack page mapped rw in guest */
char spare[PAGE_SIZE - sizeof(struct lguest_regs)]; char spare[PAGE_SIZE - sizeof(struct lguest_regs)];
struct lguest_regs regs; struct lguest_regs regs;
...@@ -60,7 +58,7 @@ struct lg_cpu { ...@@ -60,7 +58,7 @@ struct lg_cpu {
struct lguest_pages *last_pages; struct lguest_pages *last_pages;
int cpu_pgd; /* which pgd this cpu is currently using */ int cpu_pgd; /* Which pgd this cpu is currently using */
/* If a hypercall was asked for, this points to the arguments. */ /* If a hypercall was asked for, this points to the arguments. */
struct hcall_args *hcall; struct hcall_args *hcall;
...@@ -89,15 +87,17 @@ struct lg_eventfd_map { ...@@ -89,15 +87,17 @@ struct lg_eventfd_map {
}; };
/* The private info the thread maintains about the guest. */ /* The private info the thread maintains about the guest. */
struct lguest struct lguest {
{
struct lguest_data __user *lguest_data; struct lguest_data __user *lguest_data;
struct lg_cpu cpus[NR_CPUS]; struct lg_cpu cpus[NR_CPUS];
unsigned int nr_cpus; unsigned int nr_cpus;
u32 pfn_limit; u32 pfn_limit;
/* This provides the offset to the base of guest-physical
* memory in the Launcher. */ /*
* This provides the offset to the base of guest-physical memory in the
* Launcher.
*/
void __user *mem_base; void __user *mem_base;
unsigned long kernel_address; unsigned long kernel_address;
...@@ -122,11 +122,13 @@ bool lguest_address_ok(const struct lguest *lg, ...@@ -122,11 +122,13 @@ bool lguest_address_ok(const struct lguest *lg,
void __lgread(struct lg_cpu *, void *, unsigned long, unsigned); void __lgread(struct lg_cpu *, void *, unsigned long, unsigned);
void __lgwrite(struct lg_cpu *, unsigned long, const void *, unsigned); void __lgwrite(struct lg_cpu *, unsigned long, const void *, unsigned);
/*H:035 Using memory-copy operations like that is usually inconvient, so we /*H:035
* Using memory-copy operations like that is usually inconvient, so we
* have the following helper macros which read and write a specific type (often * have the following helper macros which read and write a specific type (often
* an unsigned long). * an unsigned long).
* *
* This reads into a variable of the given type then returns that. */ * This reads into a variable of the given type then returns that.
*/
#define lgread(cpu, addr, type) \ #define lgread(cpu, addr, type) \
({ type _v; __lgread((cpu), &_v, (addr), sizeof(_v)); _v; }) ({ type _v; __lgread((cpu), &_v, (addr), sizeof(_v)); _v; })
...@@ -140,9 +142,11 @@ void __lgwrite(struct lg_cpu *, unsigned long, const void *, unsigned); ...@@ -140,9 +142,11 @@ void __lgwrite(struct lg_cpu *, unsigned long, const void *, unsigned);
int run_guest(struct lg_cpu *cpu, unsigned long __user *user); int run_guest(struct lg_cpu *cpu, unsigned long __user *user);
/* Helper macros to obtain the first 12 or the last 20 bits, this is only the /*
* Helper macros to obtain the first 12 or the last 20 bits, this is only the
* first step in the migration to the kernel types. pte_pfn is already defined * first step in the migration to the kernel types. pte_pfn is already defined
* in the kernel. */ * in the kernel.
*/
#define pgd_flags(x) (pgd_val(x) & ~PAGE_MASK) #define pgd_flags(x) (pgd_val(x) & ~PAGE_MASK)
#define pgd_pfn(x) (pgd_val(x) >> PAGE_SHIFT) #define pgd_pfn(x) (pgd_val(x) >> PAGE_SHIFT)
#define pmd_flags(x) (pmd_val(x) & ~PAGE_MASK) #define pmd_flags(x) (pmd_val(x) & ~PAGE_MASK)
......
/*P:050 Lguest guests use a very simple method to describe devices. It's a /*P:050
* Lguest guests use a very simple method to describe devices. It's a
* series of device descriptors contained just above the top of normal Guest * series of device descriptors contained just above the top of normal Guest
* memory. * memory.
* *
* We use the standard "virtio" device infrastructure, which provides us with a * We use the standard "virtio" device infrastructure, which provides us with a
* console, a network and a block driver. Each one expects some configuration * console, a network and a block driver. Each one expects some configuration
* information and a "virtqueue" or two to send and receive data. :*/ * information and a "virtqueue" or two to send and receive data.
:*/
#include <linux/init.h> #include <linux/init.h>
#include <linux/bootmem.h> #include <linux/bootmem.h>
#include <linux/lguest_launcher.h> #include <linux/lguest_launcher.h>
...@@ -20,8 +22,10 @@ ...@@ -20,8 +22,10 @@
/* The pointer to our (page) of device descriptions. */ /* The pointer to our (page) of device descriptions. */
static void *lguest_devices; static void *lguest_devices;
/* For Guests, device memory can be used as normal memory, so we cast away the /*
* __iomem to quieten sparse. */ * For Guests, device memory can be used as normal memory, so we cast away the
* __iomem to quieten sparse.
*/
static inline void *lguest_map(unsigned long phys_addr, unsigned long pages) static inline void *lguest_map(unsigned long phys_addr, unsigned long pages)
{ {
return (__force void *)ioremap_cache(phys_addr, PAGE_SIZE*pages); return (__force void *)ioremap_cache(phys_addr, PAGE_SIZE*pages);
...@@ -32,8 +36,10 @@ static inline void lguest_unmap(void *addr) ...@@ -32,8 +36,10 @@ static inline void lguest_unmap(void *addr)
iounmap((__force void __iomem *)addr); iounmap((__force void __iomem *)addr);
} }
/*D:100 Each lguest device is just a virtio device plus a pointer to its entry /*D:100
* in the lguest_devices page. */ * Each lguest device is just a virtio device plus a pointer to its entry
* in the lguest_devices page.
*/
struct lguest_device { struct lguest_device {
struct virtio_device vdev; struct virtio_device vdev;
...@@ -41,9 +47,11 @@ struct lguest_device { ...@@ -41,9 +47,11 @@ struct lguest_device {
struct lguest_device_desc *desc; struct lguest_device_desc *desc;
}; };
/* Since the virtio infrastructure hands us a pointer to the virtio_device all /*
* Since the virtio infrastructure hands us a pointer to the virtio_device all
* the time, it helps to have a curt macro to get a pointer to the struct * the time, it helps to have a curt macro to get a pointer to the struct
* lguest_device it's enclosed in. */ * lguest_device it's enclosed in.
*/
#define to_lgdev(vd) container_of(vd, struct lguest_device, vdev) #define to_lgdev(vd) container_of(vd, struct lguest_device, vdev)
/*D:130 /*D:130
...@@ -55,7 +63,8 @@ struct lguest_device { ...@@ -55,7 +63,8 @@ struct lguest_device {
* the driver will look at them during setup. * the driver will look at them during setup.
* *
* A convenient routine to return the device's virtqueue config array: * A convenient routine to return the device's virtqueue config array:
* immediately after the descriptor. */ * immediately after the descriptor.
*/
static struct lguest_vqconfig *lg_vq(const struct lguest_device_desc *desc) static struct lguest_vqconfig *lg_vq(const struct lguest_device_desc *desc)
{ {
return (void *)(desc + 1); return (void *)(desc + 1);
...@@ -98,10 +107,12 @@ static u32 lg_get_features(struct virtio_device *vdev) ...@@ -98,10 +107,12 @@ static u32 lg_get_features(struct virtio_device *vdev)
return features; return features;
} }
/* The virtio core takes the features the Host offers, and copies the /*
* ones supported by the driver into the vdev->features array. Once * The virtio core takes the features the Host offers, and copies the ones
* that's all sorted out, this routine is called so we can tell the * supported by the driver into the vdev->features array. Once that's all
* Host which features we understand and accept. */ * sorted out, this routine is called so we can tell the Host which features we
* understand and accept.
*/
static void lg_finalize_features(struct virtio_device *vdev) static void lg_finalize_features(struct virtio_device *vdev)
{ {
unsigned int i, bits; unsigned int i, bits;
...@@ -112,10 +123,11 @@ static void lg_finalize_features(struct virtio_device *vdev) ...@@ -112,10 +123,11 @@ static void lg_finalize_features(struct virtio_device *vdev)
/* Give virtio_ring a chance to accept features. */ /* Give virtio_ring a chance to accept features. */
vring_transport_features(vdev); vring_transport_features(vdev);
/* The vdev->feature array is a Linux bitmask: this isn't the /*
* same as a the simple array of bits used by lguest devices * The vdev->feature array is a Linux bitmask: this isn't the same as a
* for features. So we do this slow, manual conversion which is * the simple array of bits used by lguest devices for features. So we
* completely general. */ * do this slow, manual conversion which is completely general.
*/
memset(out_features, 0, desc->feature_len); memset(out_features, 0, desc->feature_len);
bits = min_t(unsigned, desc->feature_len, sizeof(vdev->features)) * 8; bits = min_t(unsigned, desc->feature_len, sizeof(vdev->features)) * 8;
for (i = 0; i < bits; i++) { for (i = 0; i < bits; i++) {
...@@ -146,15 +158,19 @@ static void lg_set(struct virtio_device *vdev, unsigned int offset, ...@@ -146,15 +158,19 @@ static void lg_set(struct virtio_device *vdev, unsigned int offset,
memcpy(lg_config(desc) + offset, buf, len); memcpy(lg_config(desc) + offset, buf, len);
} }
/* The operations to get and set the status word just access the status field /*
* of the device descriptor. */ * The operations to get and set the status word just access the status field
* of the device descriptor.
*/
static u8 lg_get_status(struct virtio_device *vdev) static u8 lg_get_status(struct virtio_device *vdev)
{ {
return to_lgdev(vdev)->desc->status; return to_lgdev(vdev)->desc->status;
} }
/* To notify on status updates, we (ab)use the NOTIFY hypercall, with the /*
* descriptor address of the device. A zero status means "reset". */ * To notify on status updates, we (ab)use the NOTIFY hypercall, with the
* descriptor address of the device. A zero status means "reset".
*/
static void set_status(struct virtio_device *vdev, u8 status) static void set_status(struct virtio_device *vdev, u8 status)
{ {
unsigned long offset = (void *)to_lgdev(vdev)->desc - lguest_devices; unsigned long offset = (void *)to_lgdev(vdev)->desc - lguest_devices;
...@@ -191,8 +207,7 @@ static void lg_reset(struct virtio_device *vdev) ...@@ -191,8 +207,7 @@ static void lg_reset(struct virtio_device *vdev)
*/ */
/*D:140 This is the information we remember about each virtqueue. */ /*D:140 This is the information we remember about each virtqueue. */
struct lguest_vq_info struct lguest_vq_info {
{
/* A copy of the information contained in the device config. */ /* A copy of the information contained in the device config. */
struct lguest_vqconfig config; struct lguest_vqconfig config;
...@@ -200,13 +215,17 @@ struct lguest_vq_info ...@@ -200,13 +215,17 @@ struct lguest_vq_info
void *pages; void *pages;
}; };
/* When the virtio_ring code wants to prod the Host, it calls us here and we /*
* When the virtio_ring code wants to prod the Host, it calls us here and we
* make a hypercall. We hand the physical address of the virtqueue so the Host * make a hypercall. We hand the physical address of the virtqueue so the Host
* knows which virtqueue we're talking about. */ * knows which virtqueue we're talking about.
*/
static void lg_notify(struct virtqueue *vq) static void lg_notify(struct virtqueue *vq)
{ {
/* We store our virtqueue information in the "priv" pointer of the /*
* virtqueue structure. */ * We store our virtqueue information in the "priv" pointer of the
* virtqueue structure.
*/
struct lguest_vq_info *lvq = vq->priv; struct lguest_vq_info *lvq = vq->priv;
kvm_hypercall1(LHCALL_NOTIFY, lvq->config.pfn << PAGE_SHIFT); kvm_hypercall1(LHCALL_NOTIFY, lvq->config.pfn << PAGE_SHIFT);
...@@ -215,7 +234,8 @@ static void lg_notify(struct virtqueue *vq) ...@@ -215,7 +234,8 @@ static void lg_notify(struct virtqueue *vq)
/* An extern declaration inside a C file is bad form. Don't do it. */ /* An extern declaration inside a C file is bad form. Don't do it. */
extern void lguest_setup_irq(unsigned int irq); extern void lguest_setup_irq(unsigned int irq);
/* This routine finds the first virtqueue described in the configuration of /*
* This routine finds the Nth virtqueue described in the configuration of
* this device and sets it up. * this device and sets it up.
* *
* This is kind of an ugly duckling. It'd be nicer to have a standard * This is kind of an ugly duckling. It'd be nicer to have a standard
...@@ -223,9 +243,7 @@ extern void lguest_setup_irq(unsigned int irq); ...@@ -223,9 +243,7 @@ extern void lguest_setup_irq(unsigned int irq);
* everyone wants to do it differently. The KVM coders want the Guest to * everyone wants to do it differently. The KVM coders want the Guest to
* allocate its own pages and tell the Host where they are, but for lguest it's * allocate its own pages and tell the Host where they are, but for lguest it's
* simpler for the Host to simply tell us where the pages are. * simpler for the Host to simply tell us where the pages are.
* */
* So we provide drivers with a "find the Nth virtqueue and set it up"
* function. */
static struct virtqueue *lg_find_vq(struct virtio_device *vdev, static struct virtqueue *lg_find_vq(struct virtio_device *vdev,
unsigned index, unsigned index,
void (*callback)(struct virtqueue *vq), void (*callback)(struct virtqueue *vq),
...@@ -244,9 +262,11 @@ static struct virtqueue *lg_find_vq(struct virtio_device *vdev, ...@@ -244,9 +262,11 @@ static struct virtqueue *lg_find_vq(struct virtio_device *vdev,
if (!lvq) if (!lvq)
return ERR_PTR(-ENOMEM); return ERR_PTR(-ENOMEM);
/* Make a copy of the "struct lguest_vqconfig" entry, which sits after /*
* Make a copy of the "struct lguest_vqconfig" entry, which sits after
* the descriptor. We need a copy because the config space might not * the descriptor. We need a copy because the config space might not
* be aligned correctly. */ * be aligned correctly.
*/
memcpy(&lvq->config, lg_vq(ldev->desc)+index, sizeof(lvq->config)); memcpy(&lvq->config, lg_vq(ldev->desc)+index, sizeof(lvq->config));
printk("Mapping virtqueue %i addr %lx\n", index, printk("Mapping virtqueue %i addr %lx\n", index,
...@@ -261,8 +281,10 @@ static struct virtqueue *lg_find_vq(struct virtio_device *vdev, ...@@ -261,8 +281,10 @@ static struct virtqueue *lg_find_vq(struct virtio_device *vdev,
goto free_lvq; goto free_lvq;
} }
/* OK, tell virtio_ring.c to set up a virtqueue now we know its size /*
* and we've got a pointer to its pages. */ * OK, tell virtio_ring.c to set up a virtqueue now we know its size
* and we've got a pointer to its pages.
*/
vq = vring_new_virtqueue(lvq->config.num, LGUEST_VRING_ALIGN, vq = vring_new_virtqueue(lvq->config.num, LGUEST_VRING_ALIGN,
vdev, lvq->pages, lg_notify, callback, name); vdev, lvq->pages, lg_notify, callback, name);
if (!vq) { if (!vq) {
...@@ -273,18 +295,23 @@ static struct virtqueue *lg_find_vq(struct virtio_device *vdev, ...@@ -273,18 +295,23 @@ static struct virtqueue *lg_find_vq(struct virtio_device *vdev,
/* Make sure the interrupt is allocated. */ /* Make sure the interrupt is allocated. */
lguest_setup_irq(lvq->config.irq); lguest_setup_irq(lvq->config.irq);
/* Tell the interrupt for this virtqueue to go to the virtio_ring /*
* interrupt handler. */ * Tell the interrupt for this virtqueue to go to the virtio_ring
/* FIXME: We used to have a flag for the Host to tell us we could use * interrupt handler.
*
* FIXME: We used to have a flag for the Host to tell us we could use
* the interrupt as a source of randomness: it'd be nice to have that * the interrupt as a source of randomness: it'd be nice to have that
* back.. */ * back.
*/
err = request_irq(lvq->config.irq, vring_interrupt, IRQF_SHARED, err = request_irq(lvq->config.irq, vring_interrupt, IRQF_SHARED,
dev_name(&vdev->dev), vq); dev_name(&vdev->dev), vq);
if (err) if (err)
goto destroy_vring; goto destroy_vring;
/* Last of all we hook up our 'struct lguest_vq_info" to the /*
* virtqueue's priv pointer. */ * Last of all we hook up our 'struct lguest_vq_info" to the
* virtqueue's priv pointer.
*/
vq->priv = lvq; vq->priv = lvq;
return vq; return vq;
...@@ -358,11 +385,14 @@ static struct virtio_config_ops lguest_config_ops = { ...@@ -358,11 +385,14 @@ static struct virtio_config_ops lguest_config_ops = {
.del_vqs = lg_del_vqs, .del_vqs = lg_del_vqs,
}; };
/* The root device for the lguest virtio devices. This makes them appear as /*
* /sys/devices/lguest/0,1,2 not /sys/devices/0,1,2. */ * The root device for the lguest virtio devices. This makes them appear as
* /sys/devices/lguest/0,1,2 not /sys/devices/0,1,2.
*/
static struct device *lguest_root; static struct device *lguest_root;
/*D:120 This is the core of the lguest bus: actually adding a new device. /*D:120
* This is the core of the lguest bus: actually adding a new device.
* It's a separate function because it's neater that way, and because an * It's a separate function because it's neater that way, and because an
* earlier version of the code supported hotplug and unplug. They were removed * earlier version of the code supported hotplug and unplug. They were removed
* early on because they were never used. * early on because they were never used.
...@@ -371,14 +401,14 @@ static struct device *lguest_root; ...@@ -371,14 +401,14 @@ static struct device *lguest_root;
* *
* It's worth reading this carefully: we start with a pointer to the new device * It's worth reading this carefully: we start with a pointer to the new device
* descriptor in the "lguest_devices" page, and the offset into the device * descriptor in the "lguest_devices" page, and the offset into the device
* descriptor page so we can uniquely identify it if things go badly wrong. */ * descriptor page so we can uniquely identify it if things go badly wrong.
*/
static void add_lguest_device(struct lguest_device_desc *d, static void add_lguest_device(struct lguest_device_desc *d,
unsigned int offset) unsigned int offset)
{ {
struct lguest_device *ldev; struct lguest_device *ldev;
/* Start with zeroed memory; Linux's device layer seems to count on /* Start with zeroed memory; Linux's device layer counts on it. */
* it. */
ldev = kzalloc(sizeof(*ldev), GFP_KERNEL); ldev = kzalloc(sizeof(*ldev), GFP_KERNEL);
if (!ldev) { if (!ldev) {
printk(KERN_EMERG "Cannot allocate lguest dev %u type %u\n", printk(KERN_EMERG "Cannot allocate lguest dev %u type %u\n",
...@@ -388,17 +418,25 @@ static void add_lguest_device(struct lguest_device_desc *d, ...@@ -388,17 +418,25 @@ static void add_lguest_device(struct lguest_device_desc *d,
/* This devices' parent is the lguest/ dir. */ /* This devices' parent is the lguest/ dir. */
ldev->vdev.dev.parent = lguest_root; ldev->vdev.dev.parent = lguest_root;
/* We have a unique device index thanks to the dev_index counter. */ /*
* The device type comes straight from the descriptor. There's also a
* device vendor field in the virtio_device struct, which we leave as
* 0.
*/
ldev->vdev.id.device = d->type; ldev->vdev.id.device = d->type;
/* We have a simple set of routines for querying the device's /*
* configuration information and setting its status. */ * We have a simple set of routines for querying the device's
* configuration information and setting its status.
*/
ldev->vdev.config = &lguest_config_ops; ldev->vdev.config = &lguest_config_ops;
/* And we remember the device's descriptor for lguest_config_ops. */ /* And we remember the device's descriptor for lguest_config_ops. */
ldev->desc = d; ldev->desc = d;
/* register_virtio_device() sets up the generic fields for the struct /*
* register_virtio_device() sets up the generic fields for the struct
* virtio_device and calls device_register(). This makes the bus * virtio_device and calls device_register(). This makes the bus
* infrastructure look for a matching driver. */ * infrastructure look for a matching driver.
*/
if (register_virtio_device(&ldev->vdev) != 0) { if (register_virtio_device(&ldev->vdev) != 0) {
printk(KERN_ERR "Failed to register lguest dev %u type %u\n", printk(KERN_ERR "Failed to register lguest dev %u type %u\n",
offset, d->type); offset, d->type);
...@@ -406,8 +444,10 @@ static void add_lguest_device(struct lguest_device_desc *d, ...@@ -406,8 +444,10 @@ static void add_lguest_device(struct lguest_device_desc *d,
} }
} }
/*D:110 scan_devices() simply iterates through the device page. The type 0 is /*D:110
* reserved to mean "end of devices". */ * scan_devices() simply iterates through the device page. The type 0 is
* reserved to mean "end of devices".
*/
static void scan_devices(void) static void scan_devices(void)
{ {
unsigned int i; unsigned int i;
...@@ -426,7 +466,8 @@ static void scan_devices(void) ...@@ -426,7 +466,8 @@ static void scan_devices(void)
} }
} }
/*D:105 Fairly early in boot, lguest_devices_init() is called to set up the /*D:105
* Fairly early in boot, lguest_devices_init() is called to set up the
* lguest device infrastructure. We check that we are a Guest by checking * lguest device infrastructure. We check that we are a Guest by checking
* pv_info.name: there are other ways of checking, but this seems most * pv_info.name: there are other ways of checking, but this seems most
* obvious to me. * obvious to me.
...@@ -437,7 +478,8 @@ static void scan_devices(void) ...@@ -437,7 +478,8 @@ static void scan_devices(void)
* correct sysfs incantation). * correct sysfs incantation).
* *
* Finally we call scan_devices() which adds all the devices found in the * Finally we call scan_devices() which adds all the devices found in the
* lguest_devices page. */ * lguest_devices page.
*/
static int __init lguest_devices_init(void) static int __init lguest_devices_init(void)
{ {
if (strcmp(pv_info.name, "lguest") != 0) if (strcmp(pv_info.name, "lguest") != 0)
...@@ -456,11 +498,13 @@ static int __init lguest_devices_init(void) ...@@ -456,11 +498,13 @@ static int __init lguest_devices_init(void)
/* We do this after core stuff, but before the drivers. */ /* We do this after core stuff, but before the drivers. */
postcore_initcall(lguest_devices_init); postcore_initcall(lguest_devices_init);
/*D:150 At this point in the journey we used to now wade through the lguest /*D:150
* At this point in the journey we used to now wade through the lguest
* devices themselves: net, block and console. Since they're all now virtio * devices themselves: net, block and console. Since they're all now virtio
* devices rather than lguest-specific, I've decided to ignore them. Mostly, * devices rather than lguest-specific, I've decided to ignore them. Mostly,
* they're kind of boring. But this does mean you'll never experience the * they're kind of boring. But this does mean you'll never experience the
* thrill of reading the forbidden love scene buried deep in the block driver. * thrill of reading the forbidden love scene buried deep in the block driver.
* *
* "make Launcher" beckons, where we answer questions like "Where do Guests * "make Launcher" beckons, where we answer questions like "Where do Guests
* come from?", and "What do you do when someone asks for optimization?". */ * come from?", and "What do you do when someone asks for optimization?".
*/
/*P:200 This contains all the /dev/lguest code, whereby the userspace launcher /*P:200 This contains all the /dev/lguest code, whereby the userspace launcher
* controls and communicates with the Guest. For example, the first write will * controls and communicates with the Guest. For example, the first write will
* tell us the Guest's memory layout, pagetable, entry point and kernel address * tell us the Guest's memory layout and entry point. A read will run the
* offset. A read will run the Guest until something happens, such as a signal * Guest until something happens, such as a signal or the Guest doing a NOTIFY
* or the Guest doing a NOTIFY out to the Launcher. :*/ * out to the Launcher.
:*/
#include <linux/uaccess.h> #include <linux/uaccess.h>
#include <linux/miscdevice.h> #include <linux/miscdevice.h>
#include <linux/fs.h> #include <linux/fs.h>
...@@ -11,14 +12,41 @@ ...@@ -11,14 +12,41 @@
#include <linux/file.h> #include <linux/file.h>
#include "lg.h" #include "lg.h"
/*L:056
* Before we move on, let's jump ahead and look at what the kernel does when
* it needs to look up the eventfds. That will complete our picture of how we
* use RCU.
*
* The notification value is in cpu->pending_notify: we return true if it went
* to an eventfd.
*/
bool send_notify_to_eventfd(struct lg_cpu *cpu) bool send_notify_to_eventfd(struct lg_cpu *cpu)
{ {
unsigned int i; unsigned int i;
struct lg_eventfd_map *map; struct lg_eventfd_map *map;
/* lg->eventfds is RCU-protected */ /*
* This "rcu_read_lock()" helps track when someone is still looking at
* the (RCU-using) eventfds array. It's not actually a lock at all;
* indeed it's a noop in many configurations. (You didn't expect me to
* explain all the RCU secrets here, did you?)
*/
rcu_read_lock(); rcu_read_lock();
/*
* rcu_dereference is the counter-side of rcu_assign_pointer(); it
* makes sure we don't access the memory pointed to by
* cpu->lg->eventfds before cpu->lg->eventfds is set. Sounds crazy,
* but Alpha allows this! Paul McKenney points out that a really
* aggressive compiler could have the same effect:
* http://lists.ozlabs.org/pipermail/lguest/2009-July/001560.html
*
* So play safe, use rcu_dereference to get the rcu-protected pointer:
*/
map = rcu_dereference(cpu->lg->eventfds); map = rcu_dereference(cpu->lg->eventfds);
/*
* Simple array search: even if they add an eventfd while we do this,
* we'll continue to use the old array and just won't see the new one.
*/
for (i = 0; i < map->num; i++) { for (i = 0; i < map->num; i++) {
if (map->map[i].addr == cpu->pending_notify) { if (map->map[i].addr == cpu->pending_notify) {
eventfd_signal(map->map[i].event, 1); eventfd_signal(map->map[i].event, 1);
...@@ -26,19 +54,50 @@ bool send_notify_to_eventfd(struct lg_cpu *cpu) ...@@ -26,19 +54,50 @@ bool send_notify_to_eventfd(struct lg_cpu *cpu)
break; break;
} }
} }
/* We're done with the rcu-protected variable cpu->lg->eventfds. */
rcu_read_unlock(); rcu_read_unlock();
/* If we cleared the notification, it's because we found a match. */
return cpu->pending_notify == 0; return cpu->pending_notify == 0;
} }
/*L:055
* One of the more tricksy tricks in the Linux Kernel is a technique called
* Read Copy Update. Since one point of lguest is to teach lguest journeyers
* about kernel coding, I use it here. (In case you're curious, other purposes
* include learning about virtualization and instilling a deep appreciation for
* simplicity and puppies).
*
* We keep a simple array which maps LHCALL_NOTIFY values to eventfds, but we
* add new eventfds without ever blocking readers from accessing the array.
* The current Launcher only does this during boot, so that never happens. But
* Read Copy Update is cool, and adding a lock risks damaging even more puppies
* than this code does.
*
* We allocate a brand new one-larger array, copy the old one and add our new
* element. Then we make the lg eventfd pointer point to the new array.
* That's the easy part: now we need to free the old one, but we need to make
* sure no slow CPU somewhere is still looking at it. That's what
* synchronize_rcu does for us: waits until every CPU has indicated that it has
* moved on to know it's no longer using the old one.
*
* If that's unclear, see http://en.wikipedia.org/wiki/Read-copy-update.
*/
static int add_eventfd(struct lguest *lg, unsigned long addr, int fd) static int add_eventfd(struct lguest *lg, unsigned long addr, int fd)
{ {
struct lg_eventfd_map *new, *old = lg->eventfds; struct lg_eventfd_map *new, *old = lg->eventfds;
/*
* We don't allow notifications on value 0 anyway (pending_notify of
* 0 means "nothing pending").
*/
if (!addr) if (!addr)
return -EINVAL; return -EINVAL;
/* Replace the old array with the new one, carefully: others can /*
* be accessing it at the same time */ * Replace the old array with the new one, carefully: others can
* be accessing it at the same time.
*/
new = kmalloc(sizeof(*new) + sizeof(new->map[0]) * (old->num + 1), new = kmalloc(sizeof(*new) + sizeof(new->map[0]) * (old->num + 1),
GFP_KERNEL); GFP_KERNEL);
if (!new) if (!new)
...@@ -52,22 +111,41 @@ static int add_eventfd(struct lguest *lg, unsigned long addr, int fd) ...@@ -52,22 +111,41 @@ static int add_eventfd(struct lguest *lg, unsigned long addr, int fd)
new->map[new->num].addr = addr; new->map[new->num].addr = addr;
new->map[new->num].event = eventfd_ctx_fdget(fd); new->map[new->num].event = eventfd_ctx_fdget(fd);
if (IS_ERR(new->map[new->num].event)) { if (IS_ERR(new->map[new->num].event)) {
int err = PTR_ERR(new->map[new->num].event);
kfree(new); kfree(new);
return PTR_ERR(new->map[new->num].event); return err;
} }
new->num++; new->num++;
/* Now put new one in place. */ /*
* Now put new one in place: rcu_assign_pointer() is a fancy way of
* doing "lg->eventfds = new", but it uses memory barriers to make
* absolutely sure that the contents of "new" written above is nailed
* down before we actually do the assignment.
*
* We have to think about these kinds of things when we're operating on
* live data without locks.
*/
rcu_assign_pointer(lg->eventfds, new); rcu_assign_pointer(lg->eventfds, new);
/* We're not in a big hurry. Wait until noone's looking at old /*
* version, then delete it. */ * We're not in a big hurry. Wait until noone's looking at old
* version, then free it.
*/
synchronize_rcu(); synchronize_rcu();
kfree(old); kfree(old);
return 0; return 0;
} }
/*L:052
* Receiving notifications from the Guest is usually done by attaching a
* particular LHCALL_NOTIFY value to an event filedescriptor. The eventfd will
* become readable when the Guest does an LHCALL_NOTIFY with that value.
*
* This is really convenient for processing each virtqueue in a separate
* thread.
*/
static int attach_eventfd(struct lguest *lg, const unsigned long __user *input) static int attach_eventfd(struct lguest *lg, const unsigned long __user *input)
{ {
unsigned long addr, fd; unsigned long addr, fd;
...@@ -79,15 +157,22 @@ static int attach_eventfd(struct lguest *lg, const unsigned long __user *input) ...@@ -79,15 +157,22 @@ static int attach_eventfd(struct lguest *lg, const unsigned long __user *input)
if (get_user(fd, input) != 0) if (get_user(fd, input) != 0)
return -EFAULT; return -EFAULT;
/*
* Just make sure two callers don't add eventfds at once. We really
* only need to lock against callers adding to the same Guest, so using
* the Big Lguest Lock is overkill. But this is setup, not a fast path.
*/
mutex_lock(&lguest_lock); mutex_lock(&lguest_lock);
err = add_eventfd(lg, addr, fd); err = add_eventfd(lg, addr, fd);
mutex_unlock(&lguest_lock); mutex_unlock(&lguest_lock);
return 0; return err;
} }
/*L:050 Sending an interrupt is done by writing LHREQ_IRQ and an interrupt /*L:050
* number to /dev/lguest. */ * Sending an interrupt is done by writing LHREQ_IRQ and an interrupt
* number to /dev/lguest.
*/
static int user_send_irq(struct lg_cpu *cpu, const unsigned long __user *input) static int user_send_irq(struct lg_cpu *cpu, const unsigned long __user *input)
{ {
unsigned long irq; unsigned long irq;
...@@ -97,12 +182,18 @@ static int user_send_irq(struct lg_cpu *cpu, const unsigned long __user *input) ...@@ -97,12 +182,18 @@ static int user_send_irq(struct lg_cpu *cpu, const unsigned long __user *input)
if (irq >= LGUEST_IRQS) if (irq >= LGUEST_IRQS)
return -EINVAL; return -EINVAL;
/*
* Next time the Guest runs, the core code will see if it can deliver
* this interrupt.
*/
set_interrupt(cpu, irq); set_interrupt(cpu, irq);
return 0; return 0;
} }
/*L:040 Once our Guest is initialized, the Launcher makes it run by reading /*L:040
* from /dev/lguest. */ * Once our Guest is initialized, the Launcher makes it run by reading
* from /dev/lguest.
*/
static ssize_t read(struct file *file, char __user *user, size_t size,loff_t*o) static ssize_t read(struct file *file, char __user *user, size_t size,loff_t*o)
{ {
struct lguest *lg = file->private_data; struct lguest *lg = file->private_data;
...@@ -138,8 +229,10 @@ static ssize_t read(struct file *file, char __user *user, size_t size,loff_t*o) ...@@ -138,8 +229,10 @@ static ssize_t read(struct file *file, char __user *user, size_t size,loff_t*o)
return len; return len;
} }
/* If we returned from read() last time because the Guest sent I/O, /*
* clear the flag. */ * If we returned from read() last time because the Guest sent I/O,
* clear the flag.
*/
if (cpu->pending_notify) if (cpu->pending_notify)
cpu->pending_notify = 0; cpu->pending_notify = 0;
...@@ -147,8 +240,10 @@ static ssize_t read(struct file *file, char __user *user, size_t size,loff_t*o) ...@@ -147,8 +240,10 @@ static ssize_t read(struct file *file, char __user *user, size_t size,loff_t*o)
return run_guest(cpu, (unsigned long __user *)user); return run_guest(cpu, (unsigned long __user *)user);
} }
/*L:025 This actually initializes a CPU. For the moment, a Guest is only /*L:025
* uniprocessor, so "id" is always 0. */ * This actually initializes a CPU. For the moment, a Guest is only
* uniprocessor, so "id" is always 0.
*/
static int lg_cpu_start(struct lg_cpu *cpu, unsigned id, unsigned long start_ip) static int lg_cpu_start(struct lg_cpu *cpu, unsigned id, unsigned long start_ip)
{ {
/* We have a limited number the number of CPUs in the lguest struct. */ /* We have a limited number the number of CPUs in the lguest struct. */
...@@ -163,8 +258,10 @@ static int lg_cpu_start(struct lg_cpu *cpu, unsigned id, unsigned long start_ip) ...@@ -163,8 +258,10 @@ static int lg_cpu_start(struct lg_cpu *cpu, unsigned id, unsigned long start_ip)
/* Each CPU has a timer it can set. */ /* Each CPU has a timer it can set. */
init_clockdev(cpu); init_clockdev(cpu);
/* We need a complete page for the Guest registers: they are accessible /*
* to the Guest and we can only grant it access to whole pages. */ * We need a complete page for the Guest registers: they are accessible
* to the Guest and we can only grant it access to whole pages.
*/
cpu->regs_page = get_zeroed_page(GFP_KERNEL); cpu->regs_page = get_zeroed_page(GFP_KERNEL);
if (!cpu->regs_page) if (!cpu->regs_page)
return -ENOMEM; return -ENOMEM;
...@@ -172,29 +269,38 @@ static int lg_cpu_start(struct lg_cpu *cpu, unsigned id, unsigned long start_ip) ...@@ -172,29 +269,38 @@ static int lg_cpu_start(struct lg_cpu *cpu, unsigned id, unsigned long start_ip)
/* We actually put the registers at the bottom of the page. */ /* We actually put the registers at the bottom of the page. */
cpu->regs = (void *)cpu->regs_page + PAGE_SIZE - sizeof(*cpu->regs); cpu->regs = (void *)cpu->regs_page + PAGE_SIZE - sizeof(*cpu->regs);
/* Now we initialize the Guest's registers, handing it the start /*
* address. */ * Now we initialize the Guest's registers, handing it the start
* address.
*/
lguest_arch_setup_regs(cpu, start_ip); lguest_arch_setup_regs(cpu, start_ip);
/* We keep a pointer to the Launcher task (ie. current task) for when /*
* other Guests want to wake this one (eg. console input). */ * We keep a pointer to the Launcher task (ie. current task) for when
* other Guests want to wake this one (eg. console input).
*/
cpu->tsk = current; cpu->tsk = current;
/* We need to keep a pointer to the Launcher's memory map, because if /*
* We need to keep a pointer to the Launcher's memory map, because if
* the Launcher dies we need to clean it up. If we don't keep a * the Launcher dies we need to clean it up. If we don't keep a
* reference, it is destroyed before close() is called. */ * reference, it is destroyed before close() is called.
*/
cpu->mm = get_task_mm(cpu->tsk); cpu->mm = get_task_mm(cpu->tsk);
/* We remember which CPU's pages this Guest used last, for optimization /*
* when the same Guest runs on the same CPU twice. */ * We remember which CPU's pages this Guest used last, for optimization
* when the same Guest runs on the same CPU twice.
*/
cpu->last_pages = NULL; cpu->last_pages = NULL;
/* No error == success. */ /* No error == success. */
return 0; return 0;
} }
/*L:020 The initialization write supplies 3 pointer sized (32 or 64 bit) /*L:020
* values (in addition to the LHREQ_INITIALIZE value). These are: * The initialization write supplies 3 pointer sized (32 or 64 bit) values (in
* addition to the LHREQ_INITIALIZE value). These are:
* *
* base: The start of the Guest-physical memory inside the Launcher memory. * base: The start of the Guest-physical memory inside the Launcher memory.
* *
...@@ -206,14 +312,15 @@ static int lg_cpu_start(struct lg_cpu *cpu, unsigned id, unsigned long start_ip) ...@@ -206,14 +312,15 @@ static int lg_cpu_start(struct lg_cpu *cpu, unsigned id, unsigned long start_ip)
*/ */
static int initialize(struct file *file, const unsigned long __user *input) static int initialize(struct file *file, const unsigned long __user *input)
{ {
/* "struct lguest" contains everything we (the Host) know about a /* "struct lguest" contains all we (the Host) know about a Guest. */
* Guest. */
struct lguest *lg; struct lguest *lg;
int err; int err;
unsigned long args[3]; unsigned long args[3];
/* We grab the Big Lguest lock, which protects against multiple /*
* simultaneous initializations. */ * We grab the Big Lguest lock, which protects against multiple
* simultaneous initializations.
*/
mutex_lock(&lguest_lock); mutex_lock(&lguest_lock);
/* You can't initialize twice! Close the device and start again... */ /* You can't initialize twice! Close the device and start again... */
if (file->private_data) { if (file->private_data) {
...@@ -248,8 +355,10 @@ static int initialize(struct file *file, const unsigned long __user *input) ...@@ -248,8 +355,10 @@ static int initialize(struct file *file, const unsigned long __user *input)
if (err) if (err)
goto free_eventfds; goto free_eventfds;
/* Initialize the Guest's shadow page tables, using the toplevel /*
* address the Launcher gave us. This allocates memory, so can fail. */ * Initialize the Guest's shadow page tables, using the toplevel
* address the Launcher gave us. This allocates memory, so can fail.
*/
err = init_guest_pagetable(lg); err = init_guest_pagetable(lg);
if (err) if (err)
goto free_regs; goto free_regs;
...@@ -274,20 +383,24 @@ static int initialize(struct file *file, const unsigned long __user *input) ...@@ -274,20 +383,24 @@ static int initialize(struct file *file, const unsigned long __user *input)
return err; return err;
} }
/*L:010 The first operation the Launcher does must be a write. All writes /*L:010
* The first operation the Launcher does must be a write. All writes
* start with an unsigned long number: for the first write this must be * start with an unsigned long number: for the first write this must be
* LHREQ_INITIALIZE to set up the Guest. After that the Launcher can use * LHREQ_INITIALIZE to set up the Guest. After that the Launcher can use
* writes of other values to send interrupts. * writes of other values to send interrupts or set up receipt of notifications.
* *
* Note that we overload the "offset" in the /dev/lguest file to indicate what * Note that we overload the "offset" in the /dev/lguest file to indicate what
* CPU number we're dealing with. Currently this is always 0, since we only * CPU number we're dealing with. Currently this is always 0 since we only
* support uniprocessor Guests, but you can see the beginnings of SMP support * support uniprocessor Guests, but you can see the beginnings of SMP support
* here. */ * here.
*/
static ssize_t write(struct file *file, const char __user *in, static ssize_t write(struct file *file, const char __user *in,
size_t size, loff_t *off) size_t size, loff_t *off)
{ {
/* Once the Guest is initialized, we hold the "struct lguest" in the /*
* file private data. */ * Once the Guest is initialized, we hold the "struct lguest" in the
* file private data.
*/
struct lguest *lg = file->private_data; struct lguest *lg = file->private_data;
const unsigned long __user *input = (const unsigned long __user *)in; const unsigned long __user *input = (const unsigned long __user *)in;
unsigned long req; unsigned long req;
...@@ -322,13 +435,15 @@ static ssize_t write(struct file *file, const char __user *in, ...@@ -322,13 +435,15 @@ static ssize_t write(struct file *file, const char __user *in,
} }
} }
/*L:060 The final piece of interface code is the close() routine. It reverses /*L:060
* The final piece of interface code is the close() routine. It reverses
* everything done in initialize(). This is usually called because the * everything done in initialize(). This is usually called because the
* Launcher exited. * Launcher exited.
* *
* Note that the close routine returns 0 or a negative error number: it can't * Note that the close routine returns 0 or a negative error number: it can't
* really fail, but it can whine. I blame Sun for this wart, and K&R C for * really fail, but it can whine. I blame Sun for this wart, and K&R C for
* letting them do it. :*/ * letting them do it.
:*/
static int close(struct inode *inode, struct file *file) static int close(struct inode *inode, struct file *file)
{ {
struct lguest *lg = file->private_data; struct lguest *lg = file->private_data;
...@@ -338,8 +453,10 @@ static int close(struct inode *inode, struct file *file) ...@@ -338,8 +453,10 @@ static int close(struct inode *inode, struct file *file)
if (!lg) if (!lg)
return 0; return 0;
/* We need the big lock, to protect from inter-guest I/O and other /*
* Launchers initializing guests. */ * We need the big lock, to protect from inter-guest I/O and other
* Launchers initializing guests.
*/
mutex_lock(&lguest_lock); mutex_lock(&lguest_lock);
/* Free up the shadow page tables for the Guest. */ /* Free up the shadow page tables for the Guest. */
...@@ -350,8 +467,10 @@ static int close(struct inode *inode, struct file *file) ...@@ -350,8 +467,10 @@ static int close(struct inode *inode, struct file *file)
hrtimer_cancel(&lg->cpus[i].hrt); hrtimer_cancel(&lg->cpus[i].hrt);
/* We can free up the register page we allocated. */ /* We can free up the register page we allocated. */
free_page(lg->cpus[i].regs_page); free_page(lg->cpus[i].regs_page);
/* Now all the memory cleanups are done, it's safe to release /*
* the Launcher's memory management structure. */ * Now all the memory cleanups are done, it's safe to release
* the Launcher's memory management structure.
*/
mmput(lg->cpus[i].mm); mmput(lg->cpus[i].mm);
} }
...@@ -360,8 +479,10 @@ static int close(struct inode *inode, struct file *file) ...@@ -360,8 +479,10 @@ static int close(struct inode *inode, struct file *file)
eventfd_ctx_put(lg->eventfds->map[i].event); eventfd_ctx_put(lg->eventfds->map[i].event);
kfree(lg->eventfds); kfree(lg->eventfds);
/* If lg->dead doesn't contain an error code it will be NULL or a /*
* kmalloc()ed string, either of which is ok to hand to kfree(). */ * If lg->dead doesn't contain an error code it will be NULL or a
* kmalloc()ed string, either of which is ok to hand to kfree().
*/
if (!IS_ERR(lg->dead)) if (!IS_ERR(lg->dead))
kfree(lg->dead); kfree(lg->dead);
/* Free the memory allocated to the lguest_struct */ /* Free the memory allocated to the lguest_struct */
...@@ -385,7 +506,8 @@ static int close(struct inode *inode, struct file *file) ...@@ -385,7 +506,8 @@ static int close(struct inode *inode, struct file *file)
* *
* We begin our understanding with the Host kernel interface which the Launcher * We begin our understanding with the Host kernel interface which the Launcher
* uses: reading and writing a character device called /dev/lguest. All the * uses: reading and writing a character device called /dev/lguest. All the
* work happens in the read(), write() and close() routines: */ * work happens in the read(), write() and close() routines:
*/
static struct file_operations lguest_fops = { static struct file_operations lguest_fops = {
.owner = THIS_MODULE, .owner = THIS_MODULE,
.release = close, .release = close,
...@@ -393,8 +515,10 @@ static struct file_operations lguest_fops = { ...@@ -393,8 +515,10 @@ static struct file_operations lguest_fops = {
.read = read, .read = read,
}; };
/* This is a textbook example of a "misc" character device. Populate a "struct /*
* miscdevice" and register it with misc_register(). */ * This is a textbook example of a "misc" character device. Populate a "struct
* miscdevice" and register it with misc_register().
*/
static struct miscdevice lguest_dev = { static struct miscdevice lguest_dev = {
.minor = MISC_DYNAMIC_MINOR, .minor = MISC_DYNAMIC_MINOR,
.name = "lguest", .name = "lguest",
......
此差异已折叠。
/*P:600 The x86 architecture has segments, which involve a table of descriptors /*P:600
* The x86 architecture has segments, which involve a table of descriptors
* which can be used to do funky things with virtual address interpretation. * which can be used to do funky things with virtual address interpretation.
* We originally used to use segments so the Guest couldn't alter the * We originally used to use segments so the Guest couldn't alter the
* Guest<->Host Switcher, and then we had to trim Guest segments, and restore * Guest<->Host Switcher, and then we had to trim Guest segments, and restore
...@@ -8,7 +9,8 @@ ...@@ -8,7 +9,8 @@
* *
* In these modern times, the segment handling code consists of simple sanity * In these modern times, the segment handling code consists of simple sanity
* checks, and the worst you'll experience reading this code is butterfly-rash * checks, and the worst you'll experience reading this code is butterfly-rash
* from frolicking through its parklike serenity. :*/ * from frolicking through its parklike serenity.
:*/
#include "lg.h" #include "lg.h"
/*H:600 /*H:600
...@@ -41,10 +43,12 @@ ...@@ -41,10 +43,12 @@
* begin. * begin.
*/ */
/* There are several entries we don't let the Guest set. The TSS entry is the /*
* There are several entries we don't let the Guest set. The TSS entry is the
* "Task State Segment" which controls all kinds of delicate things. The * "Task State Segment" which controls all kinds of delicate things. The
* LGUEST_CS and LGUEST_DS entries are reserved for the Switcher, and the * LGUEST_CS and LGUEST_DS entries are reserved for the Switcher, and the
* the Guest can't be trusted to deal with double faults. */ * the Guest can't be trusted to deal with double faults.
*/
static bool ignored_gdt(unsigned int num) static bool ignored_gdt(unsigned int num)
{ {
return (num == GDT_ENTRY_TSS return (num == GDT_ENTRY_TSS
...@@ -53,42 +57,52 @@ static bool ignored_gdt(unsigned int num) ...@@ -53,42 +57,52 @@ static bool ignored_gdt(unsigned int num)
|| num == GDT_ENTRY_DOUBLEFAULT_TSS); || num == GDT_ENTRY_DOUBLEFAULT_TSS);
} }
/*H:630 Once the Guest gave us new GDT entries, we fix them up a little. We /*H:630
* Once the Guest gave us new GDT entries, we fix them up a little. We
* don't care if they're invalid: the worst that can happen is a General * don't care if they're invalid: the worst that can happen is a General
* Protection Fault in the Switcher when it restores a Guest segment register * Protection Fault in the Switcher when it restores a Guest segment register
* which tries to use that entry. Then we kill the Guest for causing such a * which tries to use that entry. Then we kill the Guest for causing such a
* mess: the message will be "unhandled trap 256". */ * mess: the message will be "unhandled trap 256".
*/
static void fixup_gdt_table(struct lg_cpu *cpu, unsigned start, unsigned end) static void fixup_gdt_table(struct lg_cpu *cpu, unsigned start, unsigned end)
{ {
unsigned int i; unsigned int i;
for (i = start; i < end; i++) { for (i = start; i < end; i++) {
/* We never copy these ones to real GDT, so we don't care what /*
* they say */ * We never copy these ones to real GDT, so we don't care what
* they say
*/
if (ignored_gdt(i)) if (ignored_gdt(i))
continue; continue;
/* Segment descriptors contain a privilege level: the Guest is /*
* Segment descriptors contain a privilege level: the Guest is
* sometimes careless and leaves this as 0, even though it's * sometimes careless and leaves this as 0, even though it's
* running at privilege level 1. If so, we fix it here. */ * running at privilege level 1. If so, we fix it here.
*/
if ((cpu->arch.gdt[i].b & 0x00006000) == 0) if ((cpu->arch.gdt[i].b & 0x00006000) == 0)
cpu->arch.gdt[i].b |= (GUEST_PL << 13); cpu->arch.gdt[i].b |= (GUEST_PL << 13);
/* Each descriptor has an "accessed" bit. If we don't set it /*
* Each descriptor has an "accessed" bit. If we don't set it
* now, the CPU will try to set it when the Guest first loads * now, the CPU will try to set it when the Guest first loads
* that entry into a segment register. But the GDT isn't * that entry into a segment register. But the GDT isn't
* writable by the Guest, so bad things can happen. */ * writable by the Guest, so bad things can happen.
*/
cpu->arch.gdt[i].b |= 0x00000100; cpu->arch.gdt[i].b |= 0x00000100;
} }
} }
/*H:610 Like the IDT, we never simply use the GDT the Guest gives us. We keep /*H:610
* Like the IDT, we never simply use the GDT the Guest gives us. We keep
* a GDT for each CPU, and copy across the Guest's entries each time we want to * a GDT for each CPU, and copy across the Guest's entries each time we want to
* run the Guest on that CPU. * run the Guest on that CPU.
* *
* This routine is called at boot or modprobe time for each CPU to set up the * This routine is called at boot or modprobe time for each CPU to set up the
* constant GDT entries: the ones which are the same no matter what Guest we're * constant GDT entries: the ones which are the same no matter what Guest we're
* running. */ * running.
*/
void setup_default_gdt_entries(struct lguest_ro_state *state) void setup_default_gdt_entries(struct lguest_ro_state *state)
{ {
struct desc_struct *gdt = state->guest_gdt; struct desc_struct *gdt = state->guest_gdt;
...@@ -98,30 +112,37 @@ void setup_default_gdt_entries(struct lguest_ro_state *state) ...@@ -98,30 +112,37 @@ void setup_default_gdt_entries(struct lguest_ro_state *state)
gdt[GDT_ENTRY_LGUEST_CS] = FULL_EXEC_SEGMENT; gdt[GDT_ENTRY_LGUEST_CS] = FULL_EXEC_SEGMENT;
gdt[GDT_ENTRY_LGUEST_DS] = FULL_SEGMENT; gdt[GDT_ENTRY_LGUEST_DS] = FULL_SEGMENT;
/* The TSS segment refers to the TSS entry for this particular CPU. /*
* The TSS segment refers to the TSS entry for this particular CPU.
* Forgive the magic flags: the 0x8900 means the entry is Present, it's * Forgive the magic flags: the 0x8900 means the entry is Present, it's
* privilege level 0 Available 386 TSS system segment, and the 0x67 * privilege level 0 Available 386 TSS system segment, and the 0x67
* means Saturn is eclipsed by Mercury in the twelfth house. */ * means Saturn is eclipsed by Mercury in the twelfth house.
*/
gdt[GDT_ENTRY_TSS].a = 0x00000067 | (tss << 16); gdt[GDT_ENTRY_TSS].a = 0x00000067 | (tss << 16);
gdt[GDT_ENTRY_TSS].b = 0x00008900 | (tss & 0xFF000000) gdt[GDT_ENTRY_TSS].b = 0x00008900 | (tss & 0xFF000000)
| ((tss >> 16) & 0x000000FF); | ((tss >> 16) & 0x000000FF);
} }
/* This routine sets up the initial Guest GDT for booting. All entries start /*
* as 0 (unusable). */ * This routine sets up the initial Guest GDT for booting. All entries start
* as 0 (unusable).
*/
void setup_guest_gdt(struct lg_cpu *cpu) void setup_guest_gdt(struct lg_cpu *cpu)
{ {
/* Start with full 0-4G segments... */ /*
* Start with full 0-4G segments...except the Guest is allowed to use
* them, so set the privilege level appropriately in the flags.
*/
cpu->arch.gdt[GDT_ENTRY_KERNEL_CS] = FULL_EXEC_SEGMENT; cpu->arch.gdt[GDT_ENTRY_KERNEL_CS] = FULL_EXEC_SEGMENT;
cpu->arch.gdt[GDT_ENTRY_KERNEL_DS] = FULL_SEGMENT; cpu->arch.gdt[GDT_ENTRY_KERNEL_DS] = FULL_SEGMENT;
/* ...except the Guest is allowed to use them, so set the privilege
* level appropriately in the flags. */
cpu->arch.gdt[GDT_ENTRY_KERNEL_CS].b |= (GUEST_PL << 13); cpu->arch.gdt[GDT_ENTRY_KERNEL_CS].b |= (GUEST_PL << 13);
cpu->arch.gdt[GDT_ENTRY_KERNEL_DS].b |= (GUEST_PL << 13); cpu->arch.gdt[GDT_ENTRY_KERNEL_DS].b |= (GUEST_PL << 13);
} }
/*H:650 An optimization of copy_gdt(), for just the three "thead-local storage" /*H:650
* entries. */ * An optimization of copy_gdt(), for just the three "thead-local storage"
* entries.
*/
void copy_gdt_tls(const struct lg_cpu *cpu, struct desc_struct *gdt) void copy_gdt_tls(const struct lg_cpu *cpu, struct desc_struct *gdt)
{ {
unsigned int i; unsigned int i;
...@@ -130,26 +151,34 @@ void copy_gdt_tls(const struct lg_cpu *cpu, struct desc_struct *gdt) ...@@ -130,26 +151,34 @@ void copy_gdt_tls(const struct lg_cpu *cpu, struct desc_struct *gdt)
gdt[i] = cpu->arch.gdt[i]; gdt[i] = cpu->arch.gdt[i];
} }
/*H:640 When the Guest is run on a different CPU, or the GDT entries have /*H:640
* changed, copy_gdt() is called to copy the Guest's GDT entries across to this * When the Guest is run on a different CPU, or the GDT entries have changed,
* CPU's GDT. */ * copy_gdt() is called to copy the Guest's GDT entries across to this CPU's
* GDT.
*/
void copy_gdt(const struct lg_cpu *cpu, struct desc_struct *gdt) void copy_gdt(const struct lg_cpu *cpu, struct desc_struct *gdt)
{ {
unsigned int i; unsigned int i;
/* The default entries from setup_default_gdt_entries() are not /*
* replaced. See ignored_gdt() above. */ * The default entries from setup_default_gdt_entries() are not
* replaced. See ignored_gdt() above.
*/
for (i = 0; i < GDT_ENTRIES; i++) for (i = 0; i < GDT_ENTRIES; i++)
if (!ignored_gdt(i)) if (!ignored_gdt(i))
gdt[i] = cpu->arch.gdt[i]; gdt[i] = cpu->arch.gdt[i];
} }
/*H:620 This is where the Guest asks us to load a new GDT entry /*H:620
* (LHCALL_LOAD_GDT_ENTRY). We tweak the entry and copy it in. */ * This is where the Guest asks us to load a new GDT entry
* (LHCALL_LOAD_GDT_ENTRY). We tweak the entry and copy it in.
*/
void load_guest_gdt_entry(struct lg_cpu *cpu, u32 num, u32 lo, u32 hi) void load_guest_gdt_entry(struct lg_cpu *cpu, u32 num, u32 lo, u32 hi)
{ {
/* We assume the Guest has the same number of GDT entries as the /*
* Host, otherwise we'd have to dynamically allocate the Guest GDT. */ * We assume the Guest has the same number of GDT entries as the
* Host, otherwise we'd have to dynamically allocate the Guest GDT.
*/
if (num >= ARRAY_SIZE(cpu->arch.gdt)) if (num >= ARRAY_SIZE(cpu->arch.gdt))
kill_guest(cpu, "too many gdt entries %i", num); kill_guest(cpu, "too many gdt entries %i", num);
...@@ -157,15 +186,19 @@ void load_guest_gdt_entry(struct lg_cpu *cpu, u32 num, u32 lo, u32 hi) ...@@ -157,15 +186,19 @@ void load_guest_gdt_entry(struct lg_cpu *cpu, u32 num, u32 lo, u32 hi)
cpu->arch.gdt[num].a = lo; cpu->arch.gdt[num].a = lo;
cpu->arch.gdt[num].b = hi; cpu->arch.gdt[num].b = hi;
fixup_gdt_table(cpu, num, num+1); fixup_gdt_table(cpu, num, num+1);
/* Mark that the GDT changed so the core knows it has to copy it again, /*
* even if the Guest is run on the same CPU. */ * Mark that the GDT changed so the core knows it has to copy it again,
* even if the Guest is run on the same CPU.
*/
cpu->changed |= CHANGED_GDT; cpu->changed |= CHANGED_GDT;
} }
/* This is the fast-track version for just changing the three TLS entries. /*
* This is the fast-track version for just changing the three TLS entries.
* Remember that this happens on every context switch, so it's worth * Remember that this happens on every context switch, so it's worth
* optimizing. But wouldn't it be neater to have a single hypercall to cover * optimizing. But wouldn't it be neater to have a single hypercall to cover
* both cases? */ * both cases?
*/
void guest_load_tls(struct lg_cpu *cpu, unsigned long gtls) void guest_load_tls(struct lg_cpu *cpu, unsigned long gtls)
{ {
struct desc_struct *tls = &cpu->arch.gdt[GDT_ENTRY_TLS_MIN]; struct desc_struct *tls = &cpu->arch.gdt[GDT_ENTRY_TLS_MIN];
...@@ -175,7 +208,6 @@ void guest_load_tls(struct lg_cpu *cpu, unsigned long gtls) ...@@ -175,7 +208,6 @@ void guest_load_tls(struct lg_cpu *cpu, unsigned long gtls)
/* Note that just the TLS entries have changed. */ /* Note that just the TLS entries have changed. */
cpu->changed |= CHANGED_GDT_TLS; cpu->changed |= CHANGED_GDT_TLS;
} }
/*:*/
/*H:660 /*H:660
* With this, we have finished the Host. * With this, we have finished the Host.
......
此差异已折叠。
/*P:900 This is the Switcher: code which sits at 0xFFC00000 astride both the /*P:900
* Host and Guest to do the low-level Guest<->Host switch. It is as simple as * This is the Switcher: code which sits at 0xFFC00000 (or 0xFFE00000) astride
* it can be made, but it's naturally very specific to x86. * both the Host and Guest to do the low-level Guest<->Host switch. It is as
* simple as it can be made, but it's naturally very specific to x86.
* *
* You have now completed Preparation. If this has whet your appetite; if you * You have now completed Preparation. If this has whet your appetite; if you
* are feeling invigorated and refreshed then the next, more challenging stage * are feeling invigorated and refreshed then the next, more challenging stage
* can be found in "make Guest". :*/ * can be found in "make Guest".
:*/
/*M:012 Lguest is meant to be simple: my rule of thumb is that 1% more LOC must /*M:012
* Lguest is meant to be simple: my rule of thumb is that 1% more LOC must
* gain at least 1% more performance. Since neither LOC nor performance can be * gain at least 1% more performance. Since neither LOC nor performance can be
* measured beforehand, it generally means implementing a feature then deciding * measured beforehand, it generally means implementing a feature then deciding
* if it's worth it. And once it's implemented, who can say no? * if it's worth it. And once it's implemented, who can say no?
...@@ -31,11 +34,14 @@ ...@@ -31,11 +34,14 @@
* Host (which is actually really easy). * Host (which is actually really easy).
* *
* Two questions remain. Would the performance gain outweigh the complexity? * Two questions remain. Would the performance gain outweigh the complexity?
* And who would write the verse documenting it? :*/ * And who would write the verse documenting it?
:*/
/*M:011 Lguest64 handles NMI. This gave me NMI envy (until I looked at their /*M:011
* Lguest64 handles NMI. This gave me NMI envy (until I looked at their
* code). It's worth doing though, since it would let us use oprofile in the * code). It's worth doing though, since it would let us use oprofile in the
* Host when a Guest is running. :*/ * Host when a Guest is running.
:*/
/*S:100 /*S:100
* Welcome to the Switcher itself! * Welcome to the Switcher itself!
......
此差异已折叠。
/* Things the lguest guest needs to know. Note: like all lguest interfaces, /*
* this is subject to wild and random change between versions. */ * Things the lguest guest needs to know. Note: like all lguest interfaces,
* this is subject to wild and random change between versions.
*/
#ifndef _LINUX_LGUEST_H #ifndef _LINUX_LGUEST_H
#define _LINUX_LGUEST_H #define _LINUX_LGUEST_H
...@@ -11,32 +13,41 @@ ...@@ -11,32 +13,41 @@
#define LG_CLOCK_MIN_DELTA 100UL #define LG_CLOCK_MIN_DELTA 100UL
#define LG_CLOCK_MAX_DELTA ULONG_MAX #define LG_CLOCK_MAX_DELTA ULONG_MAX
/*G:031 The second method of communicating with the Host is to via "struct /*G:031
* The second method of communicating with the Host is to via "struct
* lguest_data". Once the Guest's initialization hypercall tells the Host where * lguest_data". Once the Guest's initialization hypercall tells the Host where
* this is, the Guest and Host both publish information in it. :*/ * this is, the Guest and Host both publish information in it.
struct lguest_data :*/
{ struct lguest_data {
/* 512 == enabled (same as eflags in normal hardware). The Guest /*
* changes interrupts so often that a hypercall is too slow. */ * 512 == enabled (same as eflags in normal hardware). The Guest
* changes interrupts so often that a hypercall is too slow.
*/
unsigned int irq_enabled; unsigned int irq_enabled;
/* Fine-grained interrupt disabling by the Guest */ /* Fine-grained interrupt disabling by the Guest */
DECLARE_BITMAP(blocked_interrupts, LGUEST_IRQS); DECLARE_BITMAP(blocked_interrupts, LGUEST_IRQS);
/* The Host writes the virtual address of the last page fault here, /*
* The Host writes the virtual address of the last page fault here,
* which saves the Guest a hypercall. CR2 is the native register where * which saves the Guest a hypercall. CR2 is the native register where
* this address would normally be found. */ * this address would normally be found.
*/
unsigned long cr2; unsigned long cr2;
/* Wallclock time set by the Host. */ /* Wallclock time set by the Host. */
struct timespec time; struct timespec time;
/* Interrupt pending set by the Host. The Guest should do a hypercall /*
* if it re-enables interrupts and sees this set (to X86_EFLAGS_IF). */ * Interrupt pending set by the Host. The Guest should do a hypercall
* if it re-enables interrupts and sees this set (to X86_EFLAGS_IF).
*/
int irq_pending; int irq_pending;
/* Async hypercall ring. Instead of directly making hypercalls, we can /*
* Async hypercall ring. Instead of directly making hypercalls, we can
* place them in here for processing the next time the Host wants. * place them in here for processing the next time the Host wants.
* This batching can be quite efficient. */ * This batching can be quite efficient.
*/
/* 0xFF == done (set by Host), 0 == pending (set by Guest). */ /* 0xFF == done (set by Host), 0 == pending (set by Guest). */
u8 hcall_status[LHCALL_RING_SIZE]; u8 hcall_status[LHCALL_RING_SIZE];
......
...@@ -29,8 +29,10 @@ struct lguest_device_desc { ...@@ -29,8 +29,10 @@ struct lguest_device_desc {
__u8 type; __u8 type;
/* The number of virtqueues (first in config array) */ /* The number of virtqueues (first in config array) */
__u8 num_vq; __u8 num_vq;
/* The number of bytes of feature bits. Multiply by 2: one for host /*
* features and one for Guest acknowledgements. */ * The number of bytes of feature bits. Multiply by 2: one for host
* features and one for Guest acknowledgements.
*/
__u8 feature_len; __u8 feature_len;
/* The number of bytes of the config array after virtqueues. */ /* The number of bytes of the config array after virtqueues. */
__u8 config_len; __u8 config_len;
...@@ -39,8 +41,10 @@ struct lguest_device_desc { ...@@ -39,8 +41,10 @@ struct lguest_device_desc {
__u8 config[0]; __u8 config[0];
}; };
/*D:135 This is how we expect the device configuration field for a virtqueue /*D:135
* to be laid out in config space. */ * This is how we expect the device configuration field for a virtqueue
* to be laid out in config space.
*/
struct lguest_vqconfig { struct lguest_vqconfig {
/* The number of entries in the virtio_ring */ /* The number of entries in the virtio_ring */
__u16 num; __u16 num;
...@@ -61,7 +65,9 @@ enum lguest_req ...@@ -61,7 +65,9 @@ enum lguest_req
LHREQ_EVENTFD, /* + address, fd. */ LHREQ_EVENTFD, /* + address, fd. */
}; };
/* The alignment to use between consumer and producer parts of vring. /*
* x86 pagesize for historical reasons. */ * The alignment to use between consumer and producer parts of vring.
* x86 pagesize for historical reasons.
*/
#define LGUEST_VRING_ALIGN 4096 #define LGUEST_VRING_ALIGN 4096
#endif /* _LINUX_LGUEST_LAUNCHER */ #endif /* _LINUX_LGUEST_LAUNCHER */
此差异已折叠。
...@@ -79,8 +79,7 @@ ...@@ -79,8 +79,7 @@
* the dev->feature bits if it wants. * the dev->feature bits if it wants.
*/ */
typedef void vq_callback_t(struct virtqueue *); typedef void vq_callback_t(struct virtqueue *);
struct virtio_config_ops struct virtio_config_ops {
{
void (*get)(struct virtio_device *vdev, unsigned offset, void (*get)(struct virtio_device *vdev, unsigned offset,
void *buf, unsigned len); void *buf, unsigned len);
void (*set)(struct virtio_device *vdev, unsigned offset, void (*set)(struct virtio_device *vdev, unsigned offset,
......
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册