vhost.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701
  1. /* Copyright (C) 2009 Red Hat, Inc.
  2. * Copyright (C) 2006 Rusty Russell IBM Corporation
  3. *
  4. * Author: Michael S. Tsirkin <mst@redhat.com>
  5. *
  6. * Inspiration, some code, and most witty comments come from
  7. * Documentation/virtual/lguest/lguest.c, by Rusty Russell
  8. *
  9. * This work is licensed under the terms of the GNU GPL, version 2.
  10. *
  11. * Generic code for virtio server in host kernel.
  12. */
  13. #include <linux/eventfd.h>
  14. #include <linux/vhost.h>
  15. #include <linux/uio.h>
  16. #include <linux/mm.h>
  17. #include <linux/mmu_context.h>
  18. #include <linux/miscdevice.h>
  19. #include <linux/mutex.h>
  20. #include <linux/poll.h>
  21. #include <linux/file.h>
  22. #include <linux/highmem.h>
  23. #include <linux/slab.h>
  24. #include <linux/vmalloc.h>
  25. #include <linux/kthread.h>
  26. #include <linux/cgroup.h>
  27. #include <linux/module.h>
  28. #include <linux/sort.h>
  29. #include "vhost.h"
  30. static ushort max_mem_regions = 64;
  31. module_param(max_mem_regions, ushort, 0444);
  32. MODULE_PARM_DESC(max_mem_regions,
  33. "Maximum number of memory regions in memory map. (default: 64)");
  34. enum {
  35. VHOST_MEMORY_F_LOG = 0x1,
  36. };
  37. #define vhost_used_event(vq) ((__virtio16 __user *)&vq->avail->ring[vq->num])
  38. #define vhost_avail_event(vq) ((__virtio16 __user *)&vq->used->ring[vq->num])
  39. #ifdef CONFIG_VHOST_CROSS_ENDIAN_LEGACY
  40. static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
  41. {
  42. vq->user_be = !virtio_legacy_is_little_endian();
  43. }
  44. static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
  45. {
  46. struct vhost_vring_state s;
  47. if (vq->private_data)
  48. return -EBUSY;
  49. if (copy_from_user(&s, argp, sizeof(s)))
  50. return -EFAULT;
  51. if (s.num != VHOST_VRING_LITTLE_ENDIAN &&
  52. s.num != VHOST_VRING_BIG_ENDIAN)
  53. return -EINVAL;
  54. vq->user_be = s.num;
  55. return 0;
  56. }
  57. static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
  58. int __user *argp)
  59. {
  60. struct vhost_vring_state s = {
  61. .index = idx,
  62. .num = vq->user_be
  63. };
  64. if (copy_to_user(argp, &s, sizeof(s)))
  65. return -EFAULT;
  66. return 0;
  67. }
  68. static void vhost_init_is_le(struct vhost_virtqueue *vq)
  69. {
  70. /* Note for legacy virtio: user_be is initialized at reset time
  71. * according to the host endianness. If userspace does not set an
  72. * explicit endianness, the default behavior is native endian, as
  73. * expected by legacy virtio.
  74. */
  75. vq->is_le = vhost_has_feature(vq, VIRTIO_F_VERSION_1) || !vq->user_be;
  76. }
  77. #else
  78. static void vhost_vq_reset_user_be(struct vhost_virtqueue *vq)
  79. {
  80. }
  81. static long vhost_set_vring_endian(struct vhost_virtqueue *vq, int __user *argp)
  82. {
  83. return -ENOIOCTLCMD;
  84. }
  85. static long vhost_get_vring_endian(struct vhost_virtqueue *vq, u32 idx,
  86. int __user *argp)
  87. {
  88. return -ENOIOCTLCMD;
  89. }
  90. static void vhost_init_is_le(struct vhost_virtqueue *vq)
  91. {
  92. if (vhost_has_feature(vq, VIRTIO_F_VERSION_1))
  93. vq->is_le = true;
  94. }
  95. #endif /* CONFIG_VHOST_CROSS_ENDIAN_LEGACY */
  96. static void vhost_poll_func(struct file *file, wait_queue_head_t *wqh,
  97. poll_table *pt)
  98. {
  99. struct vhost_poll *poll;
  100. poll = container_of(pt, struct vhost_poll, table);
  101. poll->wqh = wqh;
  102. add_wait_queue(wqh, &poll->wait);
  103. }
  104. static int vhost_poll_wakeup(wait_queue_t *wait, unsigned mode, int sync,
  105. void *key)
  106. {
  107. struct vhost_poll *poll = container_of(wait, struct vhost_poll, wait);
  108. if (!((unsigned long)key & poll->mask))
  109. return 0;
  110. vhost_poll_queue(poll);
  111. return 0;
  112. }
  113. void vhost_work_init(struct vhost_work *work, vhost_work_fn_t fn)
  114. {
  115. INIT_LIST_HEAD(&work->node);
  116. work->fn = fn;
  117. init_waitqueue_head(&work->done);
  118. work->flushing = 0;
  119. work->queue_seq = work->done_seq = 0;
  120. }
  121. EXPORT_SYMBOL_GPL(vhost_work_init);
  122. /* Init poll structure */
  123. void vhost_poll_init(struct vhost_poll *poll, vhost_work_fn_t fn,
  124. unsigned long mask, struct vhost_dev *dev)
  125. {
  126. init_waitqueue_func_entry(&poll->wait, vhost_poll_wakeup);
  127. init_poll_funcptr(&poll->table, vhost_poll_func);
  128. poll->mask = mask;
  129. poll->dev = dev;
  130. poll->wqh = NULL;
  131. vhost_work_init(&poll->work, fn);
  132. }
  133. EXPORT_SYMBOL_GPL(vhost_poll_init);
  134. /* Start polling a file. We add ourselves to file's wait queue. The caller must
  135. * keep a reference to a file until after vhost_poll_stop is called. */
  136. int vhost_poll_start(struct vhost_poll *poll, struct file *file)
  137. {
  138. unsigned long mask;
  139. int ret = 0;
  140. if (poll->wqh)
  141. return 0;
  142. mask = file->f_op->poll(file, &poll->table);
  143. if (mask)
  144. vhost_poll_wakeup(&poll->wait, 0, 0, (void *)mask);
  145. if (mask & POLLERR) {
  146. if (poll->wqh)
  147. remove_wait_queue(poll->wqh, &poll->wait);
  148. ret = -EINVAL;
  149. }
  150. return ret;
  151. }
  152. EXPORT_SYMBOL_GPL(vhost_poll_start);
  153. /* Stop polling a file. After this function returns, it becomes safe to drop the
  154. * file reference. You must also flush afterwards. */
  155. void vhost_poll_stop(struct vhost_poll *poll)
  156. {
  157. if (poll->wqh) {
  158. remove_wait_queue(poll->wqh, &poll->wait);
  159. poll->wqh = NULL;
  160. }
  161. }
  162. EXPORT_SYMBOL_GPL(vhost_poll_stop);
  163. static bool vhost_work_seq_done(struct vhost_dev *dev, struct vhost_work *work,
  164. unsigned seq)
  165. {
  166. int left;
  167. spin_lock_irq(&dev->work_lock);
  168. left = seq - work->done_seq;
  169. spin_unlock_irq(&dev->work_lock);
  170. return left <= 0;
  171. }
  172. void vhost_work_flush(struct vhost_dev *dev, struct vhost_work *work)
  173. {
  174. unsigned seq;
  175. int flushing;
  176. spin_lock_irq(&dev->work_lock);
  177. seq = work->queue_seq;
  178. work->flushing++;
  179. spin_unlock_irq(&dev->work_lock);
  180. wait_event(work->done, vhost_work_seq_done(dev, work, seq));
  181. spin_lock_irq(&dev->work_lock);
  182. flushing = --work->flushing;
  183. spin_unlock_irq(&dev->work_lock);
  184. BUG_ON(flushing < 0);
  185. }
  186. EXPORT_SYMBOL_GPL(vhost_work_flush);
  187. /* Flush any work that has been scheduled. When calling this, don't hold any
  188. * locks that are also used by the callback. */
  189. void vhost_poll_flush(struct vhost_poll *poll)
  190. {
  191. vhost_work_flush(poll->dev, &poll->work);
  192. }
  193. EXPORT_SYMBOL_GPL(vhost_poll_flush);
  194. void vhost_work_queue(struct vhost_dev *dev, struct vhost_work *work)
  195. {
  196. unsigned long flags;
  197. spin_lock_irqsave(&dev->work_lock, flags);
  198. if (list_empty(&work->node)) {
  199. list_add_tail(&work->node, &dev->work_list);
  200. work->queue_seq++;
  201. spin_unlock_irqrestore(&dev->work_lock, flags);
  202. wake_up_process(dev->worker);
  203. } else {
  204. spin_unlock_irqrestore(&dev->work_lock, flags);
  205. }
  206. }
  207. EXPORT_SYMBOL_GPL(vhost_work_queue);
  208. void vhost_poll_queue(struct vhost_poll *poll)
  209. {
  210. vhost_work_queue(poll->dev, &poll->work);
  211. }
  212. EXPORT_SYMBOL_GPL(vhost_poll_queue);
  213. static void vhost_vq_reset(struct vhost_dev *dev,
  214. struct vhost_virtqueue *vq)
  215. {
  216. vq->num = 1;
  217. vq->desc = NULL;
  218. vq->avail = NULL;
  219. vq->used = NULL;
  220. vq->last_avail_idx = 0;
  221. vq->avail_idx = 0;
  222. vq->last_used_idx = 0;
  223. vq->signalled_used = 0;
  224. vq->signalled_used_valid = false;
  225. vq->used_flags = 0;
  226. vq->log_used = false;
  227. vq->log_addr = -1ull;
  228. vq->private_data = NULL;
  229. vq->acked_features = 0;
  230. vq->log_base = NULL;
  231. vq->error_ctx = NULL;
  232. vq->error = NULL;
  233. vq->kick = NULL;
  234. vq->call_ctx = NULL;
  235. vq->call = NULL;
  236. vq->log_ctx = NULL;
  237. vq->memory = NULL;
  238. vq->is_le = virtio_legacy_is_little_endian();
  239. vhost_vq_reset_user_be(vq);
  240. }
  241. static int vhost_worker(void *data)
  242. {
  243. struct vhost_dev *dev = data;
  244. struct vhost_work *work = NULL;
  245. unsigned uninitialized_var(seq);
  246. mm_segment_t oldfs = get_fs();
  247. set_fs(USER_DS);
  248. use_mm(dev->mm);
  249. for (;;) {
  250. /* mb paired w/ kthread_stop */
  251. set_current_state(TASK_INTERRUPTIBLE);
  252. spin_lock_irq(&dev->work_lock);
  253. if (work) {
  254. work->done_seq = seq;
  255. if (work->flushing)
  256. wake_up_all(&work->done);
  257. }
  258. if (kthread_should_stop()) {
  259. spin_unlock_irq(&dev->work_lock);
  260. __set_current_state(TASK_RUNNING);
  261. break;
  262. }
  263. if (!list_empty(&dev->work_list)) {
  264. work = list_first_entry(&dev->work_list,
  265. struct vhost_work, node);
  266. list_del_init(&work->node);
  267. seq = work->queue_seq;
  268. } else
  269. work = NULL;
  270. spin_unlock_irq(&dev->work_lock);
  271. if (work) {
  272. __set_current_state(TASK_RUNNING);
  273. work->fn(work);
  274. if (need_resched())
  275. schedule();
  276. } else
  277. schedule();
  278. }
  279. unuse_mm(dev->mm);
  280. set_fs(oldfs);
  281. return 0;
  282. }
  283. static void vhost_vq_free_iovecs(struct vhost_virtqueue *vq)
  284. {
  285. kfree(vq->indirect);
  286. vq->indirect = NULL;
  287. kfree(vq->log);
  288. vq->log = NULL;
  289. kfree(vq->heads);
  290. vq->heads = NULL;
  291. }
  292. /* Helper to allocate iovec buffers for all vqs. */
  293. static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
  294. {
  295. struct vhost_virtqueue *vq;
  296. int i;
  297. for (i = 0; i < dev->nvqs; ++i) {
  298. vq = dev->vqs[i];
  299. vq->indirect = kmalloc(sizeof *vq->indirect * UIO_MAXIOV,
  300. GFP_KERNEL);
  301. vq->log = kmalloc(sizeof *vq->log * UIO_MAXIOV, GFP_KERNEL);
  302. vq->heads = kmalloc(sizeof *vq->heads * UIO_MAXIOV, GFP_KERNEL);
  303. if (!vq->indirect || !vq->log || !vq->heads)
  304. goto err_nomem;
  305. }
  306. return 0;
  307. err_nomem:
  308. for (; i >= 0; --i)
  309. vhost_vq_free_iovecs(dev->vqs[i]);
  310. return -ENOMEM;
  311. }
  312. static void vhost_dev_free_iovecs(struct vhost_dev *dev)
  313. {
  314. int i;
  315. for (i = 0; i < dev->nvqs; ++i)
  316. vhost_vq_free_iovecs(dev->vqs[i]);
  317. }
  318. void vhost_dev_init(struct vhost_dev *dev,
  319. struct vhost_virtqueue **vqs, int nvqs)
  320. {
  321. struct vhost_virtqueue *vq;
  322. int i;
  323. dev->vqs = vqs;
  324. dev->nvqs = nvqs;
  325. mutex_init(&dev->mutex);
  326. dev->log_ctx = NULL;
  327. dev->log_file = NULL;
  328. dev->memory = NULL;
  329. dev->mm = NULL;
  330. spin_lock_init(&dev->work_lock);
  331. INIT_LIST_HEAD(&dev->work_list);
  332. dev->worker = NULL;
  333. for (i = 0; i < dev->nvqs; ++i) {
  334. vq = dev->vqs[i];
  335. vq->log = NULL;
  336. vq->indirect = NULL;
  337. vq->heads = NULL;
  338. vq->dev = dev;
  339. mutex_init(&vq->mutex);
  340. vhost_vq_reset(dev, vq);
  341. if (vq->handle_kick)
  342. vhost_poll_init(&vq->poll, vq->handle_kick,
  343. POLLIN, dev);
  344. }
  345. }
  346. EXPORT_SYMBOL_GPL(vhost_dev_init);
  347. /* Caller should have device mutex */
  348. long vhost_dev_check_owner(struct vhost_dev *dev)
  349. {
  350. /* Are you the owner? If not, I don't think you mean to do that */
  351. return dev->mm == current->mm ? 0 : -EPERM;
  352. }
  353. EXPORT_SYMBOL_GPL(vhost_dev_check_owner);
  354. struct vhost_attach_cgroups_struct {
  355. struct vhost_work work;
  356. struct task_struct *owner;
  357. int ret;
  358. };
  359. static void vhost_attach_cgroups_work(struct vhost_work *work)
  360. {
  361. struct vhost_attach_cgroups_struct *s;
  362. s = container_of(work, struct vhost_attach_cgroups_struct, work);
  363. s->ret = cgroup_attach_task_all(s->owner, current);
  364. }
  365. static int vhost_attach_cgroups(struct vhost_dev *dev)
  366. {
  367. struct vhost_attach_cgroups_struct attach;
  368. attach.owner = current;
  369. vhost_work_init(&attach.work, vhost_attach_cgroups_work);
  370. vhost_work_queue(dev, &attach.work);
  371. vhost_work_flush(dev, &attach.work);
  372. return attach.ret;
  373. }
  374. /* Caller should have device mutex */
  375. bool vhost_dev_has_owner(struct vhost_dev *dev)
  376. {
  377. return dev->mm;
  378. }
  379. EXPORT_SYMBOL_GPL(vhost_dev_has_owner);
  380. /* Caller should have device mutex */
  381. long vhost_dev_set_owner(struct vhost_dev *dev)
  382. {
  383. struct task_struct *worker;
  384. int err;
  385. /* Is there an owner already? */
  386. if (vhost_dev_has_owner(dev)) {
  387. err = -EBUSY;
  388. goto err_mm;
  389. }
  390. /* No owner, become one */
  391. dev->mm = get_task_mm(current);
  392. worker = kthread_create(vhost_worker, dev, "vhost-%d", current->pid);
  393. if (IS_ERR(worker)) {
  394. err = PTR_ERR(worker);
  395. goto err_worker;
  396. }
  397. dev->worker = worker;
  398. wake_up_process(worker); /* avoid contributing to loadavg */
  399. err = vhost_attach_cgroups(dev);
  400. if (err)
  401. goto err_cgroup;
  402. err = vhost_dev_alloc_iovecs(dev);
  403. if (err)
  404. goto err_cgroup;
  405. return 0;
  406. err_cgroup:
  407. kthread_stop(worker);
  408. dev->worker = NULL;
  409. err_worker:
  410. if (dev->mm)
  411. mmput(dev->mm);
  412. dev->mm = NULL;
  413. err_mm:
  414. return err;
  415. }
  416. EXPORT_SYMBOL_GPL(vhost_dev_set_owner);
  417. struct vhost_memory *vhost_dev_reset_owner_prepare(void)
  418. {
  419. return kmalloc(offsetof(struct vhost_memory, regions), GFP_KERNEL);
  420. }
  421. EXPORT_SYMBOL_GPL(vhost_dev_reset_owner_prepare);
  422. /* Caller should have device mutex */
  423. void vhost_dev_reset_owner(struct vhost_dev *dev, struct vhost_memory *memory)
  424. {
  425. int i;
  426. vhost_dev_cleanup(dev, true);
  427. /* Restore memory to default empty mapping. */
  428. memory->nregions = 0;
  429. dev->memory = memory;
  430. /* We don't need VQ locks below since vhost_dev_cleanup makes sure
  431. * VQs aren't running.
  432. */
  433. for (i = 0; i < dev->nvqs; ++i)
  434. dev->vqs[i]->memory = memory;
  435. }
  436. EXPORT_SYMBOL_GPL(vhost_dev_reset_owner);
  437. void vhost_dev_stop(struct vhost_dev *dev)
  438. {
  439. int i;
  440. for (i = 0; i < dev->nvqs; ++i) {
  441. if (dev->vqs[i]->kick && dev->vqs[i]->handle_kick) {
  442. vhost_poll_stop(&dev->vqs[i]->poll);
  443. vhost_poll_flush(&dev->vqs[i]->poll);
  444. }
  445. }
  446. }
  447. EXPORT_SYMBOL_GPL(vhost_dev_stop);
  448. /* Caller should have device mutex if and only if locked is set */
  449. void vhost_dev_cleanup(struct vhost_dev *dev, bool locked)
  450. {
  451. int i;
  452. for (i = 0; i < dev->nvqs; ++i) {
  453. if (dev->vqs[i]->error_ctx)
  454. eventfd_ctx_put(dev->vqs[i]->error_ctx);
  455. if (dev->vqs[i]->error)
  456. fput(dev->vqs[i]->error);
  457. if (dev->vqs[i]->kick)
  458. fput(dev->vqs[i]->kick);
  459. if (dev->vqs[i]->call_ctx)
  460. eventfd_ctx_put(dev->vqs[i]->call_ctx);
  461. if (dev->vqs[i]->call)
  462. fput(dev->vqs[i]->call);
  463. vhost_vq_reset(dev, dev->vqs[i]);
  464. }
  465. vhost_dev_free_iovecs(dev);
  466. if (dev->log_ctx)
  467. eventfd_ctx_put(dev->log_ctx);
  468. dev->log_ctx = NULL;
  469. if (dev->log_file)
  470. fput(dev->log_file);
  471. dev->log_file = NULL;
  472. /* No one will access memory at this point */
  473. kvfree(dev->memory);
  474. dev->memory = NULL;
  475. WARN_ON(!list_empty(&dev->work_list));
  476. if (dev->worker) {
  477. kthread_stop(dev->worker);
  478. dev->worker = NULL;
  479. }
  480. if (dev->mm)
  481. mmput(dev->mm);
  482. dev->mm = NULL;
  483. }
  484. EXPORT_SYMBOL_GPL(vhost_dev_cleanup);
  485. static int log_access_ok(void __user *log_base, u64 addr, unsigned long sz)
  486. {
  487. u64 a = addr / VHOST_PAGE_SIZE / 8;
  488. /* Make sure 64 bit math will not overflow. */
  489. if (a > ULONG_MAX - (unsigned long)log_base ||
  490. a + (unsigned long)log_base > ULONG_MAX)
  491. return 0;
  492. return access_ok(VERIFY_WRITE, log_base + a,
  493. (sz + VHOST_PAGE_SIZE * 8 - 1) / VHOST_PAGE_SIZE / 8);
  494. }
  495. /* Caller should have vq mutex and device mutex. */
  496. static int vq_memory_access_ok(void __user *log_base, struct vhost_memory *mem,
  497. int log_all)
  498. {
  499. int i;
  500. if (!mem)
  501. return 0;
  502. for (i = 0; i < mem->nregions; ++i) {
  503. struct vhost_memory_region *m = mem->regions + i;
  504. unsigned long a = m->userspace_addr;
  505. if (m->memory_size > ULONG_MAX)
  506. return 0;
  507. else if (!access_ok(VERIFY_WRITE, (void __user *)a,
  508. m->memory_size))
  509. return 0;
  510. else if (log_all && !log_access_ok(log_base,
  511. m->guest_phys_addr,
  512. m->memory_size))
  513. return 0;
  514. }
  515. return 1;
  516. }
  517. /* Can we switch to this memory table? */
  518. /* Caller should have device mutex but not vq mutex */
  519. static int memory_access_ok(struct vhost_dev *d, struct vhost_memory *mem,
  520. int log_all)
  521. {
  522. int i;
  523. for (i = 0; i < d->nvqs; ++i) {
  524. int ok;
  525. bool log;
  526. mutex_lock(&d->vqs[i]->mutex);
  527. log = log_all || vhost_has_feature(d->vqs[i], VHOST_F_LOG_ALL);
  528. /* If ring is inactive, will check when it's enabled. */
  529. if (d->vqs[i]->private_data)
  530. ok = vq_memory_access_ok(d->vqs[i]->log_base, mem, log);
  531. else
  532. ok = 1;
  533. mutex_unlock(&d->vqs[i]->mutex);
  534. if (!ok)
  535. return 0;
  536. }
  537. return 1;
  538. }
  539. static int vq_access_ok(struct vhost_virtqueue *vq, unsigned int num,
  540. struct vring_desc __user *desc,
  541. struct vring_avail __user *avail,
  542. struct vring_used __user *used)
  543. {
  544. size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
  545. return access_ok(VERIFY_READ, desc, num * sizeof *desc) &&
  546. access_ok(VERIFY_READ, avail,
  547. sizeof *avail + num * sizeof *avail->ring + s) &&
  548. access_ok(VERIFY_WRITE, used,
  549. sizeof *used + num * sizeof *used->ring + s);
  550. }
  551. /* Can we log writes? */
  552. /* Caller should have device mutex but not vq mutex */
  553. int vhost_log_access_ok(struct vhost_dev *dev)
  554. {
  555. return memory_access_ok(dev, dev->memory, 1);
  556. }
  557. EXPORT_SYMBOL_GPL(vhost_log_access_ok);
  558. /* Verify access for write logging. */
  559. /* Caller should have vq mutex and device mutex */
  560. static int vq_log_access_ok(struct vhost_virtqueue *vq,
  561. void __user *log_base)
  562. {
  563. size_t s = vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
  564. return vq_memory_access_ok(log_base, vq->memory,
  565. vhost_has_feature(vq, VHOST_F_LOG_ALL)) &&
  566. (!vq->log_used || log_access_ok(log_base, vq->log_addr,
  567. sizeof *vq->used +
  568. vq->num * sizeof *vq->used->ring + s));
  569. }
  570. /* Can we start vq? */
  571. /* Caller should have vq mutex and device mutex */
  572. int vhost_vq_access_ok(struct vhost_virtqueue *vq)
  573. {
  574. return vq_access_ok(vq, vq->num, vq->desc, vq->avail, vq->used) &&
  575. vq_log_access_ok(vq, vq->log_base);
  576. }
  577. EXPORT_SYMBOL_GPL(vhost_vq_access_ok);
  578. static int vhost_memory_reg_sort_cmp(const void *p1, const void *p2)
  579. {
  580. const struct vhost_memory_region *r1 = p1, *r2 = p2;
  581. if (r1->guest_phys_addr < r2->guest_phys_addr)
  582. return 1;
  583. if (r1->guest_phys_addr > r2->guest_phys_addr)
  584. return -1;
  585. return 0;
  586. }
  587. static void *vhost_kvzalloc(unsigned long size)
  588. {
  589. void *n = kzalloc(size, GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT);
  590. if (!n) {
  591. n = vzalloc(size);
  592. if (!n)
  593. return ERR_PTR(-ENOMEM);
  594. }
  595. return n;
  596. }
  597. static long vhost_set_memory(struct vhost_dev *d, struct vhost_memory __user *m)
  598. {
  599. struct vhost_memory mem, *newmem, *oldmem;
  600. unsigned long size = offsetof(struct vhost_memory, regions);
  601. int i;
  602. if (copy_from_user(&mem, m, size))
  603. return -EFAULT;
  604. if (mem.padding)
  605. return -EOPNOTSUPP;
  606. if (mem.nregions > max_mem_regions)
  607. return -E2BIG;
  608. newmem = vhost_kvzalloc(size + mem.nregions * sizeof(*m->regions));
  609. if (!newmem)
  610. return -ENOMEM;
  611. memcpy(newmem, &mem, size);
  612. if (copy_from_user(newmem->regions, m->regions,
  613. mem.nregions * sizeof *m->regions)) {
  614. kvfree(newmem);
  615. return -EFAULT;
  616. }
  617. sort(newmem->regions, newmem->nregions, sizeof(*newmem->regions),
  618. vhost_memory_reg_sort_cmp, NULL);
  619. if (!memory_access_ok(d, newmem, 0)) {
  620. kvfree(newmem);
  621. return -EFAULT;
  622. }
  623. oldmem = d->memory;
  624. d->memory = newmem;
  625. /* All memory accesses are done under some VQ mutex. */
  626. for (i = 0; i < d->nvqs; ++i) {
  627. mutex_lock(&d->vqs[i]->mutex);
  628. d->vqs[i]->memory = newmem;
  629. mutex_unlock(&d->vqs[i]->mutex);
  630. }
  631. kvfree(oldmem);
  632. return 0;
  633. }
  634. long vhost_vring_ioctl(struct vhost_dev *d, int ioctl, void __user *argp)
  635. {
  636. struct file *eventfp, *filep = NULL;
  637. bool pollstart = false, pollstop = false;
  638. struct eventfd_ctx *ctx = NULL;
  639. u32 __user *idxp = argp;
  640. struct vhost_virtqueue *vq;
  641. struct vhost_vring_state s;
  642. struct vhost_vring_file f;
  643. struct vhost_vring_addr a;
  644. u32 idx;
  645. long r;
  646. r = get_user(idx, idxp);
  647. if (r < 0)
  648. return r;
  649. if (idx >= d->nvqs)
  650. return -ENOBUFS;
  651. vq = d->vqs[idx];
  652. mutex_lock(&vq->mutex);
  653. switch (ioctl) {
  654. case VHOST_SET_VRING_NUM:
  655. /* Resizing ring with an active backend?
  656. * You don't want to do that. */
  657. if (vq->private_data) {
  658. r = -EBUSY;
  659. break;
  660. }
  661. if (copy_from_user(&s, argp, sizeof s)) {
  662. r = -EFAULT;
  663. break;
  664. }
  665. if (!s.num || s.num > 0xffff || (s.num & (s.num - 1))) {
  666. r = -EINVAL;
  667. break;
  668. }
  669. vq->num = s.num;
  670. break;
  671. case VHOST_SET_VRING_BASE:
  672. /* Moving base with an active backend?
  673. * You don't want to do that. */
  674. if (vq->private_data) {
  675. r = -EBUSY;
  676. break;
  677. }
  678. if (copy_from_user(&s, argp, sizeof s)) {
  679. r = -EFAULT;
  680. break;
  681. }
  682. if (s.num > 0xffff) {
  683. r = -EINVAL;
  684. break;
  685. }
  686. vq->last_avail_idx = s.num;
  687. /* Forget the cached index value. */
  688. vq->avail_idx = vq->last_avail_idx;
  689. break;
  690. case VHOST_GET_VRING_BASE:
  691. s.index = idx;
  692. s.num = vq->last_avail_idx;
  693. if (copy_to_user(argp, &s, sizeof s))
  694. r = -EFAULT;
  695. break;
  696. case VHOST_SET_VRING_ADDR:
  697. if (copy_from_user(&a, argp, sizeof a)) {
  698. r = -EFAULT;
  699. break;
  700. }
  701. if (a.flags & ~(0x1 << VHOST_VRING_F_LOG)) {
  702. r = -EOPNOTSUPP;
  703. break;
  704. }
  705. /* For 32bit, verify that the top 32bits of the user
  706. data are set to zero. */
  707. if ((u64)(unsigned long)a.desc_user_addr != a.desc_user_addr ||
  708. (u64)(unsigned long)a.used_user_addr != a.used_user_addr ||
  709. (u64)(unsigned long)a.avail_user_addr != a.avail_user_addr) {
  710. r = -EFAULT;
  711. break;
  712. }
  713. /* Make sure it's safe to cast pointers to vring types. */
  714. BUILD_BUG_ON(__alignof__ *vq->avail > VRING_AVAIL_ALIGN_SIZE);
  715. BUILD_BUG_ON(__alignof__ *vq->used > VRING_USED_ALIGN_SIZE);
  716. if ((a.avail_user_addr & (VRING_AVAIL_ALIGN_SIZE - 1)) ||
  717. (a.used_user_addr & (VRING_USED_ALIGN_SIZE - 1)) ||
  718. (a.log_guest_addr & (sizeof(u64) - 1))) {
  719. r = -EINVAL;
  720. break;
  721. }
  722. /* We only verify access here if backend is configured.
  723. * If it is not, we don't as size might not have been setup.
  724. * We will verify when backend is configured. */
  725. if (vq->private_data) {
  726. if (!vq_access_ok(vq, vq->num,
  727. (void __user *)(unsigned long)a.desc_user_addr,
  728. (void __user *)(unsigned long)a.avail_user_addr,
  729. (void __user *)(unsigned long)a.used_user_addr)) {
  730. r = -EINVAL;
  731. break;
  732. }
  733. /* Also validate log access for used ring if enabled. */
  734. if ((a.flags & (0x1 << VHOST_VRING_F_LOG)) &&
  735. !log_access_ok(vq->log_base, a.log_guest_addr,
  736. sizeof *vq->used +
  737. vq->num * sizeof *vq->used->ring)) {
  738. r = -EINVAL;
  739. break;
  740. }
  741. }
  742. vq->log_used = !!(a.flags & (0x1 << VHOST_VRING_F_LOG));
  743. vq->desc = (void __user *)(unsigned long)a.desc_user_addr;
  744. vq->avail = (void __user *)(unsigned long)a.avail_user_addr;
  745. vq->log_addr = a.log_guest_addr;
  746. vq->used = (void __user *)(unsigned long)a.used_user_addr;
  747. break;
  748. case VHOST_SET_VRING_KICK:
  749. if (copy_from_user(&f, argp, sizeof f)) {
  750. r = -EFAULT;
  751. break;
  752. }
  753. eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
  754. if (IS_ERR(eventfp)) {
  755. r = PTR_ERR(eventfp);
  756. break;
  757. }
  758. if (eventfp != vq->kick) {
  759. pollstop = (filep = vq->kick) != NULL;
  760. pollstart = (vq->kick = eventfp) != NULL;
  761. } else
  762. filep = eventfp;
  763. break;
  764. case VHOST_SET_VRING_CALL:
  765. if (copy_from_user(&f, argp, sizeof f)) {
  766. r = -EFAULT;
  767. break;
  768. }
  769. eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
  770. if (IS_ERR(eventfp)) {
  771. r = PTR_ERR(eventfp);
  772. break;
  773. }
  774. if (eventfp != vq->call) {
  775. filep = vq->call;
  776. ctx = vq->call_ctx;
  777. vq->call = eventfp;
  778. vq->call_ctx = eventfp ?
  779. eventfd_ctx_fileget(eventfp) : NULL;
  780. } else
  781. filep = eventfp;
  782. break;
  783. case VHOST_SET_VRING_ERR:
  784. if (copy_from_user(&f, argp, sizeof f)) {
  785. r = -EFAULT;
  786. break;
  787. }
  788. eventfp = f.fd == -1 ? NULL : eventfd_fget(f.fd);
  789. if (IS_ERR(eventfp)) {
  790. r = PTR_ERR(eventfp);
  791. break;
  792. }
  793. if (eventfp != vq->error) {
  794. filep = vq->error;
  795. vq->error = eventfp;
  796. ctx = vq->error_ctx;
  797. vq->error_ctx = eventfp ?
  798. eventfd_ctx_fileget(eventfp) : NULL;
  799. } else
  800. filep = eventfp;
  801. break;
  802. case VHOST_SET_VRING_ENDIAN:
  803. r = vhost_set_vring_endian(vq, argp);
  804. break;
  805. case VHOST_GET_VRING_ENDIAN:
  806. r = vhost_get_vring_endian(vq, idx, argp);
  807. break;
  808. default:
  809. r = -ENOIOCTLCMD;
  810. }
  811. if (pollstop && vq->handle_kick)
  812. vhost_poll_stop(&vq->poll);
  813. if (ctx)
  814. eventfd_ctx_put(ctx);
  815. if (filep)
  816. fput(filep);
  817. if (pollstart && vq->handle_kick)
  818. r = vhost_poll_start(&vq->poll, vq->kick);
  819. mutex_unlock(&vq->mutex);
  820. if (pollstop && vq->handle_kick)
  821. vhost_poll_flush(&vq->poll);
  822. return r;
  823. }
  824. EXPORT_SYMBOL_GPL(vhost_vring_ioctl);
  825. /* Caller must have device mutex */
  826. long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
  827. {
  828. struct file *eventfp, *filep = NULL;
  829. struct eventfd_ctx *ctx = NULL;
  830. u64 p;
  831. long r;
  832. int i, fd;
  833. /* If you are not the owner, you can become one */
  834. if (ioctl == VHOST_SET_OWNER) {
  835. r = vhost_dev_set_owner(d);
  836. goto done;
  837. }
  838. /* You must be the owner to do anything else */
  839. r = vhost_dev_check_owner(d);
  840. if (r)
  841. goto done;
  842. switch (ioctl) {
  843. case VHOST_SET_MEM_TABLE:
  844. r = vhost_set_memory(d, argp);
  845. break;
  846. case VHOST_SET_LOG_BASE:
  847. if (copy_from_user(&p, argp, sizeof p)) {
  848. r = -EFAULT;
  849. break;
  850. }
  851. if ((u64)(unsigned long)p != p) {
  852. r = -EFAULT;
  853. break;
  854. }
  855. for (i = 0; i < d->nvqs; ++i) {
  856. struct vhost_virtqueue *vq;
  857. void __user *base = (void __user *)(unsigned long)p;
  858. vq = d->vqs[i];
  859. mutex_lock(&vq->mutex);
  860. /* If ring is inactive, will check when it's enabled. */
  861. if (vq->private_data && !vq_log_access_ok(vq, base))
  862. r = -EFAULT;
  863. else
  864. vq->log_base = base;
  865. mutex_unlock(&vq->mutex);
  866. }
  867. break;
  868. case VHOST_SET_LOG_FD:
  869. r = get_user(fd, (int __user *)argp);
  870. if (r < 0)
  871. break;
  872. eventfp = fd == -1 ? NULL : eventfd_fget(fd);
  873. if (IS_ERR(eventfp)) {
  874. r = PTR_ERR(eventfp);
  875. break;
  876. }
  877. if (eventfp != d->log_file) {
  878. filep = d->log_file;
  879. ctx = d->log_ctx;
  880. d->log_ctx = eventfp ?
  881. eventfd_ctx_fileget(eventfp) : NULL;
  882. } else
  883. filep = eventfp;
  884. for (i = 0; i < d->nvqs; ++i) {
  885. mutex_lock(&d->vqs[i]->mutex);
  886. d->vqs[i]->log_ctx = d->log_ctx;
  887. mutex_unlock(&d->vqs[i]->mutex);
  888. }
  889. if (ctx)
  890. eventfd_ctx_put(ctx);
  891. if (filep)
  892. fput(filep);
  893. break;
  894. default:
  895. r = -ENOIOCTLCMD;
  896. break;
  897. }
  898. done:
  899. return r;
  900. }
  901. EXPORT_SYMBOL_GPL(vhost_dev_ioctl);
  902. static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
  903. __u64 addr, __u32 len)
  904. {
  905. const struct vhost_memory_region *reg;
  906. int start = 0, end = mem->nregions;
  907. while (start < end) {
  908. int slot = start + (end - start) / 2;
  909. reg = mem->regions + slot;
  910. if (addr >= reg->guest_phys_addr)
  911. end = slot;
  912. else
  913. start = slot + 1;
  914. }
  915. reg = mem->regions + start;
  916. if (addr >= reg->guest_phys_addr &&
  917. reg->guest_phys_addr + reg->memory_size > addr)
  918. return reg;
  919. return NULL;
  920. }
  921. /* TODO: This is really inefficient. We need something like get_user()
  922. * (instruction directly accesses the data, with an exception table entry
  923. * returning -EFAULT). See Documentation/x86/exception-tables.txt.
  924. */
  925. static int set_bit_to_user(int nr, void __user *addr)
  926. {
  927. unsigned long log = (unsigned long)addr;
  928. struct page *page;
  929. void *base;
  930. int bit = nr + (log % PAGE_SIZE) * 8;
  931. int r;
  932. r = get_user_pages_fast(log, 1, 1, &page);
  933. if (r < 0)
  934. return r;
  935. BUG_ON(r != 1);
  936. base = kmap_atomic(page);
  937. set_bit(bit, base);
  938. kunmap_atomic(base);
  939. set_page_dirty_lock(page);
  940. put_page(page);
  941. return 0;
  942. }
  943. static int log_write(void __user *log_base,
  944. u64 write_address, u64 write_length)
  945. {
  946. u64 write_page = write_address / VHOST_PAGE_SIZE;
  947. int r;
  948. if (!write_length)
  949. return 0;
  950. write_length += write_address % VHOST_PAGE_SIZE;
  951. for (;;) {
  952. u64 base = (u64)(unsigned long)log_base;
  953. u64 log = base + write_page / 8;
  954. int bit = write_page % 8;
  955. if ((u64)(unsigned long)log != log)
  956. return -EFAULT;
  957. r = set_bit_to_user(bit, (void __user *)(unsigned long)log);
  958. if (r < 0)
  959. return r;
  960. if (write_length <= VHOST_PAGE_SIZE)
  961. break;
  962. write_length -= VHOST_PAGE_SIZE;
  963. write_page += 1;
  964. }
  965. return r;
  966. }
  967. int vhost_log_write(struct vhost_virtqueue *vq, struct vhost_log *log,
  968. unsigned int log_num, u64 len)
  969. {
  970. int i, r;
  971. /* Make sure data written is seen before log. */
  972. smp_wmb();
  973. for (i = 0; i < log_num; ++i) {
  974. u64 l = min(log[i].len, len);
  975. r = log_write(vq->log_base, log[i].addr, l);
  976. if (r < 0)
  977. return r;
  978. len -= l;
  979. if (!len) {
  980. if (vq->log_ctx)
  981. eventfd_signal(vq->log_ctx, 1);
  982. return 0;
  983. }
  984. }
  985. /* Length written exceeds what we have stored. This is a bug. */
  986. BUG();
  987. return 0;
  988. }
  989. EXPORT_SYMBOL_GPL(vhost_log_write);
  990. static int vhost_update_used_flags(struct vhost_virtqueue *vq)
  991. {
  992. void __user *used;
  993. if (__put_user(cpu_to_vhost16(vq, vq->used_flags), &vq->used->flags) < 0)
  994. return -EFAULT;
  995. if (unlikely(vq->log_used)) {
  996. /* Make sure the flag is seen before log. */
  997. smp_wmb();
  998. /* Log used flag write. */
  999. used = &vq->used->flags;
  1000. log_write(vq->log_base, vq->log_addr +
  1001. (used - (void __user *)vq->used),
  1002. sizeof vq->used->flags);
  1003. if (vq->log_ctx)
  1004. eventfd_signal(vq->log_ctx, 1);
  1005. }
  1006. return 0;
  1007. }
  1008. static int vhost_update_avail_event(struct vhost_virtqueue *vq, u16 avail_event)
  1009. {
  1010. if (__put_user(cpu_to_vhost16(vq, vq->avail_idx), vhost_avail_event(vq)))
  1011. return -EFAULT;
  1012. if (unlikely(vq->log_used)) {
  1013. void __user *used;
  1014. /* Make sure the event is seen before log. */
  1015. smp_wmb();
  1016. /* Log avail event write */
  1017. used = vhost_avail_event(vq);
  1018. log_write(vq->log_base, vq->log_addr +
  1019. (used - (void __user *)vq->used),
  1020. sizeof *vhost_avail_event(vq));
  1021. if (vq->log_ctx)
  1022. eventfd_signal(vq->log_ctx, 1);
  1023. }
  1024. return 0;
  1025. }
  1026. int vhost_init_used(struct vhost_virtqueue *vq)
  1027. {
  1028. __virtio16 last_used_idx;
  1029. int r;
  1030. if (!vq->private_data) {
  1031. vq->is_le = virtio_legacy_is_little_endian();
  1032. return 0;
  1033. }
  1034. vhost_init_is_le(vq);
  1035. r = vhost_update_used_flags(vq);
  1036. if (r)
  1037. return r;
  1038. vq->signalled_used_valid = false;
  1039. if (!access_ok(VERIFY_READ, &vq->used->idx, sizeof vq->used->idx))
  1040. return -EFAULT;
  1041. r = __get_user(last_used_idx, &vq->used->idx);
  1042. if (r)
  1043. return r;
  1044. vq->last_used_idx = vhost16_to_cpu(vq, last_used_idx);
  1045. return 0;
  1046. }
  1047. EXPORT_SYMBOL_GPL(vhost_init_used);
  1048. static int translate_desc(struct vhost_virtqueue *vq, u64 addr, u32 len,
  1049. struct iovec iov[], int iov_size)
  1050. {
  1051. const struct vhost_memory_region *reg;
  1052. struct vhost_memory *mem;
  1053. struct iovec *_iov;
  1054. u64 s = 0;
  1055. int ret = 0;
  1056. mem = vq->memory;
  1057. while ((u64)len > s) {
  1058. u64 size;
  1059. if (unlikely(ret >= iov_size)) {
  1060. ret = -ENOBUFS;
  1061. break;
  1062. }
  1063. reg = find_region(mem, addr, len);
  1064. if (unlikely(!reg)) {
  1065. ret = -EFAULT;
  1066. break;
  1067. }
  1068. _iov = iov + ret;
  1069. size = reg->memory_size - addr + reg->guest_phys_addr;
  1070. _iov->iov_len = min((u64)len - s, size);
  1071. _iov->iov_base = (void __user *)(unsigned long)
  1072. (reg->userspace_addr + addr - reg->guest_phys_addr);
  1073. s += size;
  1074. addr += size;
  1075. ++ret;
  1076. }
  1077. return ret;
  1078. }
  1079. /* Each buffer in the virtqueues is actually a chain of descriptors. This
  1080. * function returns the next descriptor in the chain,
  1081. * or -1U if we're at the end. */
  1082. static unsigned next_desc(struct vhost_virtqueue *vq, struct vring_desc *desc)
  1083. {
  1084. unsigned int next;
  1085. /* If this descriptor says it doesn't chain, we're done. */
  1086. if (!(desc->flags & cpu_to_vhost16(vq, VRING_DESC_F_NEXT)))
  1087. return -1U;
  1088. /* Check they're not leading us off end of descriptors. */
  1089. next = vhost16_to_cpu(vq, desc->next);
  1090. /* Make sure compiler knows to grab that: we don't want it changing! */
  1091. /* We will use the result as an index in an array, so most
  1092. * architectures only need a compiler barrier here. */
  1093. read_barrier_depends();
  1094. return next;
  1095. }
  1096. static int get_indirect(struct vhost_virtqueue *vq,
  1097. struct iovec iov[], unsigned int iov_size,
  1098. unsigned int *out_num, unsigned int *in_num,
  1099. struct vhost_log *log, unsigned int *log_num,
  1100. struct vring_desc *indirect)
  1101. {
  1102. struct vring_desc desc;
  1103. unsigned int i = 0, count, found = 0;
  1104. u32 len = vhost32_to_cpu(vq, indirect->len);
  1105. struct iov_iter from;
  1106. int ret;
  1107. /* Sanity check */
  1108. if (unlikely(len % sizeof desc)) {
  1109. vq_err(vq, "Invalid length in indirect descriptor: "
  1110. "len 0x%llx not multiple of 0x%zx\n",
  1111. (unsigned long long)len,
  1112. sizeof desc);
  1113. return -EINVAL;
  1114. }
  1115. ret = translate_desc(vq, vhost64_to_cpu(vq, indirect->addr), len, vq->indirect,
  1116. UIO_MAXIOV);
  1117. if (unlikely(ret < 0)) {
  1118. vq_err(vq, "Translation failure %d in indirect.\n", ret);
  1119. return ret;
  1120. }
  1121. iov_iter_init(&from, READ, vq->indirect, ret, len);
  1122. /* We will use the result as an address to read from, so most
  1123. * architectures only need a compiler barrier here. */
  1124. read_barrier_depends();
  1125. count = len / sizeof desc;
  1126. /* Buffers are chained via a 16 bit next field, so
  1127. * we can have at most 2^16 of these. */
  1128. if (unlikely(count > USHRT_MAX + 1)) {
  1129. vq_err(vq, "Indirect buffer length too big: %d\n",
  1130. indirect->len);
  1131. return -E2BIG;
  1132. }
  1133. do {
  1134. unsigned iov_count = *in_num + *out_num;
  1135. if (unlikely(++found > count)) {
  1136. vq_err(vq, "Loop detected: last one at %u "
  1137. "indirect size %u\n",
  1138. i, count);
  1139. return -EINVAL;
  1140. }
  1141. if (unlikely(copy_from_iter(&desc, sizeof(desc), &from) !=
  1142. sizeof(desc))) {
  1143. vq_err(vq, "Failed indirect descriptor: idx %d, %zx\n",
  1144. i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
  1145. return -EINVAL;
  1146. }
  1147. if (unlikely(desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT))) {
  1148. vq_err(vq, "Nested indirect descriptor: idx %d, %zx\n",
  1149. i, (size_t)vhost64_to_cpu(vq, indirect->addr) + i * sizeof desc);
  1150. return -EINVAL;
  1151. }
  1152. ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
  1153. vhost32_to_cpu(vq, desc.len), iov + iov_count,
  1154. iov_size - iov_count);
  1155. if (unlikely(ret < 0)) {
  1156. vq_err(vq, "Translation failure %d indirect idx %d\n",
  1157. ret, i);
  1158. return ret;
  1159. }
  1160. /* If this is an input descriptor, increment that count. */
  1161. if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
  1162. *in_num += ret;
  1163. if (unlikely(log)) {
  1164. log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
  1165. log[*log_num].len = vhost32_to_cpu(vq, desc.len);
  1166. ++*log_num;
  1167. }
  1168. } else {
  1169. /* If it's an output descriptor, they're all supposed
  1170. * to come before any input descriptors. */
  1171. if (unlikely(*in_num)) {
  1172. vq_err(vq, "Indirect descriptor "
  1173. "has out after in: idx %d\n", i);
  1174. return -EINVAL;
  1175. }
  1176. *out_num += ret;
  1177. }
  1178. } while ((i = next_desc(vq, &desc)) != -1);
  1179. return 0;
  1180. }
  1181. /* This looks in the virtqueue and for the first available buffer, and converts
  1182. * it to an iovec for convenient access. Since descriptors consist of some
  1183. * number of output then some number of input descriptors, it's actually two
  1184. * iovecs, but we pack them into one and note how many of each there were.
  1185. *
  1186. * This function returns the descriptor number found, or vq->num (which is
  1187. * never a valid descriptor number) if none was found. A negative code is
  1188. * returned on error. */
  1189. int vhost_get_vq_desc(struct vhost_virtqueue *vq,
  1190. struct iovec iov[], unsigned int iov_size,
  1191. unsigned int *out_num, unsigned int *in_num,
  1192. struct vhost_log *log, unsigned int *log_num)
  1193. {
  1194. struct vring_desc desc;
  1195. unsigned int i, head, found = 0;
  1196. u16 last_avail_idx;
  1197. __virtio16 avail_idx;
  1198. __virtio16 ring_head;
  1199. int ret;
  1200. /* Check it isn't doing very strange things with descriptor numbers. */
  1201. last_avail_idx = vq->last_avail_idx;
  1202. if (unlikely(__get_user(avail_idx, &vq->avail->idx))) {
  1203. vq_err(vq, "Failed to access avail idx at %p\n",
  1204. &vq->avail->idx);
  1205. return -EFAULT;
  1206. }
  1207. vq->avail_idx = vhost16_to_cpu(vq, avail_idx);
  1208. if (unlikely((u16)(vq->avail_idx - last_avail_idx) > vq->num)) {
  1209. vq_err(vq, "Guest moved used index from %u to %u",
  1210. last_avail_idx, vq->avail_idx);
  1211. return -EFAULT;
  1212. }
  1213. /* If there's nothing new since last we looked, return invalid. */
  1214. if (vq->avail_idx == last_avail_idx)
  1215. return vq->num;
  1216. /* Only get avail ring entries after they have been exposed by guest. */
  1217. smp_rmb();
  1218. /* Grab the next descriptor number they're advertising, and increment
  1219. * the index we've seen. */
  1220. if (unlikely(__get_user(ring_head,
  1221. &vq->avail->ring[last_avail_idx % vq->num]))) {
  1222. vq_err(vq, "Failed to read head: idx %d address %p\n",
  1223. last_avail_idx,
  1224. &vq->avail->ring[last_avail_idx % vq->num]);
  1225. return -EFAULT;
  1226. }
  1227. head = vhost16_to_cpu(vq, ring_head);
  1228. /* If their number is silly, that's an error. */
  1229. if (unlikely(head >= vq->num)) {
  1230. vq_err(vq, "Guest says index %u > %u is available",
  1231. head, vq->num);
  1232. return -EINVAL;
  1233. }
  1234. /* When we start there are none of either input nor output. */
  1235. *out_num = *in_num = 0;
  1236. if (unlikely(log))
  1237. *log_num = 0;
  1238. i = head;
  1239. do {
  1240. unsigned iov_count = *in_num + *out_num;
  1241. if (unlikely(i >= vq->num)) {
  1242. vq_err(vq, "Desc index is %u > %u, head = %u",
  1243. i, vq->num, head);
  1244. return -EINVAL;
  1245. }
  1246. if (unlikely(++found > vq->num)) {
  1247. vq_err(vq, "Loop detected: last one at %u "
  1248. "vq size %u head %u\n",
  1249. i, vq->num, head);
  1250. return -EINVAL;
  1251. }
  1252. ret = __copy_from_user(&desc, vq->desc + i, sizeof desc);
  1253. if (unlikely(ret)) {
  1254. vq_err(vq, "Failed to get descriptor: idx %d addr %p\n",
  1255. i, vq->desc + i);
  1256. return -EFAULT;
  1257. }
  1258. if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_INDIRECT)) {
  1259. ret = get_indirect(vq, iov, iov_size,
  1260. out_num, in_num,
  1261. log, log_num, &desc);
  1262. if (unlikely(ret < 0)) {
  1263. vq_err(vq, "Failure detected "
  1264. "in indirect descriptor at idx %d\n", i);
  1265. return ret;
  1266. }
  1267. continue;
  1268. }
  1269. ret = translate_desc(vq, vhost64_to_cpu(vq, desc.addr),
  1270. vhost32_to_cpu(vq, desc.len), iov + iov_count,
  1271. iov_size - iov_count);
  1272. if (unlikely(ret < 0)) {
  1273. vq_err(vq, "Translation failure %d descriptor idx %d\n",
  1274. ret, i);
  1275. return ret;
  1276. }
  1277. if (desc.flags & cpu_to_vhost16(vq, VRING_DESC_F_WRITE)) {
  1278. /* If this is an input descriptor,
  1279. * increment that count. */
  1280. *in_num += ret;
  1281. if (unlikely(log)) {
  1282. log[*log_num].addr = vhost64_to_cpu(vq, desc.addr);
  1283. log[*log_num].len = vhost32_to_cpu(vq, desc.len);
  1284. ++*log_num;
  1285. }
  1286. } else {
  1287. /* If it's an output descriptor, they're all supposed
  1288. * to come before any input descriptors. */
  1289. if (unlikely(*in_num)) {
  1290. vq_err(vq, "Descriptor has out after in: "
  1291. "idx %d\n", i);
  1292. return -EINVAL;
  1293. }
  1294. *out_num += ret;
  1295. }
  1296. } while ((i = next_desc(vq, &desc)) != -1);
  1297. /* On success, increment avail index. */
  1298. vq->last_avail_idx++;
  1299. /* Assume notifications from guest are disabled at this point,
  1300. * if they aren't we would need to update avail_event index. */
  1301. BUG_ON(!(vq->used_flags & VRING_USED_F_NO_NOTIFY));
  1302. return head;
  1303. }
  1304. EXPORT_SYMBOL_GPL(vhost_get_vq_desc);
  1305. /* Reverse the effect of vhost_get_vq_desc. Useful for error handling. */
  1306. void vhost_discard_vq_desc(struct vhost_virtqueue *vq, int n)
  1307. {
  1308. vq->last_avail_idx -= n;
  1309. }
  1310. EXPORT_SYMBOL_GPL(vhost_discard_vq_desc);
  1311. /* After we've used one of their buffers, we tell them about it. We'll then
  1312. * want to notify the guest, using eventfd. */
  1313. int vhost_add_used(struct vhost_virtqueue *vq, unsigned int head, int len)
  1314. {
  1315. struct vring_used_elem heads = {
  1316. cpu_to_vhost32(vq, head),
  1317. cpu_to_vhost32(vq, len)
  1318. };
  1319. return vhost_add_used_n(vq, &heads, 1);
  1320. }
  1321. EXPORT_SYMBOL_GPL(vhost_add_used);
  1322. static int __vhost_add_used_n(struct vhost_virtqueue *vq,
  1323. struct vring_used_elem *heads,
  1324. unsigned count)
  1325. {
  1326. struct vring_used_elem __user *used;
  1327. u16 old, new;
  1328. int start;
  1329. start = vq->last_used_idx % vq->num;
  1330. used = vq->used->ring + start;
  1331. if (count == 1) {
  1332. if (__put_user(heads[0].id, &used->id)) {
  1333. vq_err(vq, "Failed to write used id");
  1334. return -EFAULT;
  1335. }
  1336. if (__put_user(heads[0].len, &used->len)) {
  1337. vq_err(vq, "Failed to write used len");
  1338. return -EFAULT;
  1339. }
  1340. } else if (__copy_to_user(used, heads, count * sizeof *used)) {
  1341. vq_err(vq, "Failed to write used");
  1342. return -EFAULT;
  1343. }
  1344. if (unlikely(vq->log_used)) {
  1345. /* Make sure data is seen before log. */
  1346. smp_wmb();
  1347. /* Log used ring entry write. */
  1348. log_write(vq->log_base,
  1349. vq->log_addr +
  1350. ((void __user *)used - (void __user *)vq->used),
  1351. count * sizeof *used);
  1352. }
  1353. old = vq->last_used_idx;
  1354. new = (vq->last_used_idx += count);
  1355. /* If the driver never bothers to signal in a very long while,
  1356. * used index might wrap around. If that happens, invalidate
  1357. * signalled_used index we stored. TODO: make sure driver
  1358. * signals at least once in 2^16 and remove this. */
  1359. if (unlikely((u16)(new - vq->signalled_used) < (u16)(new - old)))
  1360. vq->signalled_used_valid = false;
  1361. return 0;
  1362. }
  1363. /* After we've used one of their buffers, we tell them about it. We'll then
  1364. * want to notify the guest, using eventfd. */
  1365. int vhost_add_used_n(struct vhost_virtqueue *vq, struct vring_used_elem *heads,
  1366. unsigned count)
  1367. {
  1368. int start, n, r;
  1369. start = vq->last_used_idx % vq->num;
  1370. n = vq->num - start;
  1371. if (n < count) {
  1372. r = __vhost_add_used_n(vq, heads, n);
  1373. if (r < 0)
  1374. return r;
  1375. heads += n;
  1376. count -= n;
  1377. }
  1378. r = __vhost_add_used_n(vq, heads, count);
  1379. /* Make sure buffer is written before we update index. */
  1380. smp_wmb();
  1381. if (__put_user(cpu_to_vhost16(vq, vq->last_used_idx), &vq->used->idx)) {
  1382. vq_err(vq, "Failed to increment used idx");
  1383. return -EFAULT;
  1384. }
  1385. if (unlikely(vq->log_used)) {
  1386. /* Log used index update. */
  1387. log_write(vq->log_base,
  1388. vq->log_addr + offsetof(struct vring_used, idx),
  1389. sizeof vq->used->idx);
  1390. if (vq->log_ctx)
  1391. eventfd_signal(vq->log_ctx, 1);
  1392. }
  1393. return r;
  1394. }
  1395. EXPORT_SYMBOL_GPL(vhost_add_used_n);
  1396. static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
  1397. {
  1398. __u16 old, new;
  1399. __virtio16 event;
  1400. bool v;
  1401. /* Flush out used index updates. This is paired
  1402. * with the barrier that the Guest executes when enabling
  1403. * interrupts. */
  1404. smp_mb();
  1405. if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) &&
  1406. unlikely(vq->avail_idx == vq->last_avail_idx))
  1407. return true;
  1408. if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
  1409. __virtio16 flags;
  1410. if (__get_user(flags, &vq->avail->flags)) {
  1411. vq_err(vq, "Failed to get flags");
  1412. return true;
  1413. }
  1414. return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT));
  1415. }
  1416. old = vq->signalled_used;
  1417. v = vq->signalled_used_valid;
  1418. new = vq->signalled_used = vq->last_used_idx;
  1419. vq->signalled_used_valid = true;
  1420. if (unlikely(!v))
  1421. return true;
  1422. if (__get_user(event, vhost_used_event(vq))) {
  1423. vq_err(vq, "Failed to get used event idx");
  1424. return true;
  1425. }
  1426. return vring_need_event(vhost16_to_cpu(vq, event), new, old);
  1427. }
  1428. /* This actually signals the guest, using eventfd. */
  1429. void vhost_signal(struct vhost_dev *dev, struct vhost_virtqueue *vq)
  1430. {
  1431. /* Signal the Guest tell them we used something up. */
  1432. if (vq->call_ctx && vhost_notify(dev, vq))
  1433. eventfd_signal(vq->call_ctx, 1);
  1434. }
  1435. EXPORT_SYMBOL_GPL(vhost_signal);
  1436. /* And here's the combo meal deal. Supersize me! */
  1437. void vhost_add_used_and_signal(struct vhost_dev *dev,
  1438. struct vhost_virtqueue *vq,
  1439. unsigned int head, int len)
  1440. {
  1441. vhost_add_used(vq, head, len);
  1442. vhost_signal(dev, vq);
  1443. }
  1444. EXPORT_SYMBOL_GPL(vhost_add_used_and_signal);
  1445. /* multi-buffer version of vhost_add_used_and_signal */
  1446. void vhost_add_used_and_signal_n(struct vhost_dev *dev,
  1447. struct vhost_virtqueue *vq,
  1448. struct vring_used_elem *heads, unsigned count)
  1449. {
  1450. vhost_add_used_n(vq, heads, count);
  1451. vhost_signal(dev, vq);
  1452. }
  1453. EXPORT_SYMBOL_GPL(vhost_add_used_and_signal_n);
  1454. /* OK, now we need to know about added descriptors. */
  1455. bool vhost_enable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
  1456. {
  1457. __virtio16 avail_idx;
  1458. int r;
  1459. if (!(vq->used_flags & VRING_USED_F_NO_NOTIFY))
  1460. return false;
  1461. vq->used_flags &= ~VRING_USED_F_NO_NOTIFY;
  1462. if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
  1463. r = vhost_update_used_flags(vq);
  1464. if (r) {
  1465. vq_err(vq, "Failed to enable notification at %p: %d\n",
  1466. &vq->used->flags, r);
  1467. return false;
  1468. }
  1469. } else {
  1470. r = vhost_update_avail_event(vq, vq->avail_idx);
  1471. if (r) {
  1472. vq_err(vq, "Failed to update avail event index at %p: %d\n",
  1473. vhost_avail_event(vq), r);
  1474. return false;
  1475. }
  1476. }
  1477. /* They could have slipped one in as we were doing that: make
  1478. * sure it's written, then check again. */
  1479. smp_mb();
  1480. r = __get_user(avail_idx, &vq->avail->idx);
  1481. if (r) {
  1482. vq_err(vq, "Failed to check avail idx at %p: %d\n",
  1483. &vq->avail->idx, r);
  1484. return false;
  1485. }
  1486. return vhost16_to_cpu(vq, avail_idx) != vq->avail_idx;
  1487. }
  1488. EXPORT_SYMBOL_GPL(vhost_enable_notify);
  1489. /* We don't need to be notified again. */
  1490. void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
  1491. {
  1492. int r;
  1493. if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
  1494. return;
  1495. vq->used_flags |= VRING_USED_F_NO_NOTIFY;
  1496. if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
  1497. r = vhost_update_used_flags(vq);
  1498. if (r)
  1499. vq_err(vq, "Failed to enable notification at %p: %d\n",
  1500. &vq->used->flags, r);
  1501. }
  1502. }
  1503. EXPORT_SYMBOL_GPL(vhost_disable_notify);
  1504. static int __init vhost_init(void)
  1505. {
  1506. return 0;
  1507. }
  1508. static void __exit vhost_exit(void)
  1509. {
  1510. }
  1511. module_init(vhost_init);
  1512. module_exit(vhost_exit);
  1513. MODULE_VERSION("0.0.1");
  1514. MODULE_LICENSE("GPL v2");
  1515. MODULE_AUTHOR("Michael S. Tsirkin");
  1516. MODULE_DESCRIPTION("Host kernel accelerator for virtio");