/*P:200 This contains all the /dev/lguest code, whereby the userspace launcher1* controls and communicates with the Guest. For example, the first write will2* tell us the Guest's memory layout and entry point. A read will run the3* Guest until something happens, such as a signal or the Guest doing a NOTIFY4* out to the Launcher.5:*/6#include <linux/uaccess.h>7#include <linux/miscdevice.h>8#include <linux/fs.h>9#include <linux/sched.h>10#include <linux/eventfd.h>11#include <linux/file.h>12#include <linux/slab.h>13#include "lg.h"1415/*L:05616* Before we move on, let's jump ahead and look at what the kernel does when17* it needs to look up the eventfds. That will complete our picture of how we18* use RCU.19*20* The notification value is in cpu->pending_notify: we return true if it went21* to an eventfd.22*/23bool send_notify_to_eventfd(struct lg_cpu *cpu)24{25unsigned int i;26struct lg_eventfd_map *map;2728/*29* This "rcu_read_lock()" helps track when someone is still looking at30* the (RCU-using) eventfds array. It's not actually a lock at all;31* indeed it's a noop in many configurations. (You didn't expect me to32* explain all the RCU secrets here, did you?)33*/34rcu_read_lock();35/*36* rcu_dereference is the counter-side of rcu_assign_pointer(); it37* makes sure we don't access the memory pointed to by38* cpu->lg->eventfds before cpu->lg->eventfds is set. Sounds crazy,39* but Alpha allows this! Paul McKenney points out that a really40* aggressive compiler could have the same effect:41* http://lists.ozlabs.org/pipermail/lguest/2009-July/001560.html42*43* So play safe, use rcu_dereference to get the rcu-protected pointer:44*/45map = rcu_dereference(cpu->lg->eventfds);46/*47* Simple array search: even if they add an eventfd while we do this,48* we'll continue to use the old array and just won't see the new one.49*/50for (i = 0; i < map->num; i++) {51if (map->map[i].addr == cpu->pending_notify) {52eventfd_signal(map->map[i].event, 1);53cpu->pending_notify = 0;54break;55}56}57/* We're done with the rcu-protected variable cpu->lg->eventfds. */58rcu_read_unlock();5960/* If we cleared the notification, it's because we found a match. */61return cpu->pending_notify == 0;62}6364/*L:05565* One of the more tricksy tricks in the Linux Kernel is a technique called66* Read Copy Update. Since one point of lguest is to teach lguest journeyers67* about kernel coding, I use it here. (In case you're curious, other purposes68* include learning about virtualization and instilling a deep appreciation for69* simplicity and puppies).70*71* We keep a simple array which maps LHCALL_NOTIFY values to eventfds, but we72* add new eventfds without ever blocking readers from accessing the array.73* The current Launcher only does this during boot, so that never happens. But74* Read Copy Update is cool, and adding a lock risks damaging even more puppies75* than this code does.76*77* We allocate a brand new one-larger array, copy the old one and add our new78* element. Then we make the lg eventfd pointer point to the new array.79* That's the easy part: now we need to free the old one, but we need to make80* sure no slow CPU somewhere is still looking at it. That's what81* synchronize_rcu does for us: waits until every CPU has indicated that it has82* moved on to know it's no longer using the old one.83*84* If that's unclear, see http://en.wikipedia.org/wiki/Read-copy-update.85*/86static int add_eventfd(struct lguest *lg, unsigned long addr, int fd)87{88struct lg_eventfd_map *new, *old = lg->eventfds;8990/*91* We don't allow notifications on value 0 anyway (pending_notify of92* 0 means "nothing pending").93*/94if (!addr)95return -EINVAL;9697/*98* Replace the old array with the new one, carefully: others can99* be accessing it at the same time.100*/101new = kmalloc(sizeof(*new) + sizeof(new->map[0]) * (old->num + 1),102GFP_KERNEL);103if (!new)104return -ENOMEM;105106/* First make identical copy. */107memcpy(new->map, old->map, sizeof(old->map[0]) * old->num);108new->num = old->num;109110/* Now append new entry. */111new->map[new->num].addr = addr;112new->map[new->num].event = eventfd_ctx_fdget(fd);113if (IS_ERR(new->map[new->num].event)) {114int err = PTR_ERR(new->map[new->num].event);115kfree(new);116return err;117}118new->num++;119120/*121* Now put new one in place: rcu_assign_pointer() is a fancy way of122* doing "lg->eventfds = new", but it uses memory barriers to make123* absolutely sure that the contents of "new" written above is nailed124* down before we actually do the assignment.125*126* We have to think about these kinds of things when we're operating on127* live data without locks.128*/129rcu_assign_pointer(lg->eventfds, new);130131/*132* We're not in a big hurry. Wait until no one's looking at old133* version, then free it.134*/135synchronize_rcu();136kfree(old);137138return 0;139}140141/*L:052142* Receiving notifications from the Guest is usually done by attaching a143* particular LHCALL_NOTIFY value to an event filedescriptor. The eventfd will144* become readable when the Guest does an LHCALL_NOTIFY with that value.145*146* This is really convenient for processing each virtqueue in a separate147* thread.148*/149static int attach_eventfd(struct lguest *lg, const unsigned long __user *input)150{151unsigned long addr, fd;152int err;153154if (get_user(addr, input) != 0)155return -EFAULT;156input++;157if (get_user(fd, input) != 0)158return -EFAULT;159160/*161* Just make sure two callers don't add eventfds at once. We really162* only need to lock against callers adding to the same Guest, so using163* the Big Lguest Lock is overkill. But this is setup, not a fast path.164*/165mutex_lock(&lguest_lock);166err = add_eventfd(lg, addr, fd);167mutex_unlock(&lguest_lock);168169return err;170}171172/*L:050173* Sending an interrupt is done by writing LHREQ_IRQ and an interrupt174* number to /dev/lguest.175*/176static int user_send_irq(struct lg_cpu *cpu, const unsigned long __user *input)177{178unsigned long irq;179180if (get_user(irq, input) != 0)181return -EFAULT;182if (irq >= LGUEST_IRQS)183return -EINVAL;184185/*186* Next time the Guest runs, the core code will see if it can deliver187* this interrupt.188*/189set_interrupt(cpu, irq);190return 0;191}192193/*L:040194* Once our Guest is initialized, the Launcher makes it run by reading195* from /dev/lguest.196*/197static ssize_t read(struct file *file, char __user *user, size_t size,loff_t*o)198{199struct lguest *lg = file->private_data;200struct lg_cpu *cpu;201unsigned int cpu_id = *o;202203/* You must write LHREQ_INITIALIZE first! */204if (!lg)205return -EINVAL;206207/* Watch out for arbitrary vcpu indexes! */208if (cpu_id >= lg->nr_cpus)209return -EINVAL;210211cpu = &lg->cpus[cpu_id];212213/* If you're not the task which owns the Guest, go away. */214if (current != cpu->tsk)215return -EPERM;216217/* If the Guest is already dead, we indicate why */218if (lg->dead) {219size_t len;220221/* lg->dead either contains an error code, or a string. */222if (IS_ERR(lg->dead))223return PTR_ERR(lg->dead);224225/* We can only return as much as the buffer they read with. */226len = min(size, strlen(lg->dead)+1);227if (copy_to_user(user, lg->dead, len) != 0)228return -EFAULT;229return len;230}231232/*233* If we returned from read() last time because the Guest sent I/O,234* clear the flag.235*/236if (cpu->pending_notify)237cpu->pending_notify = 0;238239/* Run the Guest until something interesting happens. */240return run_guest(cpu, (unsigned long __user *)user);241}242243/*L:025244* This actually initializes a CPU. For the moment, a Guest is only245* uniprocessor, so "id" is always 0.246*/247static int lg_cpu_start(struct lg_cpu *cpu, unsigned id, unsigned long start_ip)248{249/* We have a limited number the number of CPUs in the lguest struct. */250if (id >= ARRAY_SIZE(cpu->lg->cpus))251return -EINVAL;252253/* Set up this CPU's id, and pointer back to the lguest struct. */254cpu->id = id;255cpu->lg = container_of((cpu - id), struct lguest, cpus[0]);256cpu->lg->nr_cpus++;257258/* Each CPU has a timer it can set. */259init_clockdev(cpu);260261/*262* We need a complete page for the Guest registers: they are accessible263* to the Guest and we can only grant it access to whole pages.264*/265cpu->regs_page = get_zeroed_page(GFP_KERNEL);266if (!cpu->regs_page)267return -ENOMEM;268269/* We actually put the registers at the bottom of the page. */270cpu->regs = (void *)cpu->regs_page + PAGE_SIZE - sizeof(*cpu->regs);271272/*273* Now we initialize the Guest's registers, handing it the start274* address.275*/276lguest_arch_setup_regs(cpu, start_ip);277278/*279* We keep a pointer to the Launcher task (ie. current task) for when280* other Guests want to wake this one (eg. console input).281*/282cpu->tsk = current;283284/*285* We need to keep a pointer to the Launcher's memory map, because if286* the Launcher dies we need to clean it up. If we don't keep a287* reference, it is destroyed before close() is called.288*/289cpu->mm = get_task_mm(cpu->tsk);290291/*292* We remember which CPU's pages this Guest used last, for optimization293* when the same Guest runs on the same CPU twice.294*/295cpu->last_pages = NULL;296297/* No error == success. */298return 0;299}300301/*L:020302* The initialization write supplies 3 pointer sized (32 or 64 bit) values (in303* addition to the LHREQ_INITIALIZE value). These are:304*305* base: The start of the Guest-physical memory inside the Launcher memory.306*307* pfnlimit: The highest (Guest-physical) page number the Guest should be308* allowed to access. The Guest memory lives inside the Launcher, so it sets309* this to ensure the Guest can only reach its own memory.310*311* start: The first instruction to execute ("eip" in x86-speak).312*/313static int initialize(struct file *file, const unsigned long __user *input)314{315/* "struct lguest" contains all we (the Host) know about a Guest. */316struct lguest *lg;317int err;318unsigned long args[3];319320/*321* We grab the Big Lguest lock, which protects against multiple322* simultaneous initializations.323*/324mutex_lock(&lguest_lock);325/* You can't initialize twice! Close the device and start again... */326if (file->private_data) {327err = -EBUSY;328goto unlock;329}330331if (copy_from_user(args, input, sizeof(args)) != 0) {332err = -EFAULT;333goto unlock;334}335336lg = kzalloc(sizeof(*lg), GFP_KERNEL);337if (!lg) {338err = -ENOMEM;339goto unlock;340}341342lg->eventfds = kmalloc(sizeof(*lg->eventfds), GFP_KERNEL);343if (!lg->eventfds) {344err = -ENOMEM;345goto free_lg;346}347lg->eventfds->num = 0;348349/* Populate the easy fields of our "struct lguest" */350lg->mem_base = (void __user *)args[0];351lg->pfn_limit = args[1];352353/* This is the first cpu (cpu 0) and it will start booting at args[2] */354err = lg_cpu_start(&lg->cpus[0], 0, args[2]);355if (err)356goto free_eventfds;357358/*359* Initialize the Guest's shadow page tables, using the toplevel360* address the Launcher gave us. This allocates memory, so can fail.361*/362err = init_guest_pagetable(lg);363if (err)364goto free_regs;365366/* We keep our "struct lguest" in the file's private_data. */367file->private_data = lg;368369mutex_unlock(&lguest_lock);370371/* And because this is a write() call, we return the length used. */372return sizeof(args);373374free_regs:375/* FIXME: This should be in free_vcpu */376free_page(lg->cpus[0].regs_page);377free_eventfds:378kfree(lg->eventfds);379free_lg:380kfree(lg);381unlock:382mutex_unlock(&lguest_lock);383return err;384}385386/*L:010387* The first operation the Launcher does must be a write. All writes388* start with an unsigned long number: for the first write this must be389* LHREQ_INITIALIZE to set up the Guest. After that the Launcher can use390* writes of other values to send interrupts or set up receipt of notifications.391*392* Note that we overload the "offset" in the /dev/lguest file to indicate what393* CPU number we're dealing with. Currently this is always 0 since we only394* support uniprocessor Guests, but you can see the beginnings of SMP support395* here.396*/397static ssize_t write(struct file *file, const char __user *in,398size_t size, loff_t *off)399{400/*401* Once the Guest is initialized, we hold the "struct lguest" in the402* file private data.403*/404struct lguest *lg = file->private_data;405const unsigned long __user *input = (const unsigned long __user *)in;406unsigned long req;407struct lg_cpu *uninitialized_var(cpu);408unsigned int cpu_id = *off;409410/* The first value tells us what this request is. */411if (get_user(req, input) != 0)412return -EFAULT;413input++;414415/* If you haven't initialized, you must do that first. */416if (req != LHREQ_INITIALIZE) {417if (!lg || (cpu_id >= lg->nr_cpus))418return -EINVAL;419cpu = &lg->cpus[cpu_id];420421/* Once the Guest is dead, you can only read() why it died. */422if (lg->dead)423return -ENOENT;424}425426switch (req) {427case LHREQ_INITIALIZE:428return initialize(file, input);429case LHREQ_IRQ:430return user_send_irq(cpu, input);431case LHREQ_EVENTFD:432return attach_eventfd(lg, input);433default:434return -EINVAL;435}436}437438/*L:060439* The final piece of interface code is the close() routine. It reverses440* everything done in initialize(). This is usually called because the441* Launcher exited.442*443* Note that the close routine returns 0 or a negative error number: it can't444* really fail, but it can whine. I blame Sun for this wart, and K&R C for445* letting them do it.446:*/447static int close(struct inode *inode, struct file *file)448{449struct lguest *lg = file->private_data;450unsigned int i;451452/* If we never successfully initialized, there's nothing to clean up */453if (!lg)454return 0;455456/*457* We need the big lock, to protect from inter-guest I/O and other458* Launchers initializing guests.459*/460mutex_lock(&lguest_lock);461462/* Free up the shadow page tables for the Guest. */463free_guest_pagetable(lg);464465for (i = 0; i < lg->nr_cpus; i++) {466/* Cancels the hrtimer set via LHCALL_SET_CLOCKEVENT. */467hrtimer_cancel(&lg->cpus[i].hrt);468/* We can free up the register page we allocated. */469free_page(lg->cpus[i].regs_page);470/*471* Now all the memory cleanups are done, it's safe to release472* the Launcher's memory management structure.473*/474mmput(lg->cpus[i].mm);475}476477/* Release any eventfds they registered. */478for (i = 0; i < lg->eventfds->num; i++)479eventfd_ctx_put(lg->eventfds->map[i].event);480kfree(lg->eventfds);481482/*483* If lg->dead doesn't contain an error code it will be NULL or a484* kmalloc()ed string, either of which is ok to hand to kfree().485*/486if (!IS_ERR(lg->dead))487kfree(lg->dead);488/* Free the memory allocated to the lguest_struct */489kfree(lg);490/* Release lock and exit. */491mutex_unlock(&lguest_lock);492493return 0;494}495496/*L:000497* Welcome to our journey through the Launcher!498*499* The Launcher is the Host userspace program which sets up, runs and services500* the Guest. In fact, many comments in the Drivers which refer to "the Host"501* doing things are inaccurate: the Launcher does all the device handling for502* the Guest, but the Guest can't know that.503*504* Just to confuse you: to the Host kernel, the Launcher *is* the Guest and we505* shall see more of that later.506*507* We begin our understanding with the Host kernel interface which the Launcher508* uses: reading and writing a character device called /dev/lguest. All the509* work happens in the read(), write() and close() routines:510*/511static const struct file_operations lguest_fops = {512.owner = THIS_MODULE,513.release = close,514.write = write,515.read = read,516.llseek = default_llseek,517};518519/*520* This is a textbook example of a "misc" character device. Populate a "struct521* miscdevice" and register it with misc_register().522*/523static struct miscdevice lguest_dev = {524.minor = MISC_DYNAMIC_MINOR,525.name = "lguest",526.fops = &lguest_fops,527};528529int __init lguest_device_init(void)530{531return misc_register(&lguest_dev);532}533534void __exit lguest_device_remove(void)535{536misc_deregister(&lguest_dev);537}538539540