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