vfio_main.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * VFIO core
  4. *
  5. * Copyright (C) 2012 Red Hat, Inc. All rights reserved.
  6. * Author: Alex Williamson <alex.williamson@redhat.com>
  7. *
  8. * Derived from original vfio:
  9. * Copyright 2010 Cisco Systems, Inc. All rights reserved.
  10. * Author: Tom Lyon, pugs@cisco.com
  11. */
  12. #include <linux/cdev.h>
  13. #include <linux/compat.h>
  14. #include <linux/device.h>
  15. #include <linux/fs.h>
  16. #include <linux/idr.h>
  17. #include <linux/iommu.h>
  18. #if IS_ENABLED(CONFIG_KVM)
  19. #include <linux/kvm_host.h>
  20. #endif
  21. #include <linux/list.h>
  22. #include <linux/miscdevice.h>
  23. #include <linux/module.h>
  24. #include <linux/mount.h>
  25. #include <linux/mutex.h>
  26. #include <linux/pci.h>
  27. #include <linux/pseudo_fs.h>
  28. #include <linux/rwsem.h>
  29. #include <linux/sched.h>
  30. #include <linux/slab.h>
  31. #include <linux/stat.h>
  32. #include <linux/string.h>
  33. #include <linux/uaccess.h>
  34. #include <linux/vfio.h>
  35. #include <linux/wait.h>
  36. #include <linux/sched/signal.h>
  37. #include <linux/pm_runtime.h>
  38. #include <linux/interval_tree.h>
  39. #include <linux/iova_bitmap.h>
  40. #include <linux/iommufd.h>
  41. #include "vfio.h"
  42. #define DRIVER_VERSION "0.3"
  43. #define DRIVER_AUTHOR "Alex Williamson <alex.williamson@redhat.com>"
  44. #define DRIVER_DESC "VFIO - User Level meta-driver"
  45. #define VFIO_MAGIC 0x5646494f /* "VFIO" */
  46. static struct vfio {
  47. struct class *device_class;
  48. struct ida device_ida;
  49. struct vfsmount *vfs_mount;
  50. int fs_count;
  51. } vfio;
  52. #ifdef CONFIG_VFIO_NOIOMMU
  53. bool vfio_noiommu __read_mostly;
  54. module_param_named(enable_unsafe_noiommu_mode,
  55. vfio_noiommu, bool, S_IRUGO | S_IWUSR);
  56. MODULE_PARM_DESC(enable_unsafe_noiommu_mode, "Enable UNSAFE, no-IOMMU mode. This mode provides no device isolation, no DMA translation, no host kernel protection, cannot be used for device assignment to virtual machines, requires RAWIO permissions, and will taint the kernel. If you do not know what this is for, step away. (default: false)");
  57. #endif
  58. static DEFINE_XARRAY(vfio_device_set_xa);
  59. int vfio_assign_device_set(struct vfio_device *device, void *set_id)
  60. {
  61. unsigned long idx = (unsigned long)set_id;
  62. struct vfio_device_set *new_dev_set;
  63. struct vfio_device_set *dev_set;
  64. if (WARN_ON(!set_id))
  65. return -EINVAL;
  66. /*
  67. * Atomically acquire a singleton object in the xarray for this set_id
  68. */
  69. xa_lock(&vfio_device_set_xa);
  70. dev_set = xa_load(&vfio_device_set_xa, idx);
  71. if (dev_set)
  72. goto found_get_ref;
  73. xa_unlock(&vfio_device_set_xa);
  74. new_dev_set = kzalloc(sizeof(*new_dev_set), GFP_KERNEL);
  75. if (!new_dev_set)
  76. return -ENOMEM;
  77. mutex_init(&new_dev_set->lock);
  78. INIT_LIST_HEAD(&new_dev_set->device_list);
  79. new_dev_set->set_id = set_id;
  80. xa_lock(&vfio_device_set_xa);
  81. dev_set = __xa_cmpxchg(&vfio_device_set_xa, idx, NULL, new_dev_set,
  82. GFP_KERNEL);
  83. if (!dev_set) {
  84. dev_set = new_dev_set;
  85. goto found_get_ref;
  86. }
  87. kfree(new_dev_set);
  88. if (xa_is_err(dev_set)) {
  89. xa_unlock(&vfio_device_set_xa);
  90. return xa_err(dev_set);
  91. }
  92. found_get_ref:
  93. dev_set->device_count++;
  94. xa_unlock(&vfio_device_set_xa);
  95. mutex_lock(&dev_set->lock);
  96. device->dev_set = dev_set;
  97. list_add_tail(&device->dev_set_list, &dev_set->device_list);
  98. mutex_unlock(&dev_set->lock);
  99. return 0;
  100. }
  101. EXPORT_SYMBOL_GPL(vfio_assign_device_set);
  102. static void vfio_release_device_set(struct vfio_device *device)
  103. {
  104. struct vfio_device_set *dev_set = device->dev_set;
  105. if (!dev_set)
  106. return;
  107. mutex_lock(&dev_set->lock);
  108. list_del(&device->dev_set_list);
  109. mutex_unlock(&dev_set->lock);
  110. xa_lock(&vfio_device_set_xa);
  111. if (!--dev_set->device_count) {
  112. __xa_erase(&vfio_device_set_xa,
  113. (unsigned long)dev_set->set_id);
  114. mutex_destroy(&dev_set->lock);
  115. kfree(dev_set);
  116. }
  117. xa_unlock(&vfio_device_set_xa);
  118. }
  119. unsigned int vfio_device_set_open_count(struct vfio_device_set *dev_set)
  120. {
  121. struct vfio_device *cur;
  122. unsigned int open_count = 0;
  123. lockdep_assert_held(&dev_set->lock);
  124. list_for_each_entry(cur, &dev_set->device_list, dev_set_list)
  125. open_count += cur->open_count;
  126. return open_count;
  127. }
  128. EXPORT_SYMBOL_GPL(vfio_device_set_open_count);
  129. struct vfio_device *
  130. vfio_find_device_in_devset(struct vfio_device_set *dev_set,
  131. struct device *dev)
  132. {
  133. struct vfio_device *cur;
  134. lockdep_assert_held(&dev_set->lock);
  135. list_for_each_entry(cur, &dev_set->device_list, dev_set_list)
  136. if (cur->dev == dev)
  137. return cur;
  138. return NULL;
  139. }
  140. EXPORT_SYMBOL_GPL(vfio_find_device_in_devset);
  141. /*
  142. * Device objects - create, release, get, put, search
  143. */
  144. /* Device reference always implies a group reference */
  145. void vfio_device_put_registration(struct vfio_device *device)
  146. {
  147. if (refcount_dec_and_test(&device->refcount))
  148. complete(&device->comp);
  149. }
  150. bool vfio_device_try_get_registration(struct vfio_device *device)
  151. {
  152. return refcount_inc_not_zero(&device->refcount);
  153. }
  154. /*
  155. * VFIO driver API
  156. */
  157. /* Release helper called by vfio_put_device() */
  158. static void vfio_device_release(struct device *dev)
  159. {
  160. struct vfio_device *device =
  161. container_of(dev, struct vfio_device, device);
  162. vfio_release_device_set(device);
  163. ida_free(&vfio.device_ida, device->index);
  164. if (device->ops->release)
  165. device->ops->release(device);
  166. iput(device->inode);
  167. simple_release_fs(&vfio.vfs_mount, &vfio.fs_count);
  168. kvfree(device);
  169. }
  170. static int vfio_init_device(struct vfio_device *device, struct device *dev,
  171. const struct vfio_device_ops *ops);
  172. /*
  173. * Allocate and initialize vfio_device so it can be registered to vfio
  174. * core.
  175. *
  176. * Drivers should use the wrapper vfio_alloc_device() for allocation.
  177. * @size is the size of the structure to be allocated, including any
  178. * private data used by the driver.
  179. *
  180. * Driver may provide an @init callback to cover device private data.
  181. *
  182. * Use vfio_put_device() to release the structure after success return.
  183. */
  184. struct vfio_device *_vfio_alloc_device(size_t size, struct device *dev,
  185. const struct vfio_device_ops *ops)
  186. {
  187. struct vfio_device *device;
  188. int ret;
  189. if (WARN_ON(size < sizeof(struct vfio_device)))
  190. return ERR_PTR(-EINVAL);
  191. device = kvzalloc(size, GFP_KERNEL);
  192. if (!device)
  193. return ERR_PTR(-ENOMEM);
  194. ret = vfio_init_device(device, dev, ops);
  195. if (ret)
  196. goto out_free;
  197. return device;
  198. out_free:
  199. kvfree(device);
  200. return ERR_PTR(ret);
  201. }
  202. EXPORT_SYMBOL_GPL(_vfio_alloc_device);
  203. static int vfio_fs_init_fs_context(struct fs_context *fc)
  204. {
  205. return init_pseudo(fc, VFIO_MAGIC) ? 0 : -ENOMEM;
  206. }
  207. static struct file_system_type vfio_fs_type = {
  208. .name = "vfio",
  209. .owner = THIS_MODULE,
  210. .init_fs_context = vfio_fs_init_fs_context,
  211. .kill_sb = kill_anon_super,
  212. };
  213. static struct inode *vfio_fs_inode_new(void)
  214. {
  215. struct inode *inode;
  216. int ret;
  217. ret = simple_pin_fs(&vfio_fs_type, &vfio.vfs_mount, &vfio.fs_count);
  218. if (ret)
  219. return ERR_PTR(ret);
  220. inode = alloc_anon_inode(vfio.vfs_mount->mnt_sb);
  221. if (IS_ERR(inode))
  222. simple_release_fs(&vfio.vfs_mount, &vfio.fs_count);
  223. return inode;
  224. }
  225. /*
  226. * Initialize a vfio_device so it can be registered to vfio core.
  227. */
  228. static int vfio_init_device(struct vfio_device *device, struct device *dev,
  229. const struct vfio_device_ops *ops)
  230. {
  231. int ret;
  232. ret = ida_alloc_max(&vfio.device_ida, MINORMASK, GFP_KERNEL);
  233. if (ret < 0) {
  234. dev_dbg(dev, "Error to alloc index\n");
  235. return ret;
  236. }
  237. device->index = ret;
  238. init_completion(&device->comp);
  239. device->dev = dev;
  240. device->ops = ops;
  241. device->inode = vfio_fs_inode_new();
  242. if (IS_ERR(device->inode)) {
  243. ret = PTR_ERR(device->inode);
  244. goto out_inode;
  245. }
  246. if (ops->init) {
  247. ret = ops->init(device);
  248. if (ret)
  249. goto out_uninit;
  250. }
  251. device_initialize(&device->device);
  252. device->device.release = vfio_device_release;
  253. device->device.class = vfio.device_class;
  254. device->device.parent = device->dev;
  255. return 0;
  256. out_uninit:
  257. iput(device->inode);
  258. simple_release_fs(&vfio.vfs_mount, &vfio.fs_count);
  259. out_inode:
  260. vfio_release_device_set(device);
  261. ida_free(&vfio.device_ida, device->index);
  262. return ret;
  263. }
  264. static int __vfio_register_dev(struct vfio_device *device,
  265. enum vfio_group_type type)
  266. {
  267. int ret;
  268. if (WARN_ON(IS_ENABLED(CONFIG_IOMMUFD) &&
  269. (!device->ops->bind_iommufd ||
  270. !device->ops->unbind_iommufd ||
  271. !device->ops->attach_ioas ||
  272. !device->ops->detach_ioas)))
  273. return -EINVAL;
  274. /*
  275. * If the driver doesn't specify a set then the device is added to a
  276. * singleton set just for itself.
  277. */
  278. if (!device->dev_set)
  279. vfio_assign_device_set(device, device);
  280. ret = dev_set_name(&device->device, "vfio%d", device->index);
  281. if (ret)
  282. return ret;
  283. ret = vfio_device_set_group(device, type);
  284. if (ret)
  285. return ret;
  286. /*
  287. * VFIO always sets IOMMU_CACHE because we offer no way for userspace to
  288. * restore cache coherency. It has to be checked here because it is only
  289. * valid for cases where we are using iommu groups.
  290. */
  291. if (type == VFIO_IOMMU && !vfio_device_is_noiommu(device) &&
  292. !device_iommu_capable(device->dev, IOMMU_CAP_CACHE_COHERENCY)) {
  293. ret = -EINVAL;
  294. goto err_out;
  295. }
  296. ret = vfio_device_add(device);
  297. if (ret)
  298. goto err_out;
  299. /* Refcounting can't start until the driver calls register */
  300. refcount_set(&device->refcount, 1);
  301. vfio_device_group_register(device);
  302. vfio_device_debugfs_init(device);
  303. return 0;
  304. err_out:
  305. vfio_device_remove_group(device);
  306. return ret;
  307. }
  308. int vfio_register_group_dev(struct vfio_device *device)
  309. {
  310. return __vfio_register_dev(device, VFIO_IOMMU);
  311. }
  312. EXPORT_SYMBOL_GPL(vfio_register_group_dev);
  313. /*
  314. * Register a virtual device without IOMMU backing. The user of this
  315. * device must not be able to directly trigger unmediated DMA.
  316. */
  317. int vfio_register_emulated_iommu_dev(struct vfio_device *device)
  318. {
  319. return __vfio_register_dev(device, VFIO_EMULATED_IOMMU);
  320. }
  321. EXPORT_SYMBOL_GPL(vfio_register_emulated_iommu_dev);
  322. /*
  323. * Decrement the device reference count and wait for the device to be
  324. * removed. Open file descriptors for the device... */
  325. void vfio_unregister_group_dev(struct vfio_device *device)
  326. {
  327. unsigned int i = 0;
  328. bool interrupted = false;
  329. long rc;
  330. /*
  331. * Prevent new device opened by userspace via the
  332. * VFIO_GROUP_GET_DEVICE_FD in the group path.
  333. */
  334. vfio_device_group_unregister(device);
  335. /*
  336. * Balances vfio_device_add() in register path, also prevents
  337. * new device opened by userspace in the cdev path.
  338. */
  339. vfio_device_del(device);
  340. vfio_device_put_registration(device);
  341. rc = try_wait_for_completion(&device->comp);
  342. while (rc <= 0) {
  343. if (device->ops->request)
  344. device->ops->request(device, i++);
  345. if (interrupted) {
  346. rc = wait_for_completion_timeout(&device->comp,
  347. HZ * 10);
  348. } else {
  349. rc = wait_for_completion_interruptible_timeout(
  350. &device->comp, HZ * 10);
  351. if (rc < 0) {
  352. interrupted = true;
  353. dev_warn(device->dev,
  354. "Device is currently in use, task"
  355. " \"%s\" (%d) "
  356. "blocked until device is released",
  357. current->comm, task_pid_nr(current));
  358. }
  359. }
  360. }
  361. vfio_device_debugfs_exit(device);
  362. /* Balances vfio_device_set_group in register path */
  363. vfio_device_remove_group(device);
  364. }
  365. EXPORT_SYMBOL_GPL(vfio_unregister_group_dev);
  366. #if IS_ENABLED(CONFIG_KVM)
  367. void vfio_device_get_kvm_safe(struct vfio_device *device, struct kvm *kvm)
  368. {
  369. void (*pfn)(struct kvm *kvm);
  370. bool (*fn)(struct kvm *kvm);
  371. bool ret;
  372. lockdep_assert_held(&device->dev_set->lock);
  373. if (!kvm)
  374. return;
  375. pfn = symbol_get(kvm_put_kvm);
  376. if (WARN_ON(!pfn))
  377. return;
  378. fn = symbol_get(kvm_get_kvm_safe);
  379. if (WARN_ON(!fn)) {
  380. symbol_put(kvm_put_kvm);
  381. return;
  382. }
  383. ret = fn(kvm);
  384. symbol_put(kvm_get_kvm_safe);
  385. if (!ret) {
  386. symbol_put(kvm_put_kvm);
  387. return;
  388. }
  389. device->put_kvm = pfn;
  390. device->kvm = kvm;
  391. }
  392. void vfio_device_put_kvm(struct vfio_device *device)
  393. {
  394. lockdep_assert_held(&device->dev_set->lock);
  395. if (!device->kvm)
  396. return;
  397. if (WARN_ON(!device->put_kvm))
  398. goto clear;
  399. device->put_kvm(device->kvm);
  400. device->put_kvm = NULL;
  401. symbol_put(kvm_put_kvm);
  402. clear:
  403. device->kvm = NULL;
  404. }
  405. #endif
  406. /* true if the vfio_device has open_device() called but not close_device() */
  407. static bool vfio_assert_device_open(struct vfio_device *device)
  408. {
  409. return !WARN_ON_ONCE(!READ_ONCE(device->open_count));
  410. }
  411. struct vfio_device_file *
  412. vfio_allocate_device_file(struct vfio_device *device)
  413. {
  414. struct vfio_device_file *df;
  415. df = kzalloc(sizeof(*df), GFP_KERNEL_ACCOUNT);
  416. if (!df)
  417. return ERR_PTR(-ENOMEM);
  418. df->device = device;
  419. spin_lock_init(&df->kvm_ref_lock);
  420. return df;
  421. }
  422. static int vfio_df_device_first_open(struct vfio_device_file *df)
  423. {
  424. struct vfio_device *device = df->device;
  425. struct iommufd_ctx *iommufd = df->iommufd;
  426. int ret;
  427. lockdep_assert_held(&device->dev_set->lock);
  428. if (!try_module_get(device->dev->driver->owner))
  429. return -ENODEV;
  430. if (iommufd)
  431. ret = vfio_df_iommufd_bind(df);
  432. else
  433. ret = vfio_device_group_use_iommu(device);
  434. if (ret)
  435. goto err_module_put;
  436. if (device->ops->open_device) {
  437. ret = device->ops->open_device(device);
  438. if (ret)
  439. goto err_unuse_iommu;
  440. }
  441. return 0;
  442. err_unuse_iommu:
  443. if (iommufd)
  444. vfio_df_iommufd_unbind(df);
  445. else
  446. vfio_device_group_unuse_iommu(device);
  447. err_module_put:
  448. module_put(device->dev->driver->owner);
  449. return ret;
  450. }
  451. static void vfio_df_device_last_close(struct vfio_device_file *df)
  452. {
  453. struct vfio_device *device = df->device;
  454. struct iommufd_ctx *iommufd = df->iommufd;
  455. lockdep_assert_held(&device->dev_set->lock);
  456. if (device->ops->close_device)
  457. device->ops->close_device(device);
  458. if (iommufd)
  459. vfio_df_iommufd_unbind(df);
  460. else
  461. vfio_device_group_unuse_iommu(device);
  462. module_put(device->dev->driver->owner);
  463. }
  464. int vfio_df_open(struct vfio_device_file *df)
  465. {
  466. struct vfio_device *device = df->device;
  467. int ret = 0;
  468. lockdep_assert_held(&device->dev_set->lock);
  469. /*
  470. * Only the group path allows the device to be opened multiple
  471. * times. The device cdev path doesn't have a secure way for it.
  472. */
  473. if (device->open_count != 0 && !df->group)
  474. return -EINVAL;
  475. device->open_count++;
  476. if (device->open_count == 1) {
  477. ret = vfio_df_device_first_open(df);
  478. if (ret)
  479. device->open_count--;
  480. }
  481. return ret;
  482. }
  483. void vfio_df_close(struct vfio_device_file *df)
  484. {
  485. struct vfio_device *device = df->device;
  486. lockdep_assert_held(&device->dev_set->lock);
  487. vfio_assert_device_open(device);
  488. if (device->open_count == 1)
  489. vfio_df_device_last_close(df);
  490. device->open_count--;
  491. }
  492. /*
  493. * Wrapper around pm_runtime_resume_and_get().
  494. * Return error code on failure or 0 on success.
  495. */
  496. static inline int vfio_device_pm_runtime_get(struct vfio_device *device)
  497. {
  498. struct device *dev = device->dev;
  499. if (dev->driver && dev->driver->pm) {
  500. int ret;
  501. ret = pm_runtime_resume_and_get(dev);
  502. if (ret) {
  503. dev_info_ratelimited(dev,
  504. "vfio: runtime resume failed %d\n", ret);
  505. return -EIO;
  506. }
  507. }
  508. return 0;
  509. }
  510. /*
  511. * Wrapper around pm_runtime_put().
  512. */
  513. static inline void vfio_device_pm_runtime_put(struct vfio_device *device)
  514. {
  515. struct device *dev = device->dev;
  516. if (dev->driver && dev->driver->pm)
  517. pm_runtime_put(dev);
  518. }
  519. /*
  520. * VFIO Device fd
  521. */
  522. static int vfio_device_fops_release(struct inode *inode, struct file *filep)
  523. {
  524. struct vfio_device_file *df = filep->private_data;
  525. struct vfio_device *device = df->device;
  526. if (df->group)
  527. vfio_df_group_close(df);
  528. else
  529. vfio_df_unbind_iommufd(df);
  530. vfio_device_put_registration(device);
  531. kfree(df);
  532. return 0;
  533. }
  534. /*
  535. * vfio_mig_get_next_state - Compute the next step in the FSM
  536. * @cur_fsm - The current state the device is in
  537. * @new_fsm - The target state to reach
  538. * @next_fsm - Pointer to the next step to get to new_fsm
  539. *
  540. * Return 0 upon success, otherwise -errno
  541. * Upon success the next step in the state progression between cur_fsm and
  542. * new_fsm will be set in next_fsm.
  543. *
  544. * This breaks down requests for combination transitions into smaller steps and
  545. * returns the next step to get to new_fsm. The function may need to be called
  546. * multiple times before reaching new_fsm.
  547. *
  548. */
  549. int vfio_mig_get_next_state(struct vfio_device *device,
  550. enum vfio_device_mig_state cur_fsm,
  551. enum vfio_device_mig_state new_fsm,
  552. enum vfio_device_mig_state *next_fsm)
  553. {
  554. enum { VFIO_DEVICE_NUM_STATES = VFIO_DEVICE_STATE_PRE_COPY_P2P + 1 };
  555. /*
  556. * The coding in this table requires the driver to implement the
  557. * following FSM arcs:
  558. * RESUMING -> STOP
  559. * STOP -> RESUMING
  560. * STOP -> STOP_COPY
  561. * STOP_COPY -> STOP
  562. *
  563. * If P2P is supported then the driver must also implement these FSM
  564. * arcs:
  565. * RUNNING -> RUNNING_P2P
  566. * RUNNING_P2P -> RUNNING
  567. * RUNNING_P2P -> STOP
  568. * STOP -> RUNNING_P2P
  569. *
  570. * If precopy is supported then the driver must support these additional
  571. * FSM arcs:
  572. * RUNNING -> PRE_COPY
  573. * PRE_COPY -> RUNNING
  574. * PRE_COPY -> STOP_COPY
  575. * However, if precopy and P2P are supported together then the driver
  576. * must support these additional arcs beyond the P2P arcs above:
  577. * PRE_COPY -> RUNNING
  578. * PRE_COPY -> PRE_COPY_P2P
  579. * PRE_COPY_P2P -> PRE_COPY
  580. * PRE_COPY_P2P -> RUNNING_P2P
  581. * PRE_COPY_P2P -> STOP_COPY
  582. * RUNNING -> PRE_COPY
  583. * RUNNING_P2P -> PRE_COPY_P2P
  584. *
  585. * Without P2P and precopy the driver must implement:
  586. * RUNNING -> STOP
  587. * STOP -> RUNNING
  588. *
  589. * The coding will step through multiple states for some combination
  590. * transitions; if all optional features are supported, this means the
  591. * following ones:
  592. * PRE_COPY -> PRE_COPY_P2P -> STOP_COPY
  593. * PRE_COPY -> RUNNING -> RUNNING_P2P
  594. * PRE_COPY -> RUNNING -> RUNNING_P2P -> STOP
  595. * PRE_COPY -> RUNNING -> RUNNING_P2P -> STOP -> RESUMING
  596. * PRE_COPY_P2P -> RUNNING_P2P -> RUNNING
  597. * PRE_COPY_P2P -> RUNNING_P2P -> STOP
  598. * PRE_COPY_P2P -> RUNNING_P2P -> STOP -> RESUMING
  599. * RESUMING -> STOP -> RUNNING_P2P
  600. * RESUMING -> STOP -> RUNNING_P2P -> PRE_COPY_P2P
  601. * RESUMING -> STOP -> RUNNING_P2P -> RUNNING
  602. * RESUMING -> STOP -> RUNNING_P2P -> RUNNING -> PRE_COPY
  603. * RESUMING -> STOP -> STOP_COPY
  604. * RUNNING -> RUNNING_P2P -> PRE_COPY_P2P
  605. * RUNNING -> RUNNING_P2P -> STOP
  606. * RUNNING -> RUNNING_P2P -> STOP -> RESUMING
  607. * RUNNING -> RUNNING_P2P -> STOP -> STOP_COPY
  608. * RUNNING_P2P -> RUNNING -> PRE_COPY
  609. * RUNNING_P2P -> STOP -> RESUMING
  610. * RUNNING_P2P -> STOP -> STOP_COPY
  611. * STOP -> RUNNING_P2P -> PRE_COPY_P2P
  612. * STOP -> RUNNING_P2P -> RUNNING
  613. * STOP -> RUNNING_P2P -> RUNNING -> PRE_COPY
  614. * STOP_COPY -> STOP -> RESUMING
  615. * STOP_COPY -> STOP -> RUNNING_P2P
  616. * STOP_COPY -> STOP -> RUNNING_P2P -> RUNNING
  617. *
  618. * The following transitions are blocked:
  619. * STOP_COPY -> PRE_COPY
  620. * STOP_COPY -> PRE_COPY_P2P
  621. */
  622. static const u8 vfio_from_fsm_table[VFIO_DEVICE_NUM_STATES][VFIO_DEVICE_NUM_STATES] = {
  623. [VFIO_DEVICE_STATE_STOP] = {
  624. [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_STOP,
  625. [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_RUNNING_P2P,
  626. [VFIO_DEVICE_STATE_PRE_COPY] = VFIO_DEVICE_STATE_RUNNING_P2P,
  627. [VFIO_DEVICE_STATE_PRE_COPY_P2P] = VFIO_DEVICE_STATE_RUNNING_P2P,
  628. [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP_COPY,
  629. [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_RESUMING,
  630. [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_RUNNING_P2P,
  631. [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
  632. },
  633. [VFIO_DEVICE_STATE_RUNNING] = {
  634. [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_RUNNING_P2P,
  635. [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_RUNNING,
  636. [VFIO_DEVICE_STATE_PRE_COPY] = VFIO_DEVICE_STATE_PRE_COPY,
  637. [VFIO_DEVICE_STATE_PRE_COPY_P2P] = VFIO_DEVICE_STATE_RUNNING_P2P,
  638. [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_RUNNING_P2P,
  639. [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_RUNNING_P2P,
  640. [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_RUNNING_P2P,
  641. [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
  642. },
  643. [VFIO_DEVICE_STATE_PRE_COPY] = {
  644. [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_RUNNING,
  645. [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_RUNNING,
  646. [VFIO_DEVICE_STATE_PRE_COPY] = VFIO_DEVICE_STATE_PRE_COPY,
  647. [VFIO_DEVICE_STATE_PRE_COPY_P2P] = VFIO_DEVICE_STATE_PRE_COPY_P2P,
  648. [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_PRE_COPY_P2P,
  649. [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_RUNNING,
  650. [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_RUNNING,
  651. [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
  652. },
  653. [VFIO_DEVICE_STATE_PRE_COPY_P2P] = {
  654. [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_RUNNING_P2P,
  655. [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_RUNNING_P2P,
  656. [VFIO_DEVICE_STATE_PRE_COPY] = VFIO_DEVICE_STATE_PRE_COPY,
  657. [VFIO_DEVICE_STATE_PRE_COPY_P2P] = VFIO_DEVICE_STATE_PRE_COPY_P2P,
  658. [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP_COPY,
  659. [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_RUNNING_P2P,
  660. [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_RUNNING_P2P,
  661. [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
  662. },
  663. [VFIO_DEVICE_STATE_STOP_COPY] = {
  664. [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_STOP,
  665. [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_STOP,
  666. [VFIO_DEVICE_STATE_PRE_COPY] = VFIO_DEVICE_STATE_ERROR,
  667. [VFIO_DEVICE_STATE_PRE_COPY_P2P] = VFIO_DEVICE_STATE_ERROR,
  668. [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP_COPY,
  669. [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_STOP,
  670. [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_STOP,
  671. [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
  672. },
  673. [VFIO_DEVICE_STATE_RESUMING] = {
  674. [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_STOP,
  675. [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_STOP,
  676. [VFIO_DEVICE_STATE_PRE_COPY] = VFIO_DEVICE_STATE_STOP,
  677. [VFIO_DEVICE_STATE_PRE_COPY_P2P] = VFIO_DEVICE_STATE_STOP,
  678. [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP,
  679. [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_RESUMING,
  680. [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_STOP,
  681. [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
  682. },
  683. [VFIO_DEVICE_STATE_RUNNING_P2P] = {
  684. [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_STOP,
  685. [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_RUNNING,
  686. [VFIO_DEVICE_STATE_PRE_COPY] = VFIO_DEVICE_STATE_RUNNING,
  687. [VFIO_DEVICE_STATE_PRE_COPY_P2P] = VFIO_DEVICE_STATE_PRE_COPY_P2P,
  688. [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP,
  689. [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_STOP,
  690. [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_RUNNING_P2P,
  691. [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
  692. },
  693. [VFIO_DEVICE_STATE_ERROR] = {
  694. [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_ERROR,
  695. [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_ERROR,
  696. [VFIO_DEVICE_STATE_PRE_COPY] = VFIO_DEVICE_STATE_ERROR,
  697. [VFIO_DEVICE_STATE_PRE_COPY_P2P] = VFIO_DEVICE_STATE_ERROR,
  698. [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_ERROR,
  699. [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_ERROR,
  700. [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_ERROR,
  701. [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
  702. },
  703. };
  704. static const unsigned int state_flags_table[VFIO_DEVICE_NUM_STATES] = {
  705. [VFIO_DEVICE_STATE_STOP] = VFIO_MIGRATION_STOP_COPY,
  706. [VFIO_DEVICE_STATE_RUNNING] = VFIO_MIGRATION_STOP_COPY,
  707. [VFIO_DEVICE_STATE_PRE_COPY] =
  708. VFIO_MIGRATION_STOP_COPY | VFIO_MIGRATION_PRE_COPY,
  709. [VFIO_DEVICE_STATE_PRE_COPY_P2P] = VFIO_MIGRATION_STOP_COPY |
  710. VFIO_MIGRATION_P2P |
  711. VFIO_MIGRATION_PRE_COPY,
  712. [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_MIGRATION_STOP_COPY,
  713. [VFIO_DEVICE_STATE_RESUMING] = VFIO_MIGRATION_STOP_COPY,
  714. [VFIO_DEVICE_STATE_RUNNING_P2P] =
  715. VFIO_MIGRATION_STOP_COPY | VFIO_MIGRATION_P2P,
  716. [VFIO_DEVICE_STATE_ERROR] = ~0U,
  717. };
  718. if (WARN_ON(cur_fsm >= ARRAY_SIZE(vfio_from_fsm_table) ||
  719. (state_flags_table[cur_fsm] & device->migration_flags) !=
  720. state_flags_table[cur_fsm]))
  721. return -EINVAL;
  722. if (new_fsm >= ARRAY_SIZE(vfio_from_fsm_table) ||
  723. (state_flags_table[new_fsm] & device->migration_flags) !=
  724. state_flags_table[new_fsm])
  725. return -EINVAL;
  726. /*
  727. * Arcs touching optional and unsupported states are skipped over. The
  728. * driver will instead see an arc from the original state to the next
  729. * logical state, as per the above comment.
  730. */
  731. *next_fsm = vfio_from_fsm_table[cur_fsm][new_fsm];
  732. while ((state_flags_table[*next_fsm] & device->migration_flags) !=
  733. state_flags_table[*next_fsm])
  734. *next_fsm = vfio_from_fsm_table[*next_fsm][new_fsm];
  735. return (*next_fsm != VFIO_DEVICE_STATE_ERROR) ? 0 : -EINVAL;
  736. }
  737. EXPORT_SYMBOL_GPL(vfio_mig_get_next_state);
  738. /*
  739. * Convert the drivers's struct file into a FD number and return it to userspace
  740. */
  741. static int vfio_ioct_mig_return_fd(struct file *filp, void __user *arg,
  742. struct vfio_device_feature_mig_state *mig)
  743. {
  744. int ret;
  745. int fd;
  746. fd = get_unused_fd_flags(O_CLOEXEC);
  747. if (fd < 0) {
  748. ret = fd;
  749. goto out_fput;
  750. }
  751. mig->data_fd = fd;
  752. if (copy_to_user(arg, mig, sizeof(*mig))) {
  753. ret = -EFAULT;
  754. goto out_put_unused;
  755. }
  756. fd_install(fd, filp);
  757. return 0;
  758. out_put_unused:
  759. put_unused_fd(fd);
  760. out_fput:
  761. fput(filp);
  762. return ret;
  763. }
  764. static int
  765. vfio_ioctl_device_feature_mig_device_state(struct vfio_device *device,
  766. u32 flags, void __user *arg,
  767. size_t argsz)
  768. {
  769. size_t minsz =
  770. offsetofend(struct vfio_device_feature_mig_state, data_fd);
  771. struct vfio_device_feature_mig_state mig;
  772. struct file *filp = NULL;
  773. int ret;
  774. if (!device->mig_ops)
  775. return -ENOTTY;
  776. ret = vfio_check_feature(flags, argsz,
  777. VFIO_DEVICE_FEATURE_SET |
  778. VFIO_DEVICE_FEATURE_GET,
  779. sizeof(mig));
  780. if (ret != 1)
  781. return ret;
  782. if (copy_from_user(&mig, arg, minsz))
  783. return -EFAULT;
  784. if (flags & VFIO_DEVICE_FEATURE_GET) {
  785. enum vfio_device_mig_state curr_state;
  786. ret = device->mig_ops->migration_get_state(device,
  787. &curr_state);
  788. if (ret)
  789. return ret;
  790. mig.device_state = curr_state;
  791. goto out_copy;
  792. }
  793. /* Handle the VFIO_DEVICE_FEATURE_SET */
  794. filp = device->mig_ops->migration_set_state(device, mig.device_state);
  795. if (IS_ERR(filp) || !filp)
  796. goto out_copy;
  797. return vfio_ioct_mig_return_fd(filp, arg, &mig);
  798. out_copy:
  799. mig.data_fd = -1;
  800. if (copy_to_user(arg, &mig, sizeof(mig)))
  801. return -EFAULT;
  802. if (IS_ERR(filp))
  803. return PTR_ERR(filp);
  804. return 0;
  805. }
  806. static int
  807. vfio_ioctl_device_feature_migration_data_size(struct vfio_device *device,
  808. u32 flags, void __user *arg,
  809. size_t argsz)
  810. {
  811. struct vfio_device_feature_mig_data_size data_size = {};
  812. unsigned long stop_copy_length;
  813. int ret;
  814. if (!device->mig_ops)
  815. return -ENOTTY;
  816. ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_GET,
  817. sizeof(data_size));
  818. if (ret != 1)
  819. return ret;
  820. ret = device->mig_ops->migration_get_data_size(device, &stop_copy_length);
  821. if (ret)
  822. return ret;
  823. data_size.stop_copy_length = stop_copy_length;
  824. if (copy_to_user(arg, &data_size, sizeof(data_size)))
  825. return -EFAULT;
  826. return 0;
  827. }
  828. static int vfio_ioctl_device_feature_migration(struct vfio_device *device,
  829. u32 flags, void __user *arg,
  830. size_t argsz)
  831. {
  832. struct vfio_device_feature_migration mig = {
  833. .flags = device->migration_flags,
  834. };
  835. int ret;
  836. if (!device->mig_ops)
  837. return -ENOTTY;
  838. ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_GET,
  839. sizeof(mig));
  840. if (ret != 1)
  841. return ret;
  842. if (copy_to_user(arg, &mig, sizeof(mig)))
  843. return -EFAULT;
  844. return 0;
  845. }
  846. void vfio_combine_iova_ranges(struct rb_root_cached *root, u32 cur_nodes,
  847. u32 req_nodes)
  848. {
  849. struct interval_tree_node *prev, *curr, *comb_start, *comb_end;
  850. unsigned long min_gap, curr_gap;
  851. /* Special shortcut when a single range is required */
  852. if (req_nodes == 1) {
  853. unsigned long last;
  854. comb_start = interval_tree_iter_first(root, 0, ULONG_MAX);
  855. /* Empty list */
  856. if (WARN_ON_ONCE(!comb_start))
  857. return;
  858. curr = comb_start;
  859. while (curr) {
  860. last = curr->last;
  861. prev = curr;
  862. curr = interval_tree_iter_next(curr, 0, ULONG_MAX);
  863. if (prev != comb_start)
  864. interval_tree_remove(prev, root);
  865. }
  866. comb_start->last = last;
  867. return;
  868. }
  869. /* Combine ranges which have the smallest gap */
  870. while (cur_nodes > req_nodes) {
  871. prev = NULL;
  872. min_gap = ULONG_MAX;
  873. curr = interval_tree_iter_first(root, 0, ULONG_MAX);
  874. while (curr) {
  875. if (prev) {
  876. curr_gap = curr->start - prev->last;
  877. if (curr_gap < min_gap) {
  878. min_gap = curr_gap;
  879. comb_start = prev;
  880. comb_end = curr;
  881. }
  882. }
  883. prev = curr;
  884. curr = interval_tree_iter_next(curr, 0, ULONG_MAX);
  885. }
  886. /* Empty list or no nodes to combine */
  887. if (WARN_ON_ONCE(min_gap == ULONG_MAX))
  888. break;
  889. comb_start->last = comb_end->last;
  890. interval_tree_remove(comb_end, root);
  891. cur_nodes--;
  892. }
  893. }
  894. EXPORT_SYMBOL_GPL(vfio_combine_iova_ranges);
  895. /* Ranges should fit into a single kernel page */
  896. #define LOG_MAX_RANGES \
  897. (PAGE_SIZE / sizeof(struct vfio_device_feature_dma_logging_range))
  898. static int
  899. vfio_ioctl_device_feature_logging_start(struct vfio_device *device,
  900. u32 flags, void __user *arg,
  901. size_t argsz)
  902. {
  903. size_t minsz =
  904. offsetofend(struct vfio_device_feature_dma_logging_control,
  905. ranges);
  906. struct vfio_device_feature_dma_logging_range __user *ranges;
  907. struct vfio_device_feature_dma_logging_control control;
  908. struct vfio_device_feature_dma_logging_range range;
  909. struct rb_root_cached root = RB_ROOT_CACHED;
  910. struct interval_tree_node *nodes;
  911. u64 iova_end;
  912. u32 nnodes;
  913. int i, ret;
  914. if (!device->log_ops)
  915. return -ENOTTY;
  916. ret = vfio_check_feature(flags, argsz,
  917. VFIO_DEVICE_FEATURE_SET,
  918. sizeof(control));
  919. if (ret != 1)
  920. return ret;
  921. if (copy_from_user(&control, arg, minsz))
  922. return -EFAULT;
  923. nnodes = control.num_ranges;
  924. if (!nnodes)
  925. return -EINVAL;
  926. if (nnodes > LOG_MAX_RANGES)
  927. return -E2BIG;
  928. ranges = u64_to_user_ptr(control.ranges);
  929. nodes = kmalloc_array(nnodes, sizeof(struct interval_tree_node),
  930. GFP_KERNEL);
  931. if (!nodes)
  932. return -ENOMEM;
  933. for (i = 0; i < nnodes; i++) {
  934. if (copy_from_user(&range, &ranges[i], sizeof(range))) {
  935. ret = -EFAULT;
  936. goto end;
  937. }
  938. if (!IS_ALIGNED(range.iova, control.page_size) ||
  939. !IS_ALIGNED(range.length, control.page_size)) {
  940. ret = -EINVAL;
  941. goto end;
  942. }
  943. if (check_add_overflow(range.iova, range.length, &iova_end) ||
  944. iova_end > ULONG_MAX) {
  945. ret = -EOVERFLOW;
  946. goto end;
  947. }
  948. nodes[i].start = range.iova;
  949. nodes[i].last = range.iova + range.length - 1;
  950. if (interval_tree_iter_first(&root, nodes[i].start,
  951. nodes[i].last)) {
  952. /* Range overlapping */
  953. ret = -EINVAL;
  954. goto end;
  955. }
  956. interval_tree_insert(nodes + i, &root);
  957. }
  958. ret = device->log_ops->log_start(device, &root, nnodes,
  959. &control.page_size);
  960. if (ret)
  961. goto end;
  962. if (copy_to_user(arg, &control, sizeof(control))) {
  963. ret = -EFAULT;
  964. device->log_ops->log_stop(device);
  965. }
  966. end:
  967. kfree(nodes);
  968. return ret;
  969. }
  970. static int
  971. vfio_ioctl_device_feature_logging_stop(struct vfio_device *device,
  972. u32 flags, void __user *arg,
  973. size_t argsz)
  974. {
  975. int ret;
  976. if (!device->log_ops)
  977. return -ENOTTY;
  978. ret = vfio_check_feature(flags, argsz,
  979. VFIO_DEVICE_FEATURE_SET, 0);
  980. if (ret != 1)
  981. return ret;
  982. return device->log_ops->log_stop(device);
  983. }
  984. static int vfio_device_log_read_and_clear(struct iova_bitmap *iter,
  985. unsigned long iova, size_t length,
  986. void *opaque)
  987. {
  988. struct vfio_device *device = opaque;
  989. return device->log_ops->log_read_and_clear(device, iova, length, iter);
  990. }
  991. static int
  992. vfio_ioctl_device_feature_logging_report(struct vfio_device *device,
  993. u32 flags, void __user *arg,
  994. size_t argsz)
  995. {
  996. size_t minsz =
  997. offsetofend(struct vfio_device_feature_dma_logging_report,
  998. bitmap);
  999. struct vfio_device_feature_dma_logging_report report;
  1000. struct iova_bitmap *iter;
  1001. u64 iova_end;
  1002. int ret;
  1003. if (!device->log_ops)
  1004. return -ENOTTY;
  1005. ret = vfio_check_feature(flags, argsz,
  1006. VFIO_DEVICE_FEATURE_GET,
  1007. sizeof(report));
  1008. if (ret != 1)
  1009. return ret;
  1010. if (copy_from_user(&report, arg, minsz))
  1011. return -EFAULT;
  1012. if (report.page_size < SZ_4K || !is_power_of_2(report.page_size))
  1013. return -EINVAL;
  1014. if (check_add_overflow(report.iova, report.length, &iova_end) ||
  1015. iova_end > ULONG_MAX)
  1016. return -EOVERFLOW;
  1017. iter = iova_bitmap_alloc(report.iova, report.length,
  1018. report.page_size,
  1019. u64_to_user_ptr(report.bitmap));
  1020. if (IS_ERR(iter))
  1021. return PTR_ERR(iter);
  1022. ret = iova_bitmap_for_each(iter, device,
  1023. vfio_device_log_read_and_clear);
  1024. iova_bitmap_free(iter);
  1025. return ret;
  1026. }
  1027. static int vfio_ioctl_device_feature(struct vfio_device *device,
  1028. struct vfio_device_feature __user *arg)
  1029. {
  1030. size_t minsz = offsetofend(struct vfio_device_feature, flags);
  1031. struct vfio_device_feature feature;
  1032. if (copy_from_user(&feature, arg, minsz))
  1033. return -EFAULT;
  1034. if (feature.argsz < minsz)
  1035. return -EINVAL;
  1036. /* Check unknown flags */
  1037. if (feature.flags &
  1038. ~(VFIO_DEVICE_FEATURE_MASK | VFIO_DEVICE_FEATURE_SET |
  1039. VFIO_DEVICE_FEATURE_GET | VFIO_DEVICE_FEATURE_PROBE))
  1040. return -EINVAL;
  1041. /* GET & SET are mutually exclusive except with PROBE */
  1042. if (!(feature.flags & VFIO_DEVICE_FEATURE_PROBE) &&
  1043. (feature.flags & VFIO_DEVICE_FEATURE_SET) &&
  1044. (feature.flags & VFIO_DEVICE_FEATURE_GET))
  1045. return -EINVAL;
  1046. switch (feature.flags & VFIO_DEVICE_FEATURE_MASK) {
  1047. case VFIO_DEVICE_FEATURE_MIGRATION:
  1048. return vfio_ioctl_device_feature_migration(
  1049. device, feature.flags, arg->data,
  1050. feature.argsz - minsz);
  1051. case VFIO_DEVICE_FEATURE_MIG_DEVICE_STATE:
  1052. return vfio_ioctl_device_feature_mig_device_state(
  1053. device, feature.flags, arg->data,
  1054. feature.argsz - minsz);
  1055. case VFIO_DEVICE_FEATURE_DMA_LOGGING_START:
  1056. return vfio_ioctl_device_feature_logging_start(
  1057. device, feature.flags, arg->data,
  1058. feature.argsz - minsz);
  1059. case VFIO_DEVICE_FEATURE_DMA_LOGGING_STOP:
  1060. return vfio_ioctl_device_feature_logging_stop(
  1061. device, feature.flags, arg->data,
  1062. feature.argsz - minsz);
  1063. case VFIO_DEVICE_FEATURE_DMA_LOGGING_REPORT:
  1064. return vfio_ioctl_device_feature_logging_report(
  1065. device, feature.flags, arg->data,
  1066. feature.argsz - minsz);
  1067. case VFIO_DEVICE_FEATURE_MIG_DATA_SIZE:
  1068. return vfio_ioctl_device_feature_migration_data_size(
  1069. device, feature.flags, arg->data,
  1070. feature.argsz - minsz);
  1071. default:
  1072. if (unlikely(!device->ops->device_feature))
  1073. return -EINVAL;
  1074. return device->ops->device_feature(device, feature.flags,
  1075. arg->data,
  1076. feature.argsz - minsz);
  1077. }
  1078. }
  1079. static long vfio_device_fops_unl_ioctl(struct file *filep,
  1080. unsigned int cmd, unsigned long arg)
  1081. {
  1082. struct vfio_device_file *df = filep->private_data;
  1083. struct vfio_device *device = df->device;
  1084. void __user *uptr = (void __user *)arg;
  1085. int ret;
  1086. if (cmd == VFIO_DEVICE_BIND_IOMMUFD)
  1087. return vfio_df_ioctl_bind_iommufd(df, uptr);
  1088. /* Paired with smp_store_release() following vfio_df_open() */
  1089. if (!smp_load_acquire(&df->access_granted))
  1090. return -EINVAL;
  1091. ret = vfio_device_pm_runtime_get(device);
  1092. if (ret)
  1093. return ret;
  1094. /* cdev only ioctls */
  1095. if (IS_ENABLED(CONFIG_VFIO_DEVICE_CDEV) && !df->group) {
  1096. switch (cmd) {
  1097. case VFIO_DEVICE_ATTACH_IOMMUFD_PT:
  1098. ret = vfio_df_ioctl_attach_pt(df, uptr);
  1099. goto out;
  1100. case VFIO_DEVICE_DETACH_IOMMUFD_PT:
  1101. ret = vfio_df_ioctl_detach_pt(df, uptr);
  1102. goto out;
  1103. }
  1104. }
  1105. switch (cmd) {
  1106. case VFIO_DEVICE_FEATURE:
  1107. ret = vfio_ioctl_device_feature(device, uptr);
  1108. break;
  1109. default:
  1110. if (unlikely(!device->ops->ioctl))
  1111. ret = -EINVAL;
  1112. else
  1113. ret = device->ops->ioctl(device, cmd, arg);
  1114. break;
  1115. }
  1116. out:
  1117. vfio_device_pm_runtime_put(device);
  1118. return ret;
  1119. }
  1120. static ssize_t vfio_device_fops_read(struct file *filep, char __user *buf,
  1121. size_t count, loff_t *ppos)
  1122. {
  1123. struct vfio_device_file *df = filep->private_data;
  1124. struct vfio_device *device = df->device;
  1125. /* Paired with smp_store_release() following vfio_df_open() */
  1126. if (!smp_load_acquire(&df->access_granted))
  1127. return -EINVAL;
  1128. if (unlikely(!device->ops->read))
  1129. return -EINVAL;
  1130. return device->ops->read(device, buf, count, ppos);
  1131. }
  1132. static ssize_t vfio_device_fops_write(struct file *filep,
  1133. const char __user *buf,
  1134. size_t count, loff_t *ppos)
  1135. {
  1136. struct vfio_device_file *df = filep->private_data;
  1137. struct vfio_device *device = df->device;
  1138. /* Paired with smp_store_release() following vfio_df_open() */
  1139. if (!smp_load_acquire(&df->access_granted))
  1140. return -EINVAL;
  1141. if (unlikely(!device->ops->write))
  1142. return -EINVAL;
  1143. return device->ops->write(device, buf, count, ppos);
  1144. }
  1145. static int vfio_device_fops_mmap(struct file *filep, struct vm_area_struct *vma)
  1146. {
  1147. struct vfio_device_file *df = filep->private_data;
  1148. struct vfio_device *device = df->device;
  1149. /* Paired with smp_store_release() following vfio_df_open() */
  1150. if (!smp_load_acquire(&df->access_granted))
  1151. return -EINVAL;
  1152. if (unlikely(!device->ops->mmap))
  1153. return -EINVAL;
  1154. return device->ops->mmap(device, vma);
  1155. }
  1156. const struct file_operations vfio_device_fops = {
  1157. .owner = THIS_MODULE,
  1158. .open = vfio_device_fops_cdev_open,
  1159. .release = vfio_device_fops_release,
  1160. .read = vfio_device_fops_read,
  1161. .write = vfio_device_fops_write,
  1162. .unlocked_ioctl = vfio_device_fops_unl_ioctl,
  1163. .compat_ioctl = compat_ptr_ioctl,
  1164. .mmap = vfio_device_fops_mmap,
  1165. };
  1166. static struct vfio_device *vfio_device_from_file(struct file *file)
  1167. {
  1168. struct vfio_device_file *df = file->private_data;
  1169. if (file->f_op != &vfio_device_fops)
  1170. return NULL;
  1171. return df->device;
  1172. }
  1173. /**
  1174. * vfio_file_is_valid - True if the file is valid vfio file
  1175. * @file: VFIO group file or VFIO device file
  1176. */
  1177. bool vfio_file_is_valid(struct file *file)
  1178. {
  1179. return vfio_group_from_file(file) ||
  1180. vfio_device_from_file(file);
  1181. }
  1182. EXPORT_SYMBOL_GPL(vfio_file_is_valid);
  1183. /**
  1184. * vfio_file_enforced_coherent - True if the DMA associated with the VFIO file
  1185. * is always CPU cache coherent
  1186. * @file: VFIO group file or VFIO device file
  1187. *
  1188. * Enforced coherency means that the IOMMU ignores things like the PCIe no-snoop
  1189. * bit in DMA transactions. A return of false indicates that the user has
  1190. * rights to access additional instructions such as wbinvd on x86.
  1191. */
  1192. bool vfio_file_enforced_coherent(struct file *file)
  1193. {
  1194. struct vfio_device *device;
  1195. struct vfio_group *group;
  1196. group = vfio_group_from_file(file);
  1197. if (group)
  1198. return vfio_group_enforced_coherent(group);
  1199. device = vfio_device_from_file(file);
  1200. if (device)
  1201. return device_iommu_capable(device->dev,
  1202. IOMMU_CAP_ENFORCE_CACHE_COHERENCY);
  1203. return true;
  1204. }
  1205. EXPORT_SYMBOL_GPL(vfio_file_enforced_coherent);
  1206. static void vfio_device_file_set_kvm(struct file *file, struct kvm *kvm)
  1207. {
  1208. struct vfio_device_file *df = file->private_data;
  1209. /*
  1210. * The kvm is first recorded in the vfio_device_file, and will
  1211. * be propagated to vfio_device::kvm when the file is bound to
  1212. * iommufd successfully in the vfio device cdev path.
  1213. */
  1214. spin_lock(&df->kvm_ref_lock);
  1215. df->kvm = kvm;
  1216. spin_unlock(&df->kvm_ref_lock);
  1217. }
  1218. /**
  1219. * vfio_file_set_kvm - Link a kvm with VFIO drivers
  1220. * @file: VFIO group file or VFIO device file
  1221. * @kvm: KVM to link
  1222. *
  1223. * When a VFIO device is first opened the KVM will be available in
  1224. * device->kvm if one was associated with the file.
  1225. */
  1226. void vfio_file_set_kvm(struct file *file, struct kvm *kvm)
  1227. {
  1228. struct vfio_group *group;
  1229. group = vfio_group_from_file(file);
  1230. if (group)
  1231. vfio_group_set_kvm(group, kvm);
  1232. if (vfio_device_from_file(file))
  1233. vfio_device_file_set_kvm(file, kvm);
  1234. }
  1235. EXPORT_SYMBOL_GPL(vfio_file_set_kvm);
  1236. /*
  1237. * Sub-module support
  1238. */
  1239. /*
  1240. * Helper for managing a buffer of info chain capabilities, allocate or
  1241. * reallocate a buffer with additional @size, filling in @id and @version
  1242. * of the capability. A pointer to the new capability is returned.
  1243. *
  1244. * NB. The chain is based at the head of the buffer, so new entries are
  1245. * added to the tail, vfio_info_cap_shift() should be called to fixup the
  1246. * next offsets prior to copying to the user buffer.
  1247. */
  1248. struct vfio_info_cap_header *vfio_info_cap_add(struct vfio_info_cap *caps,
  1249. size_t size, u16 id, u16 version)
  1250. {
  1251. void *buf;
  1252. struct vfio_info_cap_header *header, *tmp;
  1253. /* Ensure that the next capability struct will be aligned */
  1254. size = ALIGN(size, sizeof(u64));
  1255. buf = krealloc(caps->buf, caps->size + size, GFP_KERNEL);
  1256. if (!buf) {
  1257. kfree(caps->buf);
  1258. caps->buf = NULL;
  1259. caps->size = 0;
  1260. return ERR_PTR(-ENOMEM);
  1261. }
  1262. caps->buf = buf;
  1263. header = buf + caps->size;
  1264. /* Eventually copied to user buffer, zero */
  1265. memset(header, 0, size);
  1266. header->id = id;
  1267. header->version = version;
  1268. /* Add to the end of the capability chain */
  1269. for (tmp = buf; tmp->next; tmp = buf + tmp->next)
  1270. ; /* nothing */
  1271. tmp->next = caps->size;
  1272. caps->size += size;
  1273. return header;
  1274. }
  1275. EXPORT_SYMBOL_GPL(vfio_info_cap_add);
  1276. void vfio_info_cap_shift(struct vfio_info_cap *caps, size_t offset)
  1277. {
  1278. struct vfio_info_cap_header *tmp;
  1279. void *buf = (void *)caps->buf;
  1280. /* Capability structs should start with proper alignment */
  1281. WARN_ON(!IS_ALIGNED(offset, sizeof(u64)));
  1282. for (tmp = buf; tmp->next; tmp = buf + tmp->next - offset)
  1283. tmp->next += offset;
  1284. }
  1285. EXPORT_SYMBOL(vfio_info_cap_shift);
  1286. int vfio_info_add_capability(struct vfio_info_cap *caps,
  1287. struct vfio_info_cap_header *cap, size_t size)
  1288. {
  1289. struct vfio_info_cap_header *header;
  1290. header = vfio_info_cap_add(caps, size, cap->id, cap->version);
  1291. if (IS_ERR(header))
  1292. return PTR_ERR(header);
  1293. memcpy(header + 1, cap + 1, size - sizeof(*header));
  1294. return 0;
  1295. }
  1296. EXPORT_SYMBOL(vfio_info_add_capability);
  1297. int vfio_set_irqs_validate_and_prepare(struct vfio_irq_set *hdr, int num_irqs,
  1298. int max_irq_type, size_t *data_size)
  1299. {
  1300. unsigned long minsz;
  1301. size_t size;
  1302. minsz = offsetofend(struct vfio_irq_set, count);
  1303. if ((hdr->argsz < minsz) || (hdr->index >= max_irq_type) ||
  1304. (hdr->count >= (U32_MAX - hdr->start)) ||
  1305. (hdr->flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK |
  1306. VFIO_IRQ_SET_ACTION_TYPE_MASK)))
  1307. return -EINVAL;
  1308. if (data_size)
  1309. *data_size = 0;
  1310. if (hdr->start >= num_irqs || hdr->start + hdr->count > num_irqs)
  1311. return -EINVAL;
  1312. switch (hdr->flags & VFIO_IRQ_SET_DATA_TYPE_MASK) {
  1313. case VFIO_IRQ_SET_DATA_NONE:
  1314. size = 0;
  1315. break;
  1316. case VFIO_IRQ_SET_DATA_BOOL:
  1317. size = sizeof(uint8_t);
  1318. break;
  1319. case VFIO_IRQ_SET_DATA_EVENTFD:
  1320. size = sizeof(int32_t);
  1321. break;
  1322. default:
  1323. return -EINVAL;
  1324. }
  1325. if (size) {
  1326. if (hdr->argsz - minsz < hdr->count * size)
  1327. return -EINVAL;
  1328. if (!data_size)
  1329. return -EINVAL;
  1330. *data_size = hdr->count * size;
  1331. }
  1332. return 0;
  1333. }
  1334. EXPORT_SYMBOL(vfio_set_irqs_validate_and_prepare);
  1335. /*
  1336. * Pin contiguous user pages and return their associated host pages for local
  1337. * domain only.
  1338. * @device [in] : device
  1339. * @iova [in] : starting IOVA of user pages to be pinned.
  1340. * @npage [in] : count of pages to be pinned. This count should not
  1341. * be greater than VFIO_PIN_PAGES_MAX_ENTRIES.
  1342. * @prot [in] : protection flags
  1343. * @pages[out] : array of host pages
  1344. * Return error or number of pages pinned.
  1345. *
  1346. * A driver may only call this function if the vfio_device was created
  1347. * by vfio_register_emulated_iommu_dev() due to vfio_device_container_pin_pages().
  1348. */
  1349. int vfio_pin_pages(struct vfio_device *device, dma_addr_t iova,
  1350. int npage, int prot, struct page **pages)
  1351. {
  1352. /* group->container cannot change while a vfio device is open */
  1353. if (!pages || !npage || WARN_ON(!vfio_assert_device_open(device)))
  1354. return -EINVAL;
  1355. if (!device->ops->dma_unmap)
  1356. return -EINVAL;
  1357. if (vfio_device_has_container(device))
  1358. return vfio_device_container_pin_pages(device, iova,
  1359. npage, prot, pages);
  1360. if (device->iommufd_access) {
  1361. int ret;
  1362. if (iova > ULONG_MAX)
  1363. return -EINVAL;
  1364. /*
  1365. * VFIO ignores the sub page offset, npages is from the start of
  1366. * a PAGE_SIZE chunk of IOVA. The caller is expected to recover
  1367. * the sub page offset by doing:
  1368. * pages[0] + (iova % PAGE_SIZE)
  1369. */
  1370. ret = iommufd_access_pin_pages(
  1371. device->iommufd_access, ALIGN_DOWN(iova, PAGE_SIZE),
  1372. npage * PAGE_SIZE, pages,
  1373. (prot & IOMMU_WRITE) ? IOMMUFD_ACCESS_RW_WRITE : 0);
  1374. if (ret)
  1375. return ret;
  1376. return npage;
  1377. }
  1378. return -EINVAL;
  1379. }
  1380. EXPORT_SYMBOL(vfio_pin_pages);
  1381. /*
  1382. * Unpin contiguous host pages for local domain only.
  1383. * @device [in] : device
  1384. * @iova [in] : starting address of user pages to be unpinned.
  1385. * @npage [in] : count of pages to be unpinned. This count should not
  1386. * be greater than VFIO_PIN_PAGES_MAX_ENTRIES.
  1387. */
  1388. void vfio_unpin_pages(struct vfio_device *device, dma_addr_t iova, int npage)
  1389. {
  1390. if (WARN_ON(!vfio_assert_device_open(device)))
  1391. return;
  1392. if (WARN_ON(!device->ops->dma_unmap))
  1393. return;
  1394. if (vfio_device_has_container(device)) {
  1395. vfio_device_container_unpin_pages(device, iova, npage);
  1396. return;
  1397. }
  1398. if (device->iommufd_access) {
  1399. if (WARN_ON(iova > ULONG_MAX))
  1400. return;
  1401. iommufd_access_unpin_pages(device->iommufd_access,
  1402. ALIGN_DOWN(iova, PAGE_SIZE),
  1403. npage * PAGE_SIZE);
  1404. return;
  1405. }
  1406. }
  1407. EXPORT_SYMBOL(vfio_unpin_pages);
  1408. /*
  1409. * This interface allows the CPUs to perform some sort of virtual DMA on
  1410. * behalf of the device.
  1411. *
  1412. * CPUs read/write from/into a range of IOVAs pointing to user space memory
  1413. * into/from a kernel buffer.
  1414. *
  1415. * As the read/write of user space memory is conducted via the CPUs and is
  1416. * not a real device DMA, it is not necessary to pin the user space memory.
  1417. *
  1418. * @device [in] : VFIO device
  1419. * @iova [in] : base IOVA of a user space buffer
  1420. * @data [in] : pointer to kernel buffer
  1421. * @len [in] : kernel buffer length
  1422. * @write : indicate read or write
  1423. * Return error code on failure or 0 on success.
  1424. */
  1425. int vfio_dma_rw(struct vfio_device *device, dma_addr_t iova, void *data,
  1426. size_t len, bool write)
  1427. {
  1428. if (!data || len <= 0 || !vfio_assert_device_open(device))
  1429. return -EINVAL;
  1430. if (vfio_device_has_container(device))
  1431. return vfio_device_container_dma_rw(device, iova,
  1432. data, len, write);
  1433. if (device->iommufd_access) {
  1434. unsigned int flags = 0;
  1435. if (iova > ULONG_MAX)
  1436. return -EINVAL;
  1437. /* VFIO historically tries to auto-detect a kthread */
  1438. if (!current->mm)
  1439. flags |= IOMMUFD_ACCESS_RW_KTHREAD;
  1440. if (write)
  1441. flags |= IOMMUFD_ACCESS_RW_WRITE;
  1442. return iommufd_access_rw(device->iommufd_access, iova, data,
  1443. len, flags);
  1444. }
  1445. return -EINVAL;
  1446. }
  1447. EXPORT_SYMBOL(vfio_dma_rw);
  1448. /*
  1449. * Module/class support
  1450. */
  1451. static int __init vfio_init(void)
  1452. {
  1453. int ret;
  1454. ida_init(&vfio.device_ida);
  1455. ret = vfio_group_init();
  1456. if (ret)
  1457. return ret;
  1458. ret = vfio_virqfd_init();
  1459. if (ret)
  1460. goto err_virqfd;
  1461. /* /sys/class/vfio-dev/vfioX */
  1462. vfio.device_class = class_create("vfio-dev");
  1463. if (IS_ERR(vfio.device_class)) {
  1464. ret = PTR_ERR(vfio.device_class);
  1465. goto err_dev_class;
  1466. }
  1467. ret = vfio_cdev_init(vfio.device_class);
  1468. if (ret)
  1469. goto err_alloc_dev_chrdev;
  1470. vfio_debugfs_create_root();
  1471. pr_info(DRIVER_DESC " version: " DRIVER_VERSION "\n");
  1472. return 0;
  1473. err_alloc_dev_chrdev:
  1474. class_destroy(vfio.device_class);
  1475. vfio.device_class = NULL;
  1476. err_dev_class:
  1477. vfio_virqfd_exit();
  1478. err_virqfd:
  1479. vfio_group_cleanup();
  1480. return ret;
  1481. }
  1482. static void __exit vfio_cleanup(void)
  1483. {
  1484. vfio_debugfs_remove_root();
  1485. ida_destroy(&vfio.device_ida);
  1486. vfio_cdev_cleanup();
  1487. class_destroy(vfio.device_class);
  1488. vfio.device_class = NULL;
  1489. vfio_virqfd_exit();
  1490. vfio_group_cleanup();
  1491. xa_destroy(&vfio_device_set_xa);
  1492. }
  1493. module_init(vfio_init);
  1494. module_exit(vfio_cleanup);
  1495. MODULE_IMPORT_NS(IOMMUFD);
  1496. MODULE_VERSION(DRIVER_VERSION);
  1497. MODULE_LICENSE("GPL v2");
  1498. MODULE_AUTHOR(DRIVER_AUTHOR);
  1499. MODULE_DESCRIPTION(DRIVER_DESC);
  1500. MODULE_SOFTDEP("post: vfio_iommu_type1 vfio_iommu_spapr_tce");