2
0

vfio-helpers.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. /*
  2. * VFIO utility
  3. *
  4. * Copyright 2016 - 2018 Red Hat, Inc.
  5. *
  6. * Authors:
  7. * Fam Zheng <famz@redhat.com>
  8. *
  9. * This work is licensed under the terms of the GNU GPL, version 2 or later.
  10. * See the COPYING file in the top-level directory.
  11. */
  12. #include "qemu/osdep.h"
  13. #include <sys/ioctl.h>
  14. #include <linux/vfio.h>
  15. #include "qapi/error.h"
  16. #include "exec/ramlist.h"
  17. #include "exec/cpu-common.h"
  18. #include "exec/memory.h"
  19. #include "trace.h"
  20. #include "qemu/error-report.h"
  21. #include "standard-headers/linux/pci_regs.h"
  22. #include "qemu/event_notifier.h"
  23. #include "qemu/vfio-helpers.h"
  24. #include "qemu/lockable.h"
  25. #include "trace.h"
  26. #define QEMU_VFIO_DEBUG 0
  27. #define QEMU_VFIO_IOVA_MIN 0x10000ULL
  28. /* XXX: Once VFIO exposes the iova bit width in the IOMMU capability interface,
  29. * we can use a runtime limit; alternatively it's also possible to do platform
  30. * specific detection by reading sysfs entries. Until then, 39 is a safe bet.
  31. **/
  32. #define QEMU_VFIO_IOVA_MAX (1ULL << 39)
  33. typedef struct {
  34. /* Page aligned addr. */
  35. void *host;
  36. size_t size;
  37. uint64_t iova;
  38. } IOVAMapping;
  39. struct IOVARange {
  40. uint64_t start;
  41. uint64_t end;
  42. };
  43. struct QEMUVFIOState {
  44. QemuMutex lock;
  45. /* These fields are protected by BQL */
  46. int container;
  47. int group;
  48. int device;
  49. RAMBlockNotifier ram_notifier;
  50. struct vfio_region_info config_region_info, bar_region_info[6];
  51. struct IOVARange *usable_iova_ranges;
  52. uint8_t nb_iova_ranges;
  53. /* These fields are protected by @lock */
  54. /* VFIO's IO virtual address space is managed by splitting into a few
  55. * sections:
  56. *
  57. * --------------- <= 0
  58. * |xxxxxxxxxxxxx|
  59. * |-------------| <= QEMU_VFIO_IOVA_MIN
  60. * | |
  61. * | Fixed |
  62. * | |
  63. * |-------------| <= low_water_mark
  64. * | |
  65. * | Free |
  66. * | |
  67. * |-------------| <= high_water_mark
  68. * | |
  69. * | Temp |
  70. * | |
  71. * |-------------| <= QEMU_VFIO_IOVA_MAX
  72. * |xxxxxxxxxxxxx|
  73. * |xxxxxxxxxxxxx|
  74. * ---------------
  75. *
  76. * - Addresses lower than QEMU_VFIO_IOVA_MIN are reserved as invalid;
  77. *
  78. * - Fixed mappings of HVAs are assigned "low" IOVAs in the range of
  79. * [QEMU_VFIO_IOVA_MIN, low_water_mark). Once allocated they will not be
  80. * reclaimed - low_water_mark never shrinks;
  81. *
  82. * - IOVAs in range [low_water_mark, high_water_mark) are free;
  83. *
  84. * - IOVAs in range [high_water_mark, QEMU_VFIO_IOVA_MAX) are volatile
  85. * mappings. At each qemu_vfio_dma_reset_temporary() call, the whole area
  86. * is recycled. The caller should make sure I/O's depending on these
  87. * mappings are completed before calling.
  88. **/
  89. uint64_t low_water_mark;
  90. uint64_t high_water_mark;
  91. IOVAMapping *mappings;
  92. int nr_mappings;
  93. };
  94. /**
  95. * Find group file by PCI device address as specified @device, and return the
  96. * path. The returned string is owned by caller and should be g_free'ed later.
  97. */
  98. static char *sysfs_find_group_file(const char *device, Error **errp)
  99. {
  100. g_autoptr(GError) gerr = NULL;
  101. char *sysfs_link;
  102. char *sysfs_group;
  103. char *p;
  104. char *path = NULL;
  105. sysfs_link = g_strdup_printf("/sys/bus/pci/devices/%s/iommu_group", device);
  106. sysfs_group = g_file_read_link(sysfs_link, &gerr);
  107. if (gerr) {
  108. error_setg(errp, "Failed to find iommu group sysfs path: %s",
  109. gerr->message);
  110. goto out;
  111. }
  112. p = strrchr(sysfs_group, '/');
  113. if (!p) {
  114. error_setg(errp, "Failed to find iommu group number");
  115. goto out;
  116. }
  117. path = g_strdup_printf("/dev/vfio/%s", p + 1);
  118. out:
  119. g_free(sysfs_link);
  120. g_free(sysfs_group);
  121. return path;
  122. }
  123. static inline void assert_bar_index_valid(QEMUVFIOState *s, int index)
  124. {
  125. assert(index >= 0 && index < ARRAY_SIZE(s->bar_region_info));
  126. }
  127. static int qemu_vfio_pci_init_bar(QEMUVFIOState *s, int index, Error **errp)
  128. {
  129. g_autofree char *barname = NULL;
  130. assert_bar_index_valid(s, index);
  131. s->bar_region_info[index] = (struct vfio_region_info) {
  132. .index = VFIO_PCI_BAR0_REGION_INDEX + index,
  133. .argsz = sizeof(struct vfio_region_info),
  134. };
  135. if (ioctl(s->device, VFIO_DEVICE_GET_REGION_INFO, &s->bar_region_info[index])) {
  136. error_setg_errno(errp, errno, "Failed to get BAR region info");
  137. return -errno;
  138. }
  139. barname = g_strdup_printf("bar[%d]", index);
  140. trace_qemu_vfio_region_info(barname, s->bar_region_info[index].offset,
  141. s->bar_region_info[index].size,
  142. s->bar_region_info[index].cap_offset);
  143. return 0;
  144. }
  145. /**
  146. * Map a PCI bar area.
  147. */
  148. void *qemu_vfio_pci_map_bar(QEMUVFIOState *s, int index,
  149. uint64_t offset, uint64_t size, int prot,
  150. Error **errp)
  151. {
  152. void *p;
  153. assert(QEMU_IS_ALIGNED(offset, qemu_real_host_page_size()));
  154. assert_bar_index_valid(s, index);
  155. p = mmap(NULL, MIN(size, s->bar_region_info[index].size - offset),
  156. prot, MAP_SHARED,
  157. s->device, s->bar_region_info[index].offset + offset);
  158. trace_qemu_vfio_pci_map_bar(index, s->bar_region_info[index].offset ,
  159. size, offset, p);
  160. if (p == MAP_FAILED) {
  161. error_setg_errno(errp, errno, "Failed to map BAR region");
  162. p = NULL;
  163. }
  164. return p;
  165. }
  166. /**
  167. * Unmap a PCI bar area.
  168. */
  169. void qemu_vfio_pci_unmap_bar(QEMUVFIOState *s, int index, void *bar,
  170. uint64_t offset, uint64_t size)
  171. {
  172. if (bar) {
  173. munmap(bar, MIN(size, s->bar_region_info[index].size - offset));
  174. }
  175. }
  176. /**
  177. * Initialize device IRQ with @irq_type and register an event notifier.
  178. */
  179. int qemu_vfio_pci_init_irq(QEMUVFIOState *s, EventNotifier *e,
  180. int irq_type, Error **errp)
  181. {
  182. int r;
  183. struct vfio_irq_set *irq_set;
  184. size_t irq_set_size;
  185. struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info) };
  186. irq_info.index = irq_type;
  187. if (ioctl(s->device, VFIO_DEVICE_GET_IRQ_INFO, &irq_info)) {
  188. error_setg_errno(errp, errno, "Failed to get device interrupt info");
  189. return -errno;
  190. }
  191. if (!(irq_info.flags & VFIO_IRQ_INFO_EVENTFD)) {
  192. error_setg(errp, "Device interrupt doesn't support eventfd");
  193. return -EINVAL;
  194. }
  195. irq_set_size = sizeof(*irq_set) + sizeof(int);
  196. irq_set = g_malloc0(irq_set_size);
  197. /* Get to a known IRQ state */
  198. *irq_set = (struct vfio_irq_set) {
  199. .argsz = irq_set_size,
  200. .flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER,
  201. .index = irq_info.index,
  202. .start = 0,
  203. .count = 1,
  204. };
  205. *(int *)&irq_set->data = event_notifier_get_fd(e);
  206. r = ioctl(s->device, VFIO_DEVICE_SET_IRQS, irq_set);
  207. g_free(irq_set);
  208. if (r) {
  209. error_setg_errno(errp, errno, "Failed to setup device interrupt");
  210. return -errno;
  211. }
  212. return 0;
  213. }
  214. static int qemu_vfio_pci_read_config(QEMUVFIOState *s, void *buf,
  215. int size, int ofs)
  216. {
  217. int ret;
  218. trace_qemu_vfio_pci_read_config(buf, ofs, size,
  219. s->config_region_info.offset,
  220. s->config_region_info.size);
  221. assert(QEMU_IS_ALIGNED(s->config_region_info.offset + ofs, size));
  222. ret = RETRY_ON_EINTR(
  223. pread(s->device, buf, size, s->config_region_info.offset + ofs)
  224. );
  225. return ret == size ? 0 : -errno;
  226. }
  227. static int qemu_vfio_pci_write_config(QEMUVFIOState *s, void *buf, int size, int ofs)
  228. {
  229. int ret;
  230. trace_qemu_vfio_pci_write_config(buf, ofs, size,
  231. s->config_region_info.offset,
  232. s->config_region_info.size);
  233. assert(QEMU_IS_ALIGNED(s->config_region_info.offset + ofs, size));
  234. ret = RETRY_ON_EINTR(
  235. pwrite(s->device, buf, size, s->config_region_info.offset + ofs)
  236. );
  237. return ret == size ? 0 : -errno;
  238. }
  239. static void collect_usable_iova_ranges(QEMUVFIOState *s, void *buf)
  240. {
  241. struct vfio_iommu_type1_info *info = (struct vfio_iommu_type1_info *)buf;
  242. struct vfio_info_cap_header *cap = (void *)buf + info->cap_offset;
  243. struct vfio_iommu_type1_info_cap_iova_range *cap_iova_range;
  244. int i;
  245. while (cap->id != VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE) {
  246. if (!cap->next) {
  247. return;
  248. }
  249. cap = buf + cap->next;
  250. }
  251. cap_iova_range = (struct vfio_iommu_type1_info_cap_iova_range *)cap;
  252. s->nb_iova_ranges = cap_iova_range->nr_iovas;
  253. if (s->nb_iova_ranges > 1) {
  254. s->usable_iova_ranges =
  255. g_renew(struct IOVARange, s->usable_iova_ranges,
  256. s->nb_iova_ranges);
  257. }
  258. for (i = 0; i < s->nb_iova_ranges; i++) {
  259. s->usable_iova_ranges[i].start = cap_iova_range->iova_ranges[i].start;
  260. s->usable_iova_ranges[i].end = cap_iova_range->iova_ranges[i].end;
  261. }
  262. }
  263. static int qemu_vfio_init_pci(QEMUVFIOState *s, const char *device,
  264. Error **errp)
  265. {
  266. int ret;
  267. int i;
  268. uint16_t pci_cmd;
  269. struct vfio_group_status group_status = { .argsz = sizeof(group_status) };
  270. struct vfio_iommu_type1_info *iommu_info = NULL;
  271. size_t iommu_info_size = sizeof(*iommu_info);
  272. struct vfio_device_info device_info = { .argsz = sizeof(device_info) };
  273. char *group_file = NULL;
  274. s->usable_iova_ranges = NULL;
  275. /* Create a new container */
  276. s->container = open("/dev/vfio/vfio", O_RDWR);
  277. if (s->container == -1) {
  278. error_setg_errno(errp, errno, "Failed to open /dev/vfio/vfio");
  279. return -errno;
  280. }
  281. if (ioctl(s->container, VFIO_GET_API_VERSION) != VFIO_API_VERSION) {
  282. error_setg(errp, "Invalid VFIO version");
  283. ret = -EINVAL;
  284. goto fail_container;
  285. }
  286. if (!ioctl(s->container, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU)) {
  287. error_setg_errno(errp, errno, "VFIO IOMMU Type1 is not supported");
  288. ret = -EINVAL;
  289. goto fail_container;
  290. }
  291. /* Open the group */
  292. group_file = sysfs_find_group_file(device, errp);
  293. if (!group_file) {
  294. ret = -EINVAL;
  295. goto fail_container;
  296. }
  297. s->group = open(group_file, O_RDWR);
  298. if (s->group == -1) {
  299. error_setg_errno(errp, errno, "Failed to open VFIO group file: %s",
  300. group_file);
  301. g_free(group_file);
  302. ret = -errno;
  303. goto fail_container;
  304. }
  305. g_free(group_file);
  306. /* Test the group is viable and available */
  307. if (ioctl(s->group, VFIO_GROUP_GET_STATUS, &group_status)) {
  308. error_setg_errno(errp, errno, "Failed to get VFIO group status");
  309. ret = -errno;
  310. goto fail;
  311. }
  312. if (!(group_status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
  313. error_setg(errp, "VFIO group is not viable");
  314. ret = -EINVAL;
  315. goto fail;
  316. }
  317. /* Add the group to the container */
  318. if (ioctl(s->group, VFIO_GROUP_SET_CONTAINER, &s->container)) {
  319. error_setg_errno(errp, errno, "Failed to add group to VFIO container");
  320. ret = -errno;
  321. goto fail;
  322. }
  323. /* Enable the IOMMU model we want */
  324. if (ioctl(s->container, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU)) {
  325. error_setg_errno(errp, errno, "Failed to set VFIO IOMMU type");
  326. ret = -errno;
  327. goto fail;
  328. }
  329. iommu_info = g_malloc0(iommu_info_size);
  330. iommu_info->argsz = iommu_info_size;
  331. /* Get additional IOMMU info */
  332. if (ioctl(s->container, VFIO_IOMMU_GET_INFO, iommu_info)) {
  333. error_setg_errno(errp, errno, "Failed to get IOMMU info");
  334. ret = -errno;
  335. goto fail;
  336. }
  337. /*
  338. * if the kernel does not report usable IOVA regions, choose
  339. * the legacy [QEMU_VFIO_IOVA_MIN, QEMU_VFIO_IOVA_MAX -1] region
  340. */
  341. s->nb_iova_ranges = 1;
  342. s->usable_iova_ranges = g_new0(struct IOVARange, 1);
  343. s->usable_iova_ranges[0].start = QEMU_VFIO_IOVA_MIN;
  344. s->usable_iova_ranges[0].end = QEMU_VFIO_IOVA_MAX - 1;
  345. if (iommu_info->argsz > iommu_info_size) {
  346. iommu_info_size = iommu_info->argsz;
  347. iommu_info = g_realloc(iommu_info, iommu_info_size);
  348. if (ioctl(s->container, VFIO_IOMMU_GET_INFO, iommu_info)) {
  349. ret = -errno;
  350. goto fail;
  351. }
  352. collect_usable_iova_ranges(s, iommu_info);
  353. }
  354. s->device = ioctl(s->group, VFIO_GROUP_GET_DEVICE_FD, device);
  355. if (s->device < 0) {
  356. error_setg_errno(errp, errno, "Failed to get device fd");
  357. ret = -errno;
  358. goto fail;
  359. }
  360. /* Test and setup the device */
  361. if (ioctl(s->device, VFIO_DEVICE_GET_INFO, &device_info)) {
  362. error_setg_errno(errp, errno, "Failed to get device info");
  363. ret = -errno;
  364. goto fail;
  365. }
  366. if (device_info.num_regions < VFIO_PCI_CONFIG_REGION_INDEX) {
  367. error_setg(errp, "Invalid device regions");
  368. ret = -EINVAL;
  369. goto fail;
  370. }
  371. s->config_region_info = (struct vfio_region_info) {
  372. .index = VFIO_PCI_CONFIG_REGION_INDEX,
  373. .argsz = sizeof(struct vfio_region_info),
  374. };
  375. if (ioctl(s->device, VFIO_DEVICE_GET_REGION_INFO, &s->config_region_info)) {
  376. error_setg_errno(errp, errno, "Failed to get config region info");
  377. ret = -errno;
  378. goto fail;
  379. }
  380. trace_qemu_vfio_region_info("config", s->config_region_info.offset,
  381. s->config_region_info.size,
  382. s->config_region_info.cap_offset);
  383. for (i = 0; i < ARRAY_SIZE(s->bar_region_info); i++) {
  384. ret = qemu_vfio_pci_init_bar(s, i, errp);
  385. if (ret) {
  386. goto fail;
  387. }
  388. }
  389. /* Enable bus master */
  390. ret = qemu_vfio_pci_read_config(s, &pci_cmd, sizeof(pci_cmd), PCI_COMMAND);
  391. if (ret) {
  392. goto fail;
  393. }
  394. pci_cmd |= PCI_COMMAND_MASTER;
  395. ret = qemu_vfio_pci_write_config(s, &pci_cmd, sizeof(pci_cmd), PCI_COMMAND);
  396. if (ret) {
  397. goto fail;
  398. }
  399. g_free(iommu_info);
  400. return 0;
  401. fail:
  402. g_free(s->usable_iova_ranges);
  403. s->usable_iova_ranges = NULL;
  404. s->nb_iova_ranges = 0;
  405. g_free(iommu_info);
  406. close(s->group);
  407. fail_container:
  408. close(s->container);
  409. return ret;
  410. }
  411. static void qemu_vfio_ram_block_added(RAMBlockNotifier *n, void *host,
  412. size_t size, size_t max_size)
  413. {
  414. QEMUVFIOState *s = container_of(n, QEMUVFIOState, ram_notifier);
  415. Error *local_err = NULL;
  416. int ret;
  417. trace_qemu_vfio_ram_block_added(s, host, max_size);
  418. ret = qemu_vfio_dma_map(s, host, max_size, false, NULL, &local_err);
  419. if (ret) {
  420. error_reportf_err(local_err,
  421. "qemu_vfio_dma_map(%p, %zu) failed: ",
  422. host, max_size);
  423. }
  424. }
  425. static void qemu_vfio_ram_block_removed(RAMBlockNotifier *n, void *host,
  426. size_t size, size_t max_size)
  427. {
  428. QEMUVFIOState *s = container_of(n, QEMUVFIOState, ram_notifier);
  429. if (host) {
  430. trace_qemu_vfio_ram_block_removed(s, host, max_size);
  431. qemu_vfio_dma_unmap(s, host);
  432. }
  433. }
  434. static void qemu_vfio_open_common(QEMUVFIOState *s)
  435. {
  436. qemu_mutex_init(&s->lock);
  437. s->ram_notifier.ram_block_added = qemu_vfio_ram_block_added;
  438. s->ram_notifier.ram_block_removed = qemu_vfio_ram_block_removed;
  439. s->low_water_mark = QEMU_VFIO_IOVA_MIN;
  440. s->high_water_mark = QEMU_VFIO_IOVA_MAX;
  441. ram_block_notifier_add(&s->ram_notifier);
  442. }
  443. /**
  444. * Open a PCI device, e.g. "0000:00:01.0".
  445. */
  446. QEMUVFIOState *qemu_vfio_open_pci(const char *device, Error **errp)
  447. {
  448. int r;
  449. QEMUVFIOState *s = g_new0(QEMUVFIOState, 1);
  450. /*
  451. * VFIO may pin all memory inside mappings, resulting it in pinning
  452. * all memory inside RAM blocks unconditionally.
  453. */
  454. r = ram_block_discard_disable(true);
  455. if (r) {
  456. error_setg_errno(errp, -r, "Cannot set discarding of RAM broken");
  457. g_free(s);
  458. return NULL;
  459. }
  460. r = qemu_vfio_init_pci(s, device, errp);
  461. if (r) {
  462. ram_block_discard_disable(false);
  463. g_free(s);
  464. return NULL;
  465. }
  466. qemu_vfio_open_common(s);
  467. return s;
  468. }
  469. static void qemu_vfio_dump_mappings(QEMUVFIOState *s)
  470. {
  471. for (int i = 0; i < s->nr_mappings; ++i) {
  472. trace_qemu_vfio_dump_mapping(s->mappings[i].host,
  473. s->mappings[i].iova,
  474. s->mappings[i].size);
  475. }
  476. }
  477. /**
  478. * Find the mapping entry that contains [host, host + size) and set @index to
  479. * the position. If no entry contains it, @index is the position _after_ which
  480. * to insert the new mapping. IOW, it is the index of the largest element that
  481. * is smaller than @host, or -1 if no entry is.
  482. */
  483. static IOVAMapping *qemu_vfio_find_mapping(QEMUVFIOState *s, void *host,
  484. int *index)
  485. {
  486. IOVAMapping *p = s->mappings;
  487. IOVAMapping *q = p ? p + s->nr_mappings - 1 : NULL;
  488. IOVAMapping *mid;
  489. trace_qemu_vfio_find_mapping(s, host);
  490. if (!p) {
  491. *index = -1;
  492. return NULL;
  493. }
  494. while (true) {
  495. mid = p + (q - p) / 2;
  496. if (mid == p) {
  497. break;
  498. }
  499. if (mid->host > host) {
  500. q = mid;
  501. } else if (mid->host < host) {
  502. p = mid;
  503. } else {
  504. break;
  505. }
  506. }
  507. if (mid->host > host) {
  508. mid--;
  509. } else if (mid < &s->mappings[s->nr_mappings - 1]
  510. && (mid + 1)->host <= host) {
  511. mid++;
  512. }
  513. *index = mid - &s->mappings[0];
  514. if (mid >= &s->mappings[0] &&
  515. mid->host <= host && mid->host + mid->size > host) {
  516. assert(mid < &s->mappings[s->nr_mappings]);
  517. return mid;
  518. }
  519. /* At this point *index + 1 is the right position to insert the new
  520. * mapping.*/
  521. return NULL;
  522. }
  523. /**
  524. * Allocate IOVA and create a new mapping record and insert it in @s.
  525. */
  526. static IOVAMapping *qemu_vfio_add_mapping(QEMUVFIOState *s,
  527. void *host, size_t size,
  528. int index, uint64_t iova)
  529. {
  530. int shift;
  531. IOVAMapping m = {.host = host, .size = size, .iova = iova};
  532. IOVAMapping *insert;
  533. assert(QEMU_IS_ALIGNED(size, qemu_real_host_page_size()));
  534. assert(QEMU_IS_ALIGNED(s->low_water_mark, qemu_real_host_page_size()));
  535. assert(QEMU_IS_ALIGNED(s->high_water_mark, qemu_real_host_page_size()));
  536. trace_qemu_vfio_new_mapping(s, host, size, index, iova);
  537. assert(index >= 0);
  538. s->nr_mappings++;
  539. s->mappings = g_renew(IOVAMapping, s->mappings, s->nr_mappings);
  540. insert = &s->mappings[index];
  541. shift = s->nr_mappings - index - 1;
  542. if (shift) {
  543. memmove(insert + 1, insert, shift * sizeof(s->mappings[0]));
  544. }
  545. *insert = m;
  546. return insert;
  547. }
  548. /* Do the DMA mapping with VFIO. */
  549. static int qemu_vfio_do_mapping(QEMUVFIOState *s, void *host, size_t size,
  550. uint64_t iova, Error **errp)
  551. {
  552. struct vfio_iommu_type1_dma_map dma_map = {
  553. .argsz = sizeof(dma_map),
  554. .flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE,
  555. .iova = iova,
  556. .vaddr = (uintptr_t)host,
  557. .size = size,
  558. };
  559. trace_qemu_vfio_do_mapping(s, host, iova, size);
  560. if (ioctl(s->container, VFIO_IOMMU_MAP_DMA, &dma_map)) {
  561. error_setg_errno(errp, errno, "VFIO_MAP_DMA failed");
  562. return -errno;
  563. }
  564. return 0;
  565. }
  566. /**
  567. * Undo the DMA mapping from @s with VFIO, and remove from mapping list.
  568. */
  569. static void qemu_vfio_undo_mapping(QEMUVFIOState *s, IOVAMapping *mapping,
  570. Error **errp)
  571. {
  572. int index;
  573. struct vfio_iommu_type1_dma_unmap unmap = {
  574. .argsz = sizeof(unmap),
  575. .flags = 0,
  576. .iova = mapping->iova,
  577. .size = mapping->size,
  578. };
  579. index = mapping - s->mappings;
  580. assert(mapping->size > 0);
  581. assert(QEMU_IS_ALIGNED(mapping->size, qemu_real_host_page_size()));
  582. assert(index >= 0 && index < s->nr_mappings);
  583. if (ioctl(s->container, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
  584. error_setg_errno(errp, errno, "VFIO_UNMAP_DMA failed");
  585. }
  586. memmove(mapping, &s->mappings[index + 1],
  587. sizeof(s->mappings[0]) * (s->nr_mappings - index - 1));
  588. s->nr_mappings--;
  589. s->mappings = g_renew(IOVAMapping, s->mappings, s->nr_mappings);
  590. }
  591. /* Check if the mapping list is (ascending) ordered. */
  592. static bool qemu_vfio_verify_mappings(QEMUVFIOState *s)
  593. {
  594. int i;
  595. if (QEMU_VFIO_DEBUG) {
  596. for (i = 0; i < s->nr_mappings - 1; ++i) {
  597. if (!(s->mappings[i].host < s->mappings[i + 1].host)) {
  598. error_report("item %d not sorted!", i);
  599. qemu_vfio_dump_mappings(s);
  600. return false;
  601. }
  602. if (!(s->mappings[i].host + s->mappings[i].size <=
  603. s->mappings[i + 1].host)) {
  604. error_report("item %d overlap with next!", i);
  605. qemu_vfio_dump_mappings(s);
  606. return false;
  607. }
  608. }
  609. }
  610. return true;
  611. }
  612. static bool qemu_vfio_find_fixed_iova(QEMUVFIOState *s, size_t size,
  613. uint64_t *iova, Error **errp)
  614. {
  615. int i;
  616. for (i = 0; i < s->nb_iova_ranges; i++) {
  617. if (s->usable_iova_ranges[i].end < s->low_water_mark) {
  618. continue;
  619. }
  620. s->low_water_mark =
  621. MAX(s->low_water_mark, s->usable_iova_ranges[i].start);
  622. if (s->usable_iova_ranges[i].end - s->low_water_mark + 1 >= size ||
  623. s->usable_iova_ranges[i].end - s->low_water_mark + 1 == 0) {
  624. *iova = s->low_water_mark;
  625. s->low_water_mark += size;
  626. return true;
  627. }
  628. }
  629. error_setg(errp, "fixed iova range not found");
  630. return false;
  631. }
  632. static bool qemu_vfio_find_temp_iova(QEMUVFIOState *s, size_t size,
  633. uint64_t *iova, Error **errp)
  634. {
  635. int i;
  636. for (i = s->nb_iova_ranges - 1; i >= 0; i--) {
  637. if (s->usable_iova_ranges[i].start > s->high_water_mark) {
  638. continue;
  639. }
  640. s->high_water_mark =
  641. MIN(s->high_water_mark, s->usable_iova_ranges[i].end + 1);
  642. if (s->high_water_mark - s->usable_iova_ranges[i].start + 1 >= size ||
  643. s->high_water_mark - s->usable_iova_ranges[i].start + 1 == 0) {
  644. *iova = s->high_water_mark - size;
  645. s->high_water_mark = *iova;
  646. return true;
  647. }
  648. }
  649. error_setg(errp, "temporary iova range not found");
  650. return false;
  651. }
  652. /**
  653. * qemu_vfio_water_mark_reached:
  654. *
  655. * Returns %true if high watermark has been reached, %false otherwise.
  656. */
  657. static bool qemu_vfio_water_mark_reached(QEMUVFIOState *s, size_t size,
  658. Error **errp)
  659. {
  660. if (s->high_water_mark - s->low_water_mark + 1 < size) {
  661. error_setg(errp, "iova exhausted (water mark reached)");
  662. return true;
  663. }
  664. return false;
  665. }
  666. /* Map [host, host + size) area into a contiguous IOVA address space, and store
  667. * the result in @iova if not NULL. The caller need to make sure the area is
  668. * aligned to page size, and mustn't overlap with existing mapping areas (split
  669. * mapping status within this area is not allowed).
  670. */
  671. int qemu_vfio_dma_map(QEMUVFIOState *s, void *host, size_t size,
  672. bool temporary, uint64_t *iova, Error **errp)
  673. {
  674. int index;
  675. IOVAMapping *mapping;
  676. uint64_t iova0;
  677. assert(QEMU_PTR_IS_ALIGNED(host, qemu_real_host_page_size()));
  678. assert(QEMU_IS_ALIGNED(size, qemu_real_host_page_size()));
  679. trace_qemu_vfio_dma_map(s, host, size, temporary, iova);
  680. QEMU_LOCK_GUARD(&s->lock);
  681. mapping = qemu_vfio_find_mapping(s, host, &index);
  682. if (mapping) {
  683. iova0 = mapping->iova + ((uint8_t *)host - (uint8_t *)mapping->host);
  684. } else {
  685. int ret;
  686. if (qemu_vfio_water_mark_reached(s, size, errp)) {
  687. return -ENOMEM;
  688. }
  689. if (!temporary) {
  690. if (!qemu_vfio_find_fixed_iova(s, size, &iova0, errp)) {
  691. return -ENOMEM;
  692. }
  693. mapping = qemu_vfio_add_mapping(s, host, size, index + 1, iova0);
  694. assert(qemu_vfio_verify_mappings(s));
  695. ret = qemu_vfio_do_mapping(s, host, size, iova0, errp);
  696. if (ret < 0) {
  697. qemu_vfio_undo_mapping(s, mapping, NULL);
  698. return ret;
  699. }
  700. qemu_vfio_dump_mappings(s);
  701. } else {
  702. if (!qemu_vfio_find_temp_iova(s, size, &iova0, errp)) {
  703. return -ENOMEM;
  704. }
  705. ret = qemu_vfio_do_mapping(s, host, size, iova0, errp);
  706. if (ret < 0) {
  707. return ret;
  708. }
  709. }
  710. }
  711. trace_qemu_vfio_dma_mapped(s, host, iova0, size);
  712. if (iova) {
  713. *iova = iova0;
  714. }
  715. return 0;
  716. }
  717. /* Reset the high watermark and free all "temporary" mappings. */
  718. int qemu_vfio_dma_reset_temporary(QEMUVFIOState *s)
  719. {
  720. struct vfio_iommu_type1_dma_unmap unmap = {
  721. .argsz = sizeof(unmap),
  722. .flags = 0,
  723. .iova = s->high_water_mark,
  724. .size = QEMU_VFIO_IOVA_MAX - s->high_water_mark,
  725. };
  726. trace_qemu_vfio_dma_reset_temporary(s);
  727. QEMU_LOCK_GUARD(&s->lock);
  728. if (ioctl(s->container, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
  729. error_report("VFIO_UNMAP_DMA failed: %s", strerror(errno));
  730. return -errno;
  731. }
  732. s->high_water_mark = QEMU_VFIO_IOVA_MAX;
  733. return 0;
  734. }
  735. /* Unmapping the whole area that was previously mapped with
  736. * qemu_vfio_dma_map(). */
  737. void qemu_vfio_dma_unmap(QEMUVFIOState *s, void *host)
  738. {
  739. int index = 0;
  740. IOVAMapping *m;
  741. if (!host) {
  742. return;
  743. }
  744. trace_qemu_vfio_dma_unmap(s, host);
  745. QEMU_LOCK_GUARD(&s->lock);
  746. m = qemu_vfio_find_mapping(s, host, &index);
  747. if (!m) {
  748. return;
  749. }
  750. qemu_vfio_undo_mapping(s, m, NULL);
  751. }
  752. static void qemu_vfio_reset(QEMUVFIOState *s)
  753. {
  754. ioctl(s->device, VFIO_DEVICE_RESET);
  755. }
  756. /* Close and free the VFIO resources. */
  757. void qemu_vfio_close(QEMUVFIOState *s)
  758. {
  759. int i;
  760. if (!s) {
  761. return;
  762. }
  763. ram_block_notifier_remove(&s->ram_notifier);
  764. for (i = 0; i < s->nr_mappings; ++i) {
  765. qemu_vfio_undo_mapping(s, &s->mappings[i], NULL);
  766. }
  767. g_free(s->usable_iova_ranges);
  768. s->nb_iova_ranges = 0;
  769. qemu_vfio_reset(s);
  770. close(s->device);
  771. close(s->group);
  772. close(s->container);
  773. ram_block_discard_disable(false);
  774. }