lguest_user.c 15 KB

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