[go: nahoru, domu]

lguest_user.c revision df60aeef4f4fe0645d9a195a7689005520422de5
1/*P:200 This contains all the /dev/lguest code, whereby the userspace launcher
2 * controls and communicates with the Guest.  For example, the first write will
3 * tell us the Guest's memory layout, pagetable, entry point and kernel address
4 * offset.  A read will run the Guest until something happens, such as a signal
5 * or the Guest doing a NOTIFY out to the Launcher. :*/
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 "lg.h"
13
14/*L:055 When something happens, the Waker process needs a way to stop the
15 * kernel running the Guest and return to the Launcher.  So the Waker writes
16 * LHREQ_BREAK and the value "1" to /dev/lguest to do this.  Once the Launcher
17 * has done whatever needs attention, it writes LHREQ_BREAK and "0" to release
18 * the Waker. */
19static int break_guest_out(struct lg_cpu *cpu, const unsigned long __user*input)
20{
21	unsigned long on;
22
23	/* Fetch whether they're turning break on or off. */
24	if (get_user(on, input) != 0)
25		return -EFAULT;
26
27	if (on) {
28		cpu->break_out = 1;
29		if (!wake_up_process(cpu->tsk))
30			kick_process(cpu->tsk);
31		/* Wait for them to reset it */
32		return wait_event_interruptible(cpu->break_wq, !cpu->break_out);
33	} else {
34		cpu->break_out = 0;
35		wake_up(&cpu->break_wq);
36		return 0;
37	}
38}
39
40bool send_notify_to_eventfd(struct lg_cpu *cpu)
41{
42	unsigned int i;
43	struct lg_eventfd_map *map;
44
45	/* lg->eventfds is RCU-protected */
46	rcu_read_lock();
47	map = rcu_dereference(cpu->lg->eventfds);
48	for (i = 0; i < map->num; i++) {
49		if (map->map[i].addr == cpu->pending_notify) {
50			eventfd_signal(map->map[i].event, 1);
51			cpu->pending_notify = 0;
52			break;
53		}
54	}
55	rcu_read_unlock();
56	return cpu->pending_notify == 0;
57}
58
59static int add_eventfd(struct lguest *lg, unsigned long addr, int fd)
60{
61	struct lg_eventfd_map *new, *old = lg->eventfds;
62
63	if (!addr)
64		return -EINVAL;
65
66	/* Replace the old array with the new one, carefully: others can
67	 * be accessing it at the same time */
68	new = kmalloc(sizeof(*new) + sizeof(new->map[0]) * (old->num + 1),
69		      GFP_KERNEL);
70	if (!new)
71		return -ENOMEM;
72
73	/* First make identical copy. */
74	memcpy(new->map, old->map, sizeof(old->map[0]) * old->num);
75	new->num = old->num;
76
77	/* Now append new entry. */
78	new->map[new->num].addr = addr;
79	new->map[new->num].event = eventfd_fget(fd);
80	if (IS_ERR(new->map[new->num].event)) {
81		kfree(new);
82		return PTR_ERR(new->map[new->num].event);
83	}
84	new->num++;
85
86	/* Now put new one in place. */
87	rcu_assign_pointer(lg->eventfds, new);
88
89	/* We're not in a big hurry.  Wait until noone's looking at old
90	 * version, then delete it. */
91	synchronize_rcu();
92	kfree(old);
93
94	return 0;
95}
96
97static int attach_eventfd(struct lguest *lg, const unsigned long __user *input)
98{
99	unsigned long addr, fd;
100	int err;
101
102	if (get_user(addr, input) != 0)
103		return -EFAULT;
104	input++;
105	if (get_user(fd, input) != 0)
106		return -EFAULT;
107
108	mutex_lock(&lguest_lock);
109	err = add_eventfd(lg, addr, fd);
110	mutex_unlock(&lguest_lock);
111
112	return 0;
113}
114
115/*L:050 Sending an interrupt is done by writing LHREQ_IRQ and an interrupt
116 * number to /dev/lguest. */
117static int user_send_irq(struct lg_cpu *cpu, const unsigned long __user *input)
118{
119	unsigned long irq;
120
121	if (get_user(irq, input) != 0)
122		return -EFAULT;
123	if (irq >= LGUEST_IRQS)
124		return -EINVAL;
125
126	set_interrupt(cpu, irq);
127	return 0;
128}
129
130/*L:040 Once our Guest is initialized, the Launcher makes it run by reading
131 * from /dev/lguest. */
132static ssize_t read(struct file *file, char __user *user, size_t size,loff_t*o)
133{
134	struct lguest *lg = file->private_data;
135	struct lg_cpu *cpu;
136	unsigned int cpu_id = *o;
137
138	/* You must write LHREQ_INITIALIZE first! */
139	if (!lg)
140		return -EINVAL;
141
142	/* Watch out for arbitrary vcpu indexes! */
143	if (cpu_id >= lg->nr_cpus)
144		return -EINVAL;
145
146	cpu = &lg->cpus[cpu_id];
147
148	/* If you're not the task which owns the Guest, go away. */
149	if (current != cpu->tsk)
150		return -EPERM;
151
152	/* If the Guest is already dead, we indicate why */
153	if (lg->dead) {
154		size_t len;
155
156		/* lg->dead either contains an error code, or a string. */
157		if (IS_ERR(lg->dead))
158			return PTR_ERR(lg->dead);
159
160		/* We can only return as much as the buffer they read with. */
161		len = min(size, strlen(lg->dead)+1);
162		if (copy_to_user(user, lg->dead, len) != 0)
163			return -EFAULT;
164		return len;
165	}
166
167	/* If we returned from read() last time because the Guest sent I/O,
168	 * clear the flag. */
169	if (cpu->pending_notify)
170		cpu->pending_notify = 0;
171
172	/* Run the Guest until something interesting happens. */
173	return run_guest(cpu, (unsigned long __user *)user);
174}
175
176/*L:025 This actually initializes a CPU.  For the moment, a Guest is only
177 * uniprocessor, so "id" is always 0. */
178static int lg_cpu_start(struct lg_cpu *cpu, unsigned id, unsigned long start_ip)
179{
180	/* We have a limited number the number of CPUs in the lguest struct. */
181	if (id >= ARRAY_SIZE(cpu->lg->cpus))
182		return -EINVAL;
183
184	/* Set up this CPU's id, and pointer back to the lguest struct. */
185	cpu->id = id;
186	cpu->lg = container_of((cpu - id), struct lguest, cpus[0]);
187	cpu->lg->nr_cpus++;
188
189	/* Each CPU has a timer it can set. */
190	init_clockdev(cpu);
191
192	/* We need a complete page for the Guest registers: they are accessible
193	 * to the Guest and we can only grant it access to whole pages. */
194	cpu->regs_page = get_zeroed_page(GFP_KERNEL);
195	if (!cpu->regs_page)
196		return -ENOMEM;
197
198	/* We actually put the registers at the bottom of the page. */
199	cpu->regs = (void *)cpu->regs_page + PAGE_SIZE - sizeof(*cpu->regs);
200
201	/* Now we initialize the Guest's registers, handing it the start
202	 * address. */
203	lguest_arch_setup_regs(cpu, start_ip);
204
205	/* Initialize the queue for the Waker to wait on */
206	init_waitqueue_head(&cpu->break_wq);
207
208	/* We keep a pointer to the Launcher task (ie. current task) for when
209	 * other Guests want to wake this one (eg. console input). */
210	cpu->tsk = current;
211
212	/* We need to keep a pointer to the Launcher's memory map, because if
213	 * the Launcher dies we need to clean it up.  If we don't keep a
214	 * reference, it is destroyed before close() is called. */
215	cpu->mm = get_task_mm(cpu->tsk);
216
217	/* We remember which CPU's pages this Guest used last, for optimization
218	 * when the same Guest runs on the same CPU twice. */
219	cpu->last_pages = NULL;
220
221	/* No error == success. */
222	return 0;
223}
224
225/*L:020 The initialization write supplies 3 pointer sized (32 or 64 bit)
226 * values (in addition to the LHREQ_INITIALIZE value).  These are:
227 *
228 * base: The start of the Guest-physical memory inside the Launcher memory.
229 *
230 * pfnlimit: The highest (Guest-physical) page number the Guest should be
231 * allowed to access.  The Guest memory lives inside the Launcher, so it sets
232 * this to ensure the Guest can only reach its own memory.
233 *
234 * start: The first instruction to execute ("eip" in x86-speak).
235 */
236static int initialize(struct file *file, const unsigned long __user *input)
237{
238	/* "struct lguest" contains everything we (the Host) know about a
239	 * Guest. */
240	struct lguest *lg;
241	int err;
242	unsigned long args[3];
243
244	/* We grab the Big Lguest lock, which protects against multiple
245	 * simultaneous initializations. */
246	mutex_lock(&lguest_lock);
247	/* You can't initialize twice!  Close the device and start again... */
248	if (file->private_data) {
249		err = -EBUSY;
250		goto unlock;
251	}
252
253	if (copy_from_user(args, input, sizeof(args)) != 0) {
254		err = -EFAULT;
255		goto unlock;
256	}
257
258	lg = kzalloc(sizeof(*lg), GFP_KERNEL);
259	if (!lg) {
260		err = -ENOMEM;
261		goto unlock;
262	}
263
264	lg->eventfds = kmalloc(sizeof(*lg->eventfds), GFP_KERNEL);
265	if (!lg->eventfds) {
266		err = -ENOMEM;
267		goto free_lg;
268	}
269	lg->eventfds->num = 0;
270
271	/* Populate the easy fields of our "struct lguest" */
272	lg->mem_base = (void __user *)args[0];
273	lg->pfn_limit = args[1];
274
275	/* This is the first cpu (cpu 0) and it will start booting at args[2] */
276	err = lg_cpu_start(&lg->cpus[0], 0, args[2]);
277	if (err)
278		goto free_eventfds;
279
280	/* Initialize the Guest's shadow page tables, using the toplevel
281	 * address the Launcher gave us.  This allocates memory, so can fail. */
282	err = init_guest_pagetable(lg);
283	if (err)
284		goto free_regs;
285
286	/* We keep our "struct lguest" in the file's private_data. */
287	file->private_data = lg;
288
289	mutex_unlock(&lguest_lock);
290
291	/* And because this is a write() call, we return the length used. */
292	return sizeof(args);
293
294free_regs:
295	/* FIXME: This should be in free_vcpu */
296	free_page(lg->cpus[0].regs_page);
297free_eventfds:
298	kfree(lg->eventfds);
299free_lg:
300	kfree(lg);
301unlock:
302	mutex_unlock(&lguest_lock);
303	return err;
304}
305
306/*L:010 The first operation the Launcher does must be a write.  All writes
307 * start with an unsigned long number: for the first write this must be
308 * LHREQ_INITIALIZE to set up the Guest.  After that the Launcher can use
309 * writes of other values to send interrupts.
310 *
311 * Note that we overload the "offset" in the /dev/lguest file to indicate what
312 * CPU number we're dealing with.  Currently this is always 0, since we only
313 * support uniprocessor Guests, but you can see the beginnings of SMP support
314 * here. */
315static ssize_t write(struct file *file, const char __user *in,
316		     size_t size, loff_t *off)
317{
318	/* Once the Guest is initialized, we hold the "struct lguest" in the
319	 * file private data. */
320	struct lguest *lg = file->private_data;
321	const unsigned long __user *input = (const unsigned long __user *)in;
322	unsigned long req;
323	struct lg_cpu *uninitialized_var(cpu);
324	unsigned int cpu_id = *off;
325
326	/* The first value tells us what this request is. */
327	if (get_user(req, input) != 0)
328		return -EFAULT;
329	input++;
330
331	/* If you haven't initialized, you must do that first. */
332	if (req != LHREQ_INITIALIZE) {
333		if (!lg || (cpu_id >= lg->nr_cpus))
334			return -EINVAL;
335		cpu = &lg->cpus[cpu_id];
336
337		/* Once the Guest is dead, you can only read() why it died. */
338		if (lg->dead)
339			return -ENOENT;
340	}
341
342	switch (req) {
343	case LHREQ_INITIALIZE:
344		return initialize(file, input);
345	case LHREQ_IRQ:
346		return user_send_irq(cpu, input);
347	case LHREQ_BREAK:
348		return break_guest_out(cpu, input);
349	case LHREQ_EVENTFD:
350		return attach_eventfd(lg, input);
351	default:
352		return -EINVAL;
353	}
354}
355
356/*L:060 The final piece of interface code is the close() routine.  It reverses
357 * everything done in initialize().  This is usually called because the
358 * Launcher exited.
359 *
360 * Note that the close routine returns 0 or a negative error number: it can't
361 * really fail, but it can whine.  I blame Sun for this wart, and K&R C for
362 * letting them do it. :*/
363static int close(struct inode *inode, struct file *file)
364{
365	struct lguest *lg = file->private_data;
366	unsigned int i;
367
368	/* If we never successfully initialized, there's nothing to clean up */
369	if (!lg)
370		return 0;
371
372	/* We need the big lock, to protect from inter-guest I/O and other
373	 * Launchers initializing guests. */
374	mutex_lock(&lguest_lock);
375
376	/* Free up the shadow page tables for the Guest. */
377	free_guest_pagetable(lg);
378
379	for (i = 0; i < lg->nr_cpus; i++) {
380		/* Cancels the hrtimer set via LHCALL_SET_CLOCKEVENT. */
381		hrtimer_cancel(&lg->cpus[i].hrt);
382		/* We can free up the register page we allocated. */
383		free_page(lg->cpus[i].regs_page);
384		/* Now all the memory cleanups are done, it's safe to release
385		 * the Launcher's memory management structure. */
386		mmput(lg->cpus[i].mm);
387	}
388
389	/* Release any eventfds they registered. */
390	for (i = 0; i < lg->eventfds->num; i++)
391		fput(lg->eventfds->map[i].event);
392	kfree(lg->eventfds);
393
394	/* If lg->dead doesn't contain an error code it will be NULL or a
395	 * kmalloc()ed string, either of which is ok to hand to kfree(). */
396	if (!IS_ERR(lg->dead))
397		kfree(lg->dead);
398	/* Free the memory allocated to the lguest_struct */
399	kfree(lg);
400	/* Release lock and exit. */
401	mutex_unlock(&lguest_lock);
402
403	return 0;
404}
405
406/*L:000
407 * Welcome to our journey through the Launcher!
408 *
409 * The Launcher is the Host userspace program which sets up, runs and services
410 * the Guest.  In fact, many comments in the Drivers which refer to "the Host"
411 * doing things are inaccurate: the Launcher does all the device handling for
412 * the Guest, but the Guest can't know that.
413 *
414 * Just to confuse you: to the Host kernel, the Launcher *is* the Guest and we
415 * shall see more of that later.
416 *
417 * We begin our understanding with the Host kernel interface which the Launcher
418 * uses: reading and writing a character device called /dev/lguest.  All the
419 * work happens in the read(), write() and close() routines: */
420static struct file_operations lguest_fops = {
421	.owner	 = THIS_MODULE,
422	.release = close,
423	.write	 = write,
424	.read	 = read,
425};
426
427/* This is a textbook example of a "misc" character device.  Populate a "struct
428 * miscdevice" and register it with misc_register(). */
429static struct miscdevice lguest_dev = {
430	.minor	= MISC_DYNAMIC_MINOR,
431	.name	= "lguest",
432	.fops	= &lguest_fops,
433};
434
435int __init lguest_device_init(void)
436{
437	return misc_register(&lguest_dev);
438}
439
440void __exit lguest_device_remove(void)
441{
442	misc_deregister(&lguest_dev);
443}
444