lguest_user.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /*P:200 This contains all the /dev/lguest code, whereby the userspace
  2. * launcher controls and communicates with the Guest. For example,
  3. * the first write will tell us the Guest's memory layout and entry
  4. * point. A read will run the Guest until something happens, such as
  5. * a signal or the Guest doing a NOTIFY out to the Launcher. There is
  6. * also a way for the Launcher to attach eventfds to particular NOTIFY
  7. * values instead of returning from the read() call.
  8. :*/
  9. #include <linux/uaccess.h>
  10. #include <linux/miscdevice.h>
  11. #include <linux/fs.h>
  12. #include <linux/sched.h>
  13. #include <linux/eventfd.h>
  14. #include <linux/file.h>
  15. #include <linux/slab.h>
  16. #include "lg.h"
  17. /*L:056
  18. * Before we move on, let's jump ahead and look at what the kernel does when
  19. * it needs to look up the eventfds. That will complete our picture of how we
  20. * use RCU.
  21. *
  22. * The notification value is in cpu->pending_notify: we return true if it went
  23. * to an eventfd.
  24. */
  25. bool send_notify_to_eventfd(struct lg_cpu *cpu)
  26. {
  27. unsigned int i;
  28. struct lg_eventfd_map *map;
  29. /*
  30. * This "rcu_read_lock()" helps track when someone is still looking at
  31. * the (RCU-using) eventfds array. It's not actually a lock at all;
  32. * indeed it's a noop in many configurations. (You didn't expect me to
  33. * explain all the RCU secrets here, did you?)
  34. */
  35. rcu_read_lock();
  36. /*
  37. * rcu_dereference is the counter-side of rcu_assign_pointer(); it
  38. * makes sure we don't access the memory pointed to by
  39. * cpu->lg->eventfds before cpu->lg->eventfds is set. Sounds crazy,
  40. * but Alpha allows this! Paul McKenney points out that a really
  41. * aggressive compiler could have the same effect:
  42. * http://lists.ozlabs.org/pipermail/lguest/2009-July/001560.html
  43. *
  44. * So play safe, use rcu_dereference to get the rcu-protected pointer:
  45. */
  46. map = rcu_dereference(cpu->lg->eventfds);
  47. /*
  48. * Simple array search: even if they add an eventfd while we do this,
  49. * we'll continue to use the old array and just won't see the new one.
  50. */
  51. for (i = 0; i < map->num; i++) {
  52. if (map->map[i].addr == cpu->pending_notify) {
  53. eventfd_signal(map->map[i].event, 1);
  54. cpu->pending_notify = 0;
  55. break;
  56. }
  57. }
  58. /* We're done with the rcu-protected variable cpu->lg->eventfds. */
  59. rcu_read_unlock();
  60. /* If we cleared the notification, it's because we found a match. */
  61. return cpu->pending_notify == 0;
  62. }
  63. /*L:055
  64. * One of the more tricksy tricks in the Linux Kernel is a technique called
  65. * Read Copy Update. Since one point of lguest is to teach lguest journeyers
  66. * about kernel coding, I use it here. (In case you're curious, other purposes
  67. * include learning about virtualization and instilling a deep appreciation for
  68. * simplicity and puppies).
  69. *
  70. * We keep a simple array which maps LHCALL_NOTIFY values to eventfds, but we
  71. * add new eventfds without ever blocking readers from accessing the array.
  72. * The current Launcher only does this during boot, so that never happens. But
  73. * Read Copy Update is cool, and adding a lock risks damaging even more puppies
  74. * than this code does.
  75. *
  76. * We allocate a brand new one-larger array, copy the old one and add our new
  77. * element. Then we make the lg eventfd pointer point to the new array.
  78. * That's the easy part: now we need to free the old one, but we need to make
  79. * sure no slow CPU somewhere is still looking at it. That's what
  80. * synchronize_rcu does for us: waits until every CPU has indicated that it has
  81. * moved on to know it's no longer using the old one.
  82. *
  83. * If that's unclear, see http://en.wikipedia.org/wiki/Read-copy-update.
  84. */
  85. static int add_eventfd(struct lguest *lg, unsigned long addr, int fd)
  86. {
  87. struct lg_eventfd_map *new, *old = lg->eventfds;
  88. /*
  89. * We don't allow notifications on value 0 anyway (pending_notify of
  90. * 0 means "nothing pending").
  91. */
  92. if (!addr)
  93. return -EINVAL;
  94. /*
  95. * Replace the old array with the new one, carefully: others can
  96. * be accessing it at the same time.
  97. */
  98. new = kmalloc(sizeof(*new) + sizeof(new->map[0]) * (old->num + 1),
  99. GFP_KERNEL);
  100. if (!new)
  101. return -ENOMEM;
  102. /* First make identical copy. */
  103. memcpy(new->map, old->map, sizeof(old->map[0]) * old->num);
  104. new->num = old->num;
  105. /* Now append new entry. */
  106. new->map[new->num].addr = addr;
  107. new->map[new->num].event = eventfd_ctx_fdget(fd);
  108. if (IS_ERR(new->map[new->num].event)) {
  109. int err = PTR_ERR(new->map[new->num].event);
  110. kfree(new);
  111. return err;
  112. }
  113. new->num++;
  114. /*
  115. * Now put new one in place: rcu_assign_pointer() is a fancy way of
  116. * doing "lg->eventfds = new", but it uses memory barriers to make
  117. * absolutely sure that the contents of "new" written above is nailed
  118. * down before we actually do the assignment.
  119. *
  120. * We have to think about these kinds of things when we're operating on
  121. * live data without locks.
  122. */
  123. rcu_assign_pointer(lg->eventfds, new);
  124. /*
  125. * We're not in a big hurry. Wait until no one's looking at old
  126. * version, then free it.
  127. */
  128. synchronize_rcu();
  129. kfree(old);
  130. return 0;
  131. }
  132. /*L:052
  133. * Receiving notifications from the Guest is usually done by attaching a
  134. * particular LHCALL_NOTIFY value to an event filedescriptor. The eventfd will
  135. * become readable when the Guest does an LHCALL_NOTIFY with that value.
  136. *
  137. * This is really convenient for processing each virtqueue in a separate
  138. * thread.
  139. */
  140. static int attach_eventfd(struct lguest *lg, const unsigned long __user *input)
  141. {
  142. unsigned long addr, fd;
  143. int err;
  144. if (get_user(addr, input) != 0)
  145. return -EFAULT;
  146. input++;
  147. if (get_user(fd, input) != 0)
  148. return -EFAULT;
  149. /*
  150. * Just make sure two callers don't add eventfds at once. We really
  151. * only need to lock against callers adding to the same Guest, so using
  152. * the Big Lguest Lock is overkill. But this is setup, not a fast path.
  153. */
  154. mutex_lock(&lguest_lock);
  155. err = add_eventfd(lg, addr, fd);
  156. mutex_unlock(&lguest_lock);
  157. return err;
  158. }
  159. /*L:050
  160. * Sending an interrupt is done by writing LHREQ_IRQ and an interrupt
  161. * number to /dev/lguest.
  162. */
  163. static int user_send_irq(struct lg_cpu *cpu, const unsigned long __user *input)
  164. {
  165. unsigned long irq;
  166. if (get_user(irq, input) != 0)
  167. return -EFAULT;
  168. if (irq >= LGUEST_IRQS)
  169. return -EINVAL;
  170. /*
  171. * Next time the Guest runs, the core code will see if it can deliver
  172. * this interrupt.
  173. */
  174. set_interrupt(cpu, irq);
  175. return 0;
  176. }
  177. /*L:040
  178. * Once our Guest is initialized, the Launcher makes it run by reading
  179. * from /dev/lguest.
  180. */
  181. static ssize_t read(struct file *file, char __user *user, size_t size,loff_t*o)
  182. {
  183. struct lguest *lg = file->private_data;
  184. struct lg_cpu *cpu;
  185. unsigned int cpu_id = *o;
  186. /* You must write LHREQ_INITIALIZE first! */
  187. if (!lg)
  188. return -EINVAL;
  189. /* Watch out for arbitrary vcpu indexes! */
  190. if (cpu_id >= lg->nr_cpus)
  191. return -EINVAL;
  192. cpu = &lg->cpus[cpu_id];
  193. /* If you're not the task which owns the Guest, go away. */
  194. if (current != cpu->tsk)
  195. return -EPERM;
  196. /* If the Guest is already dead, we indicate why */
  197. if (lg->dead) {
  198. size_t len;
  199. /* lg->dead either contains an error code, or a string. */
  200. if (IS_ERR(lg->dead))
  201. return PTR_ERR(lg->dead);
  202. /* We can only return as much as the buffer they read with. */
  203. len = min(size, strlen(lg->dead)+1);
  204. if (copy_to_user(user, lg->dead, len) != 0)
  205. return -EFAULT;
  206. return len;
  207. }
  208. /*
  209. * If we returned from read() last time because the Guest sent I/O,
  210. * clear the flag.
  211. */
  212. if (cpu->pending_notify)
  213. cpu->pending_notify = 0;
  214. /* Run the Guest until something interesting happens. */
  215. return run_guest(cpu, (unsigned long __user *)user);
  216. }
  217. /*L:025
  218. * This actually initializes a CPU. For the moment, a Guest is only
  219. * uniprocessor, so "id" is always 0.
  220. */
  221. static int lg_cpu_start(struct lg_cpu *cpu, unsigned id, unsigned long start_ip)
  222. {
  223. /* We have a limited number the number of CPUs in the lguest struct. */
  224. if (id >= ARRAY_SIZE(cpu->lg->cpus))
  225. return -EINVAL;
  226. /* Set up this CPU's id, and pointer back to the lguest struct. */
  227. cpu->id = id;
  228. cpu->lg = container_of((cpu - id), struct lguest, cpus[0]);
  229. cpu->lg->nr_cpus++;
  230. /* Each CPU has a timer it can set. */
  231. init_clockdev(cpu);
  232. /*
  233. * We need a complete page for the Guest registers: they are accessible
  234. * to the Guest and we can only grant it access to whole pages.
  235. */
  236. cpu->regs_page = get_zeroed_page(GFP_KERNEL);
  237. if (!cpu->regs_page)
  238. return -ENOMEM;
  239. /* We actually put the registers at the bottom of the page. */
  240. cpu->regs = (void *)cpu->regs_page + PAGE_SIZE - sizeof(*cpu->regs);
  241. /*
  242. * Now we initialize the Guest's registers, handing it the start
  243. * address.
  244. */
  245. lguest_arch_setup_regs(cpu, start_ip);
  246. /*
  247. * We keep a pointer to the Launcher task (ie. current task) for when
  248. * other Guests want to wake this one (eg. console input).
  249. */
  250. cpu->tsk = current;
  251. /*
  252. * We need to keep a pointer to the Launcher's memory map, because if
  253. * the Launcher dies we need to clean it up. If we don't keep a
  254. * reference, it is destroyed before close() is called.
  255. */
  256. cpu->mm = get_task_mm(cpu->tsk);
  257. /*
  258. * We remember which CPU's pages this Guest used last, for optimization
  259. * when the same Guest runs on the same CPU twice.
  260. */
  261. cpu->last_pages = NULL;
  262. /* No error == success. */
  263. return 0;
  264. }
  265. /*L:020
  266. * The initialization write supplies 3 pointer sized (32 or 64 bit) values (in
  267. * addition to the LHREQ_INITIALIZE value). These are:
  268. *
  269. * base: The start of the Guest-physical memory inside the Launcher memory.
  270. *
  271. * pfnlimit: The highest (Guest-physical) page number the Guest should be
  272. * allowed to access. The Guest memory lives inside the Launcher, so it sets
  273. * this to ensure the Guest can only reach its own memory.
  274. *
  275. * start: The first instruction to execute ("eip" in x86-speak).
  276. */
  277. static int initialize(struct file *file, const unsigned long __user *input)
  278. {
  279. /* "struct lguest" contains all we (the Host) know about a Guest. */
  280. struct lguest *lg;
  281. int err;
  282. unsigned long args[3];
  283. /*
  284. * We grab the Big Lguest lock, which protects against multiple
  285. * simultaneous initializations.
  286. */
  287. mutex_lock(&lguest_lock);
  288. /* You can't initialize twice! Close the device and start again... */
  289. if (file->private_data) {
  290. err = -EBUSY;
  291. goto unlock;
  292. }
  293. if (copy_from_user(args, input, sizeof(args)) != 0) {
  294. err = -EFAULT;
  295. goto unlock;
  296. }
  297. lg = kzalloc(sizeof(*lg), GFP_KERNEL);
  298. if (!lg) {
  299. err = -ENOMEM;
  300. goto unlock;
  301. }
  302. lg->eventfds = kmalloc(sizeof(*lg->eventfds), GFP_KERNEL);
  303. if (!lg->eventfds) {
  304. err = -ENOMEM;
  305. goto free_lg;
  306. }
  307. lg->eventfds->num = 0;
  308. /* Populate the easy fields of our "struct lguest" */
  309. lg->mem_base = (void __user *)args[0];
  310. lg->pfn_limit = args[1];
  311. /* This is the first cpu (cpu 0) and it will start booting at args[2] */
  312. err = lg_cpu_start(&lg->cpus[0], 0, args[2]);
  313. if (err)
  314. goto free_eventfds;
  315. /*
  316. * Initialize the Guest's shadow page tables. This allocates
  317. * memory, so can fail.
  318. */
  319. err = init_guest_pagetable(lg);
  320. if (err)
  321. goto free_regs;
  322. /* We keep our "struct lguest" in the file's private_data. */
  323. file->private_data = lg;
  324. mutex_unlock(&lguest_lock);
  325. /* And because this is a write() call, we return the length used. */
  326. return sizeof(args);
  327. free_regs:
  328. /* FIXME: This should be in free_vcpu */
  329. free_page(lg->cpus[0].regs_page);
  330. free_eventfds:
  331. kfree(lg->eventfds);
  332. free_lg:
  333. kfree(lg);
  334. unlock:
  335. mutex_unlock(&lguest_lock);
  336. return err;
  337. }
  338. /*L:010
  339. * The first operation the Launcher does must be a write. All writes
  340. * start with an unsigned long number: for the first write this must be
  341. * LHREQ_INITIALIZE to set up the Guest. After that the Launcher can use
  342. * writes of other values to send interrupts or set up receipt of notifications.
  343. *
  344. * Note that we overload the "offset" in the /dev/lguest file to indicate what
  345. * CPU number we're dealing with. Currently this is always 0 since we only
  346. * support uniprocessor Guests, but you can see the beginnings of SMP support
  347. * here.
  348. */
  349. static ssize_t write(struct file *file, const char __user *in,
  350. size_t size, loff_t *off)
  351. {
  352. /*
  353. * Once the Guest is initialized, we hold the "struct lguest" in the
  354. * file private data.
  355. */
  356. struct lguest *lg = file->private_data;
  357. const unsigned long __user *input = (const unsigned long __user *)in;
  358. unsigned long req;
  359. struct lg_cpu *uninitialized_var(cpu);
  360. unsigned int cpu_id = *off;
  361. /* The first value tells us what this request is. */
  362. if (get_user(req, input) != 0)
  363. return -EFAULT;
  364. input++;
  365. /* If you haven't initialized, you must do that first. */
  366. if (req != LHREQ_INITIALIZE) {
  367. if (!lg || (cpu_id >= lg->nr_cpus))
  368. return -EINVAL;
  369. cpu = &lg->cpus[cpu_id];
  370. /* Once the Guest is dead, you can only read() why it died. */
  371. if (lg->dead)
  372. return -ENOENT;
  373. }
  374. switch (req) {
  375. case LHREQ_INITIALIZE:
  376. return initialize(file, input);
  377. case LHREQ_IRQ:
  378. return user_send_irq(cpu, input);
  379. case LHREQ_EVENTFD:
  380. return attach_eventfd(lg, input);
  381. default:
  382. return -EINVAL;
  383. }
  384. }
  385. /*L:060
  386. * The final piece of interface code is the close() routine. It reverses
  387. * everything done in initialize(). This is usually called because the
  388. * Launcher exited.
  389. *
  390. * Note that the close routine returns 0 or a negative error number: it can't
  391. * really fail, but it can whine. I blame Sun for this wart, and K&R C for
  392. * letting them do it.
  393. :*/
  394. static int close(struct inode *inode, struct file *file)
  395. {
  396. struct lguest *lg = file->private_data;
  397. unsigned int i;
  398. /* If we never successfully initialized, there's nothing to clean up */
  399. if (!lg)
  400. return 0;
  401. /*
  402. * We need the big lock, to protect from inter-guest I/O and other
  403. * Launchers initializing guests.
  404. */
  405. mutex_lock(&lguest_lock);
  406. /* Free up the shadow page tables for the Guest. */
  407. free_guest_pagetable(lg);
  408. for (i = 0; i < lg->nr_cpus; i++) {
  409. /* Cancels the hrtimer set via LHCALL_SET_CLOCKEVENT. */
  410. hrtimer_cancel(&lg->cpus[i].hrt);
  411. /* We can free up the register page we allocated. */
  412. free_page(lg->cpus[i].regs_page);
  413. /*
  414. * Now all the memory cleanups are done, it's safe to release
  415. * the Launcher's memory management structure.
  416. */
  417. mmput(lg->cpus[i].mm);
  418. }
  419. /* Release any eventfds they registered. */
  420. for (i = 0; i < lg->eventfds->num; i++)
  421. eventfd_ctx_put(lg->eventfds->map[i].event);
  422. kfree(lg->eventfds);
  423. /*
  424. * If lg->dead doesn't contain an error code it will be NULL or a
  425. * kmalloc()ed string, either of which is ok to hand to kfree().
  426. */
  427. if (!IS_ERR(lg->dead))
  428. kfree(lg->dead);
  429. /* Free the memory allocated to the lguest_struct */
  430. kfree(lg);
  431. /* Release lock and exit. */
  432. mutex_unlock(&lguest_lock);
  433. return 0;
  434. }
  435. /*L:000
  436. * Welcome to our journey through the Launcher!
  437. *
  438. * The Launcher is the Host userspace program which sets up, runs and services
  439. * the Guest. In fact, many comments in the Drivers which refer to "the Host"
  440. * doing things are inaccurate: the Launcher does all the device handling for
  441. * the Guest, but the Guest can't know that.
  442. *
  443. * Just to confuse you: to the Host kernel, the Launcher *is* the Guest and we
  444. * shall see more of that later.
  445. *
  446. * We begin our understanding with the Host kernel interface which the Launcher
  447. * uses: reading and writing a character device called /dev/lguest. All the
  448. * work happens in the read(), write() and close() routines:
  449. */
  450. static const struct file_operations lguest_fops = {
  451. .owner = THIS_MODULE,
  452. .release = close,
  453. .write = write,
  454. .read = read,
  455. .llseek = default_llseek,
  456. };
  457. /*:*/
  458. /*
  459. * This is a textbook example of a "misc" character device. Populate a "struct
  460. * miscdevice" and register it with misc_register().
  461. */
  462. static struct miscdevice lguest_dev = {
  463. .minor = MISC_DYNAMIC_MINOR,
  464. .name = "lguest",
  465. .fops = &lguest_fops,
  466. };
  467. int __init lguest_device_init(void)
  468. {
  469. return misc_register(&lguest_dev);
  470. }
  471. void __exit lguest_device_remove(void)
  472. {
  473. misc_deregister(&lguest_dev);
  474. }