xref: /qemu/hw/vfio/iommufd.c (revision e3404e01)
1 /*
2  * iommufd container backend
3  *
4  * Copyright (C) 2023 Intel Corporation.
5  * Copyright Red Hat, Inc. 2023
6  *
7  * Authors: Yi Liu <yi.l.liu@intel.com>
8  *          Eric Auger <eric.auger@redhat.com>
9  *
10  * SPDX-License-Identifier: GPL-2.0-or-later
11  */
12 
13 #include "qemu/osdep.h"
14 #include <sys/ioctl.h>
15 #include <linux/vfio.h>
16 #include <linux/iommufd.h>
17 
18 #include "hw/vfio/vfio-common.h"
19 #include "qemu/error-report.h"
20 #include "trace.h"
21 #include "qapi/error.h"
22 #include "sysemu/iommufd.h"
23 #include "hw/qdev-core.h"
24 #include "sysemu/reset.h"
25 #include "qemu/cutils.h"
26 #include "qemu/chardev_open.h"
27 #include "pci.h"
28 
29 static int iommufd_cdev_map(const VFIOContainerBase *bcontainer, hwaddr iova,
30                             ram_addr_t size, void *vaddr, bool readonly)
31 {
32     const VFIOIOMMUFDContainer *container =
33         container_of(bcontainer, VFIOIOMMUFDContainer, bcontainer);
34 
35     return iommufd_backend_map_dma(container->be,
36                                    container->ioas_id,
37                                    iova, size, vaddr, readonly);
38 }
39 
40 static int iommufd_cdev_unmap(const VFIOContainerBase *bcontainer,
41                               hwaddr iova, ram_addr_t size,
42                               IOMMUTLBEntry *iotlb)
43 {
44     const VFIOIOMMUFDContainer *container =
45         container_of(bcontainer, VFIOIOMMUFDContainer, bcontainer);
46 
47     /* TODO: Handle dma_unmap_bitmap with iotlb args (migration) */
48     return iommufd_backend_unmap_dma(container->be,
49                                      container->ioas_id, iova, size);
50 }
51 
52 static int iommufd_cdev_kvm_device_add(VFIODevice *vbasedev, Error **errp)
53 {
54     return vfio_kvm_device_add_fd(vbasedev->fd, errp);
55 }
56 
57 static void iommufd_cdev_kvm_device_del(VFIODevice *vbasedev)
58 {
59     Error *err = NULL;
60 
61     if (vfio_kvm_device_del_fd(vbasedev->fd, &err)) {
62         error_report_err(err);
63     }
64 }
65 
66 static int iommufd_cdev_connect_and_bind(VFIODevice *vbasedev, Error **errp)
67 {
68     IOMMUFDBackend *iommufd = vbasedev->iommufd;
69     struct vfio_device_bind_iommufd bind = {
70         .argsz = sizeof(bind),
71         .flags = 0,
72     };
73     int ret;
74 
75     ret = iommufd_backend_connect(iommufd, errp);
76     if (ret) {
77         return ret;
78     }
79 
80     /*
81      * Add device to kvm-vfio to be prepared for the tracking
82      * in KVM. Especially for some emulated devices, it requires
83      * to have kvm information in the device open.
84      */
85     ret = iommufd_cdev_kvm_device_add(vbasedev, errp);
86     if (ret) {
87         goto err_kvm_device_add;
88     }
89 
90     /* Bind device to iommufd */
91     bind.iommufd = iommufd->fd;
92     ret = ioctl(vbasedev->fd, VFIO_DEVICE_BIND_IOMMUFD, &bind);
93     if (ret) {
94         error_setg_errno(errp, errno, "error bind device fd=%d to iommufd=%d",
95                          vbasedev->fd, bind.iommufd);
96         goto err_bind;
97     }
98 
99     vbasedev->devid = bind.out_devid;
100     trace_iommufd_cdev_connect_and_bind(bind.iommufd, vbasedev->name,
101                                         vbasedev->fd, vbasedev->devid);
102     return ret;
103 err_bind:
104     iommufd_cdev_kvm_device_del(vbasedev);
105 err_kvm_device_add:
106     iommufd_backend_disconnect(iommufd);
107     return ret;
108 }
109 
110 static void iommufd_cdev_unbind_and_disconnect(VFIODevice *vbasedev)
111 {
112     /* Unbind is automatically conducted when device fd is closed */
113     iommufd_cdev_kvm_device_del(vbasedev);
114     iommufd_backend_disconnect(vbasedev->iommufd);
115 }
116 
117 static int iommufd_cdev_getfd(const char *sysfs_path, Error **errp)
118 {
119     ERRP_GUARD();
120     long int ret = -ENOTTY;
121     g_autofree char *path = NULL;
122     g_autofree char *vfio_dev_path = NULL;
123     g_autofree char *vfio_path = NULL;
124     DIR *dir = NULL;
125     struct dirent *dent;
126     g_autofree gchar *contents = NULL;
127     gsize length;
128     int major, minor;
129     dev_t vfio_devt;
130 
131     path = g_strdup_printf("%s/vfio-dev", sysfs_path);
132     dir = opendir(path);
133     if (!dir) {
134         error_setg_errno(errp, errno, "couldn't open directory %s", path);
135         goto out;
136     }
137 
138     while ((dent = readdir(dir))) {
139         if (!strncmp(dent->d_name, "vfio", 4)) {
140             vfio_dev_path = g_strdup_printf("%s/%s/dev", path, dent->d_name);
141             break;
142         }
143     }
144 
145     if (!vfio_dev_path) {
146         error_setg(errp, "failed to find vfio-dev/vfioX/dev");
147         goto out_close_dir;
148     }
149 
150     if (!g_file_get_contents(vfio_dev_path, &contents, &length, NULL)) {
151         error_setg(errp, "failed to load \"%s\"", vfio_dev_path);
152         goto out_close_dir;
153     }
154 
155     if (sscanf(contents, "%d:%d", &major, &minor) != 2) {
156         error_setg(errp, "failed to get major:minor for \"%s\"", vfio_dev_path);
157         goto out_close_dir;
158     }
159     vfio_devt = makedev(major, minor);
160 
161     vfio_path = g_strdup_printf("/dev/vfio/devices/%s", dent->d_name);
162     ret = open_cdev(vfio_path, vfio_devt);
163     if (ret < 0) {
164         error_setg(errp, "Failed to open %s", vfio_path);
165     }
166 
167     trace_iommufd_cdev_getfd(vfio_path, ret);
168 
169 out_close_dir:
170     closedir(dir);
171 out:
172     if (*errp) {
173         error_prepend(errp, VFIO_MSG_PREFIX, path);
174     }
175 
176     return ret;
177 }
178 
179 static int iommufd_cdev_attach_ioas_hwpt(VFIODevice *vbasedev, uint32_t id,
180                                          Error **errp)
181 {
182     int ret, iommufd = vbasedev->iommufd->fd;
183     struct vfio_device_attach_iommufd_pt attach_data = {
184         .argsz = sizeof(attach_data),
185         .flags = 0,
186         .pt_id = id,
187     };
188 
189     /* Attach device to an IOAS or hwpt within iommufd */
190     ret = ioctl(vbasedev->fd, VFIO_DEVICE_ATTACH_IOMMUFD_PT, &attach_data);
191     if (ret) {
192         error_setg_errno(errp, errno,
193                          "[iommufd=%d] error attach %s (%d) to id=%d",
194                          iommufd, vbasedev->name, vbasedev->fd, id);
195     } else {
196         trace_iommufd_cdev_attach_ioas_hwpt(iommufd, vbasedev->name,
197                                             vbasedev->fd, id);
198     }
199     return ret;
200 }
201 
202 static int iommufd_cdev_detach_ioas_hwpt(VFIODevice *vbasedev, Error **errp)
203 {
204     int ret, iommufd = vbasedev->iommufd->fd;
205     struct vfio_device_detach_iommufd_pt detach_data = {
206         .argsz = sizeof(detach_data),
207         .flags = 0,
208     };
209 
210     ret = ioctl(vbasedev->fd, VFIO_DEVICE_DETACH_IOMMUFD_PT, &detach_data);
211     if (ret) {
212         error_setg_errno(errp, errno, "detach %s failed", vbasedev->name);
213     } else {
214         trace_iommufd_cdev_detach_ioas_hwpt(iommufd, vbasedev->name);
215     }
216     return ret;
217 }
218 
219 static int iommufd_cdev_attach_container(VFIODevice *vbasedev,
220                                          VFIOIOMMUFDContainer *container,
221                                          Error **errp)
222 {
223     return iommufd_cdev_attach_ioas_hwpt(vbasedev, container->ioas_id, errp);
224 }
225 
226 static void iommufd_cdev_detach_container(VFIODevice *vbasedev,
227                                           VFIOIOMMUFDContainer *container)
228 {
229     Error *err = NULL;
230 
231     if (iommufd_cdev_detach_ioas_hwpt(vbasedev, &err)) {
232         error_report_err(err);
233     }
234 }
235 
236 static void iommufd_cdev_container_destroy(VFIOIOMMUFDContainer *container)
237 {
238     VFIOContainerBase *bcontainer = &container->bcontainer;
239 
240     if (!QLIST_EMPTY(&bcontainer->device_list)) {
241         return;
242     }
243     memory_listener_unregister(&bcontainer->listener);
244     vfio_container_destroy(bcontainer);
245     iommufd_backend_free_id(container->be, container->ioas_id);
246     g_free(container);
247 }
248 
249 static int iommufd_cdev_ram_block_discard_disable(bool state)
250 {
251     /*
252      * We support coordinated discarding of RAM via the RamDiscardManager.
253      */
254     return ram_block_uncoordinated_discard_disable(state);
255 }
256 
257 static int iommufd_cdev_get_info_iova_range(VFIOIOMMUFDContainer *container,
258                                             uint32_t ioas_id, Error **errp)
259 {
260     VFIOContainerBase *bcontainer = &container->bcontainer;
261     struct iommu_ioas_iova_ranges *info;
262     struct iommu_iova_range *iova_ranges;
263     int ret, sz, fd = container->be->fd;
264 
265     info = g_malloc0(sizeof(*info));
266     info->size = sizeof(*info);
267     info->ioas_id = ioas_id;
268 
269     ret = ioctl(fd, IOMMU_IOAS_IOVA_RANGES, info);
270     if (ret && errno != EMSGSIZE) {
271         goto error;
272     }
273 
274     sz = info->num_iovas * sizeof(struct iommu_iova_range);
275     info = g_realloc(info, sizeof(*info) + sz);
276     info->allowed_iovas = (uintptr_t)(info + 1);
277 
278     ret = ioctl(fd, IOMMU_IOAS_IOVA_RANGES, info);
279     if (ret) {
280         goto error;
281     }
282 
283     iova_ranges = (struct iommu_iova_range *)(uintptr_t)info->allowed_iovas;
284 
285     for (int i = 0; i < info->num_iovas; i++) {
286         Range *range = g_new(Range, 1);
287 
288         range_set_bounds(range, iova_ranges[i].start, iova_ranges[i].last);
289         bcontainer->iova_ranges =
290             range_list_insert(bcontainer->iova_ranges, range);
291     }
292     bcontainer->pgsizes = info->out_iova_alignment;
293 
294     g_free(info);
295     return 0;
296 
297 error:
298     ret = -errno;
299     g_free(info);
300     error_setg_errno(errp, errno, "Cannot get IOVA ranges");
301     return ret;
302 }
303 
304 static int iommufd_cdev_attach(const char *name, VFIODevice *vbasedev,
305                                AddressSpace *as, Error **errp)
306 {
307     VFIOContainerBase *bcontainer;
308     VFIOIOMMUFDContainer *container;
309     VFIOAddressSpace *space;
310     struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
311     int ret, devfd;
312     uint32_t ioas_id;
313     Error *err = NULL;
314     const VFIOIOMMUClass *iommufd_vioc =
315         VFIO_IOMMU_CLASS(object_class_by_name(TYPE_VFIO_IOMMU_IOMMUFD));
316 
317     if (vbasedev->fd < 0) {
318         devfd = iommufd_cdev_getfd(vbasedev->sysfsdev, errp);
319         if (devfd < 0) {
320             return devfd;
321         }
322         vbasedev->fd = devfd;
323     } else {
324         devfd = vbasedev->fd;
325     }
326 
327     ret = iommufd_cdev_connect_and_bind(vbasedev, errp);
328     if (ret) {
329         goto err_connect_bind;
330     }
331 
332     space = vfio_get_address_space(as);
333 
334     /* try to attach to an existing container in this space */
335     QLIST_FOREACH(bcontainer, &space->containers, next) {
336         container = container_of(bcontainer, VFIOIOMMUFDContainer, bcontainer);
337         if (bcontainer->ops != iommufd_vioc ||
338             vbasedev->iommufd != container->be) {
339             continue;
340         }
341         if (iommufd_cdev_attach_container(vbasedev, container, &err)) {
342             const char *msg = error_get_pretty(err);
343 
344             trace_iommufd_cdev_fail_attach_existing_container(msg);
345             error_free(err);
346             err = NULL;
347         } else {
348             ret = iommufd_cdev_ram_block_discard_disable(true);
349             if (ret) {
350                 error_setg(errp,
351                               "Cannot set discarding of RAM broken (%d)", ret);
352                 goto err_discard_disable;
353             }
354             goto found_container;
355         }
356     }
357 
358     /* Need to allocate a new dedicated container */
359     ret = iommufd_backend_alloc_ioas(vbasedev->iommufd, &ioas_id, errp);
360     if (ret < 0) {
361         goto err_alloc_ioas;
362     }
363 
364     trace_iommufd_cdev_alloc_ioas(vbasedev->iommufd->fd, ioas_id);
365 
366     container = g_malloc0(sizeof(*container));
367     container->be = vbasedev->iommufd;
368     container->ioas_id = ioas_id;
369 
370     bcontainer = &container->bcontainer;
371     vfio_container_init(bcontainer, space, iommufd_vioc);
372     QLIST_INSERT_HEAD(&space->containers, bcontainer, next);
373 
374     ret = iommufd_cdev_attach_container(vbasedev, container, errp);
375     if (ret) {
376         goto err_attach_container;
377     }
378 
379     ret = iommufd_cdev_ram_block_discard_disable(true);
380     if (ret) {
381         goto err_discard_disable;
382     }
383 
384     ret = iommufd_cdev_get_info_iova_range(container, ioas_id, &err);
385     if (ret) {
386         error_append_hint(&err,
387                    "Fallback to default 64bit IOVA range and 4K page size\n");
388         warn_report_err(err);
389         err = NULL;
390         bcontainer->pgsizes = qemu_real_host_page_size();
391     }
392 
393     bcontainer->listener = vfio_memory_listener;
394     memory_listener_register(&bcontainer->listener, bcontainer->space->as);
395 
396     if (bcontainer->error) {
397         ret = -1;
398         error_propagate_prepend(errp, bcontainer->error,
399                                 "memory listener initialization failed: ");
400         goto err_listener_register;
401     }
402 
403     bcontainer->initialized = true;
404 
405 found_container:
406     ret = ioctl(devfd, VFIO_DEVICE_GET_INFO, &dev_info);
407     if (ret) {
408         error_setg_errno(errp, errno, "error getting device info");
409         goto err_listener_register;
410     }
411 
412     ret = vfio_cpr_register_container(bcontainer, errp);
413     if (ret) {
414         goto err_listener_register;
415     }
416 
417     /*
418      * TODO: examine RAM_BLOCK_DISCARD stuff, should we do group level
419      * for discarding incompatibility check as well?
420      */
421     if (vbasedev->ram_block_discard_allowed) {
422         iommufd_cdev_ram_block_discard_disable(false);
423     }
424 
425     vbasedev->group = 0;
426     vbasedev->num_irqs = dev_info.num_irqs;
427     vbasedev->num_regions = dev_info.num_regions;
428     vbasedev->flags = dev_info.flags;
429     vbasedev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
430     vbasedev->bcontainer = bcontainer;
431     QLIST_INSERT_HEAD(&bcontainer->device_list, vbasedev, container_next);
432     QLIST_INSERT_HEAD(&vfio_device_list, vbasedev, global_next);
433 
434     trace_iommufd_cdev_device_info(vbasedev->name, devfd, vbasedev->num_irqs,
435                                    vbasedev->num_regions, vbasedev->flags);
436     return 0;
437 
438 err_listener_register:
439     iommufd_cdev_ram_block_discard_disable(false);
440 err_discard_disable:
441     iommufd_cdev_detach_container(vbasedev, container);
442 err_attach_container:
443     iommufd_cdev_container_destroy(container);
444 err_alloc_ioas:
445     vfio_put_address_space(space);
446     iommufd_cdev_unbind_and_disconnect(vbasedev);
447 err_connect_bind:
448     close(vbasedev->fd);
449     return ret;
450 }
451 
452 static void iommufd_cdev_detach(VFIODevice *vbasedev)
453 {
454     VFIOContainerBase *bcontainer = vbasedev->bcontainer;
455     VFIOAddressSpace *space = bcontainer->space;
456     VFIOIOMMUFDContainer *container = container_of(bcontainer,
457                                                    VFIOIOMMUFDContainer,
458                                                    bcontainer);
459     QLIST_REMOVE(vbasedev, global_next);
460     QLIST_REMOVE(vbasedev, container_next);
461     vbasedev->bcontainer = NULL;
462 
463     if (!vbasedev->ram_block_discard_allowed) {
464         iommufd_cdev_ram_block_discard_disable(false);
465     }
466 
467     vfio_cpr_unregister_container(bcontainer);
468     iommufd_cdev_detach_container(vbasedev, container);
469     iommufd_cdev_container_destroy(container);
470     vfio_put_address_space(space);
471 
472     iommufd_cdev_unbind_and_disconnect(vbasedev);
473     close(vbasedev->fd);
474 }
475 
476 static VFIODevice *iommufd_cdev_pci_find_by_devid(__u32 devid)
477 {
478     VFIODevice *vbasedev_iter;
479     const VFIOIOMMUClass *iommufd_vioc =
480         VFIO_IOMMU_CLASS(object_class_by_name(TYPE_VFIO_IOMMU_IOMMUFD));
481 
482     QLIST_FOREACH(vbasedev_iter, &vfio_device_list, global_next) {
483         if (vbasedev_iter->bcontainer->ops != iommufd_vioc) {
484             continue;
485         }
486         if (devid == vbasedev_iter->devid) {
487             return vbasedev_iter;
488         }
489     }
490     return NULL;
491 }
492 
493 static VFIOPCIDevice *
494 iommufd_cdev_dep_get_realized_vpdev(struct vfio_pci_dependent_device *dep_dev,
495                                     VFIODevice *reset_dev)
496 {
497     VFIODevice *vbasedev_tmp;
498 
499     if (dep_dev->devid == reset_dev->devid ||
500         dep_dev->devid == VFIO_PCI_DEVID_OWNED) {
501         return NULL;
502     }
503 
504     vbasedev_tmp = iommufd_cdev_pci_find_by_devid(dep_dev->devid);
505     if (!vbasedev_tmp || !vbasedev_tmp->dev->realized ||
506         vbasedev_tmp->type != VFIO_DEVICE_TYPE_PCI) {
507         return NULL;
508     }
509 
510     return container_of(vbasedev_tmp, VFIOPCIDevice, vbasedev);
511 }
512 
513 static int iommufd_cdev_pci_hot_reset(VFIODevice *vbasedev, bool single)
514 {
515     VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
516     struct vfio_pci_hot_reset_info *info = NULL;
517     struct vfio_pci_dependent_device *devices;
518     struct vfio_pci_hot_reset *reset;
519     int ret, i;
520     bool multi = false;
521 
522     trace_vfio_pci_hot_reset(vdev->vbasedev.name, single ? "one" : "multi");
523 
524     if (!single) {
525         vfio_pci_pre_reset(vdev);
526     }
527     vdev->vbasedev.needs_reset = false;
528 
529     ret = vfio_pci_get_pci_hot_reset_info(vdev, &info);
530 
531     if (ret) {
532         goto out_single;
533     }
534 
535     assert(info->flags & VFIO_PCI_HOT_RESET_FLAG_DEV_ID);
536 
537     devices = &info->devices[0];
538 
539     if (!(info->flags & VFIO_PCI_HOT_RESET_FLAG_DEV_ID_OWNED)) {
540         if (!vdev->has_pm_reset) {
541             for (i = 0; i < info->count; i++) {
542                 if (devices[i].devid == VFIO_PCI_DEVID_NOT_OWNED) {
543                     error_report("vfio: Cannot reset device %s, "
544                                  "depends on device %04x:%02x:%02x.%x "
545                                  "which is not owned.",
546                                  vdev->vbasedev.name, devices[i].segment,
547                                  devices[i].bus, PCI_SLOT(devices[i].devfn),
548                                  PCI_FUNC(devices[i].devfn));
549                 }
550             }
551         }
552         ret = -EPERM;
553         goto out_single;
554     }
555 
556     trace_vfio_pci_hot_reset_has_dep_devices(vdev->vbasedev.name);
557 
558     for (i = 0; i < info->count; i++) {
559         VFIOPCIDevice *tmp;
560 
561         trace_iommufd_cdev_pci_hot_reset_dep_devices(devices[i].segment,
562                                                      devices[i].bus,
563                                                      PCI_SLOT(devices[i].devfn),
564                                                      PCI_FUNC(devices[i].devfn),
565                                                      devices[i].devid);
566 
567         /*
568          * If a VFIO cdev device is resettable, all the dependent devices
569          * are either bound to same iommufd or within same iommu_groups as
570          * one of the iommufd bound devices.
571          */
572         assert(devices[i].devid != VFIO_PCI_DEVID_NOT_OWNED);
573 
574         tmp = iommufd_cdev_dep_get_realized_vpdev(&devices[i], &vdev->vbasedev);
575         if (!tmp) {
576             continue;
577         }
578 
579         if (single) {
580             ret = -EINVAL;
581             goto out_single;
582         }
583         vfio_pci_pre_reset(tmp);
584         tmp->vbasedev.needs_reset = false;
585         multi = true;
586     }
587 
588     if (!single && !multi) {
589         ret = -EINVAL;
590         goto out_single;
591     }
592 
593     /* Use zero length array for hot reset with iommufd backend */
594     reset = g_malloc0(sizeof(*reset));
595     reset->argsz = sizeof(*reset);
596 
597      /* Bus reset! */
598     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
599     g_free(reset);
600     if (ret) {
601         ret = -errno;
602     }
603 
604     trace_vfio_pci_hot_reset_result(vdev->vbasedev.name,
605                                     ret ? strerror(errno) : "Success");
606 
607     /* Re-enable INTx on affected devices */
608     for (i = 0; i < info->count; i++) {
609         VFIOPCIDevice *tmp;
610 
611         tmp = iommufd_cdev_dep_get_realized_vpdev(&devices[i], &vdev->vbasedev);
612         if (!tmp) {
613             continue;
614         }
615         vfio_pci_post_reset(tmp);
616     }
617 out_single:
618     if (!single) {
619         vfio_pci_post_reset(vdev);
620     }
621     g_free(info);
622 
623     return ret;
624 }
625 
626 static void vfio_iommu_iommufd_class_init(ObjectClass *klass, void *data)
627 {
628     VFIOIOMMUClass *vioc = VFIO_IOMMU_CLASS(klass);
629 
630     vioc->dma_map = iommufd_cdev_map;
631     vioc->dma_unmap = iommufd_cdev_unmap;
632     vioc->attach_device = iommufd_cdev_attach;
633     vioc->detach_device = iommufd_cdev_detach;
634     vioc->pci_hot_reset = iommufd_cdev_pci_hot_reset;
635 };
636 
637 static const TypeInfo types[] = {
638     {
639         .name = TYPE_VFIO_IOMMU_IOMMUFD,
640         .parent = TYPE_VFIO_IOMMU,
641         .class_init = vfio_iommu_iommufd_class_init,
642     },
643 };
644 
645 DEFINE_TYPES(types)
646