lguest_user.c 15 KB

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