lguest_user.c 15 KB

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