xref: /openbmc/qemu/hw/vfio/iommufd.c (revision 5db05230)
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     long int ret = -ENOTTY;
120     char *path, *vfio_dev_path = NULL, *vfio_path = NULL;
121     DIR *dir = NULL;
122     struct dirent *dent;
123     gchar *contents;
124     struct stat st;
125     gsize length;
126     int major, minor;
127     dev_t vfio_devt;
128 
129     path = g_strdup_printf("%s/vfio-dev", sysfs_path);
130     if (stat(path, &st) < 0) {
131         error_setg_errno(errp, errno, "no such host device");
132         goto out_free_path;
133     }
134 
135     dir = opendir(path);
136     if (!dir) {
137         error_setg_errno(errp, errno, "couldn't open directory %s", path);
138         goto out_free_path;
139     }
140 
141     while ((dent = readdir(dir))) {
142         if (!strncmp(dent->d_name, "vfio", 4)) {
143             vfio_dev_path = g_strdup_printf("%s/%s/dev", path, dent->d_name);
144             break;
145         }
146     }
147 
148     if (!vfio_dev_path) {
149         error_setg(errp, "failed to find vfio-dev/vfioX/dev");
150         goto out_close_dir;
151     }
152 
153     if (!g_file_get_contents(vfio_dev_path, &contents, &length, NULL)) {
154         error_setg(errp, "failed to load \"%s\"", vfio_dev_path);
155         goto out_free_dev_path;
156     }
157 
158     if (sscanf(contents, "%d:%d", &major, &minor) != 2) {
159         error_setg(errp, "failed to get major:minor for \"%s\"", vfio_dev_path);
160         goto out_free_dev_path;
161     }
162     g_free(contents);
163     vfio_devt = makedev(major, minor);
164 
165     vfio_path = g_strdup_printf("/dev/vfio/devices/%s", dent->d_name);
166     ret = open_cdev(vfio_path, vfio_devt);
167     if (ret < 0) {
168         error_setg(errp, "Failed to open %s", vfio_path);
169     }
170 
171     trace_iommufd_cdev_getfd(vfio_path, ret);
172     g_free(vfio_path);
173 
174 out_free_dev_path:
175     g_free(vfio_dev_path);
176 out_close_dir:
177     closedir(dir);
178 out_free_path:
179     if (*errp) {
180         error_prepend(errp, VFIO_MSG_PREFIX, path);
181     }
182     g_free(path);
183 
184     return ret;
185 }
186 
187 static int iommufd_cdev_attach_ioas_hwpt(VFIODevice *vbasedev, uint32_t id,
188                                          Error **errp)
189 {
190     int ret, iommufd = vbasedev->iommufd->fd;
191     struct vfio_device_attach_iommufd_pt attach_data = {
192         .argsz = sizeof(attach_data),
193         .flags = 0,
194         .pt_id = id,
195     };
196 
197     /* Attach device to an IOAS or hwpt within iommufd */
198     ret = ioctl(vbasedev->fd, VFIO_DEVICE_ATTACH_IOMMUFD_PT, &attach_data);
199     if (ret) {
200         error_setg_errno(errp, errno,
201                          "[iommufd=%d] error attach %s (%d) to id=%d",
202                          iommufd, vbasedev->name, vbasedev->fd, id);
203     } else {
204         trace_iommufd_cdev_attach_ioas_hwpt(iommufd, vbasedev->name,
205                                             vbasedev->fd, id);
206     }
207     return ret;
208 }
209 
210 static int iommufd_cdev_detach_ioas_hwpt(VFIODevice *vbasedev, Error **errp)
211 {
212     int ret, iommufd = vbasedev->iommufd->fd;
213     struct vfio_device_detach_iommufd_pt detach_data = {
214         .argsz = sizeof(detach_data),
215         .flags = 0,
216     };
217 
218     ret = ioctl(vbasedev->fd, VFIO_DEVICE_DETACH_IOMMUFD_PT, &detach_data);
219     if (ret) {
220         error_setg_errno(errp, errno, "detach %s failed", vbasedev->name);
221     } else {
222         trace_iommufd_cdev_detach_ioas_hwpt(iommufd, vbasedev->name);
223     }
224     return ret;
225 }
226 
227 static int iommufd_cdev_attach_container(VFIODevice *vbasedev,
228                                          VFIOIOMMUFDContainer *container,
229                                          Error **errp)
230 {
231     return iommufd_cdev_attach_ioas_hwpt(vbasedev, container->ioas_id, errp);
232 }
233 
234 static void iommufd_cdev_detach_container(VFIODevice *vbasedev,
235                                           VFIOIOMMUFDContainer *container)
236 {
237     Error *err = NULL;
238 
239     if (iommufd_cdev_detach_ioas_hwpt(vbasedev, &err)) {
240         error_report_err(err);
241     }
242 }
243 
244 static void iommufd_cdev_container_destroy(VFIOIOMMUFDContainer *container)
245 {
246     VFIOContainerBase *bcontainer = &container->bcontainer;
247 
248     if (!QLIST_EMPTY(&bcontainer->device_list)) {
249         return;
250     }
251     memory_listener_unregister(&bcontainer->listener);
252     vfio_container_destroy(bcontainer);
253     iommufd_backend_free_id(container->be, container->ioas_id);
254     g_free(container);
255 }
256 
257 static int iommufd_cdev_ram_block_discard_disable(bool state)
258 {
259     /*
260      * We support coordinated discarding of RAM via the RamDiscardManager.
261      */
262     return ram_block_uncoordinated_discard_disable(state);
263 }
264 
265 static int iommufd_cdev_get_info_iova_range(VFIOIOMMUFDContainer *container,
266                                             uint32_t ioas_id, Error **errp)
267 {
268     VFIOContainerBase *bcontainer = &container->bcontainer;
269     struct iommu_ioas_iova_ranges *info;
270     struct iommu_iova_range *iova_ranges;
271     int ret, sz, fd = container->be->fd;
272 
273     info = g_malloc0(sizeof(*info));
274     info->size = sizeof(*info);
275     info->ioas_id = ioas_id;
276 
277     ret = ioctl(fd, IOMMU_IOAS_IOVA_RANGES, info);
278     if (ret && errno != EMSGSIZE) {
279         goto error;
280     }
281 
282     sz = info->num_iovas * sizeof(struct iommu_iova_range);
283     info = g_realloc(info, sizeof(*info) + sz);
284     info->allowed_iovas = (uintptr_t)(info + 1);
285 
286     ret = ioctl(fd, IOMMU_IOAS_IOVA_RANGES, info);
287     if (ret) {
288         goto error;
289     }
290 
291     iova_ranges = (struct iommu_iova_range *)(uintptr_t)info->allowed_iovas;
292 
293     for (int i = 0; i < info->num_iovas; i++) {
294         Range *range = g_new(Range, 1);
295 
296         range_set_bounds(range, iova_ranges[i].start, iova_ranges[i].last);
297         bcontainer->iova_ranges =
298             range_list_insert(bcontainer->iova_ranges, range);
299     }
300     bcontainer->pgsizes = info->out_iova_alignment;
301 
302     g_free(info);
303     return 0;
304 
305 error:
306     ret = -errno;
307     g_free(info);
308     error_setg_errno(errp, errno, "Cannot get IOVA ranges");
309     return ret;
310 }
311 
312 static int iommufd_cdev_attach(const char *name, VFIODevice *vbasedev,
313                                AddressSpace *as, Error **errp)
314 {
315     VFIOContainerBase *bcontainer;
316     VFIOIOMMUFDContainer *container;
317     VFIOAddressSpace *space;
318     struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
319     int ret, devfd;
320     uint32_t ioas_id;
321     Error *err = NULL;
322 
323     if (vbasedev->fd < 0) {
324         devfd = iommufd_cdev_getfd(vbasedev->sysfsdev, errp);
325         if (devfd < 0) {
326             return devfd;
327         }
328         vbasedev->fd = devfd;
329     } else {
330         devfd = vbasedev->fd;
331     }
332 
333     ret = iommufd_cdev_connect_and_bind(vbasedev, errp);
334     if (ret) {
335         goto err_connect_bind;
336     }
337 
338     space = vfio_get_address_space(as);
339 
340     /* try to attach to an existing container in this space */
341     QLIST_FOREACH(bcontainer, &space->containers, next) {
342         container = container_of(bcontainer, VFIOIOMMUFDContainer, bcontainer);
343         if (bcontainer->ops != &vfio_iommufd_ops ||
344             vbasedev->iommufd != container->be) {
345             continue;
346         }
347         if (iommufd_cdev_attach_container(vbasedev, container, &err)) {
348             const char *msg = error_get_pretty(err);
349 
350             trace_iommufd_cdev_fail_attach_existing_container(msg);
351             error_free(err);
352             err = NULL;
353         } else {
354             ret = iommufd_cdev_ram_block_discard_disable(true);
355             if (ret) {
356                 error_setg(errp,
357                               "Cannot set discarding of RAM broken (%d)", ret);
358                 goto err_discard_disable;
359             }
360             goto found_container;
361         }
362     }
363 
364     /* Need to allocate a new dedicated container */
365     ret = iommufd_backend_alloc_ioas(vbasedev->iommufd, &ioas_id, errp);
366     if (ret < 0) {
367         goto err_alloc_ioas;
368     }
369 
370     trace_iommufd_cdev_alloc_ioas(vbasedev->iommufd->fd, ioas_id);
371 
372     container = g_malloc0(sizeof(*container));
373     container->be = vbasedev->iommufd;
374     container->ioas_id = ioas_id;
375 
376     bcontainer = &container->bcontainer;
377     vfio_container_init(bcontainer, space, &vfio_iommufd_ops);
378     QLIST_INSERT_HEAD(&space->containers, bcontainer, next);
379 
380     ret = iommufd_cdev_attach_container(vbasedev, container, errp);
381     if (ret) {
382         goto err_attach_container;
383     }
384 
385     ret = iommufd_cdev_ram_block_discard_disable(true);
386     if (ret) {
387         goto err_discard_disable;
388     }
389 
390     ret = iommufd_cdev_get_info_iova_range(container, ioas_id, &err);
391     if (ret) {
392         error_append_hint(&err,
393                    "Fallback to default 64bit IOVA range and 4K page size\n");
394         warn_report_err(err);
395         err = NULL;
396         bcontainer->pgsizes = qemu_real_host_page_size();
397     }
398 
399     bcontainer->listener = vfio_memory_listener;
400     memory_listener_register(&bcontainer->listener, bcontainer->space->as);
401 
402     if (bcontainer->error) {
403         ret = -1;
404         error_propagate_prepend(errp, bcontainer->error,
405                                 "memory listener initialization failed: ");
406         goto err_listener_register;
407     }
408 
409     bcontainer->initialized = true;
410 
411 found_container:
412     ret = ioctl(devfd, VFIO_DEVICE_GET_INFO, &dev_info);
413     if (ret) {
414         error_setg_errno(errp, errno, "error getting device info");
415         goto err_listener_register;
416     }
417 
418     /*
419      * TODO: examine RAM_BLOCK_DISCARD stuff, should we do group level
420      * for discarding incompatibility check as well?
421      */
422     if (vbasedev->ram_block_discard_allowed) {
423         iommufd_cdev_ram_block_discard_disable(false);
424     }
425 
426     vbasedev->group = 0;
427     vbasedev->num_irqs = dev_info.num_irqs;
428     vbasedev->num_regions = dev_info.num_regions;
429     vbasedev->flags = dev_info.flags;
430     vbasedev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
431     vbasedev->bcontainer = bcontainer;
432     QLIST_INSERT_HEAD(&bcontainer->device_list, vbasedev, container_next);
433     QLIST_INSERT_HEAD(&vfio_device_list, vbasedev, global_next);
434 
435     trace_iommufd_cdev_device_info(vbasedev->name, devfd, vbasedev->num_irqs,
436                                    vbasedev->num_regions, vbasedev->flags);
437     return 0;
438 
439 err_listener_register:
440     iommufd_cdev_ram_block_discard_disable(false);
441 err_discard_disable:
442     iommufd_cdev_detach_container(vbasedev, container);
443 err_attach_container:
444     iommufd_cdev_container_destroy(container);
445 err_alloc_ioas:
446     vfio_put_address_space(space);
447     iommufd_cdev_unbind_and_disconnect(vbasedev);
448 err_connect_bind:
449     close(vbasedev->fd);
450     return ret;
451 }
452 
453 static void iommufd_cdev_detach(VFIODevice *vbasedev)
454 {
455     VFIOContainerBase *bcontainer = vbasedev->bcontainer;
456     VFIOAddressSpace *space = bcontainer->space;
457     VFIOIOMMUFDContainer *container = container_of(bcontainer,
458                                                    VFIOIOMMUFDContainer,
459                                                    bcontainer);
460     QLIST_REMOVE(vbasedev, global_next);
461     QLIST_REMOVE(vbasedev, container_next);
462     vbasedev->bcontainer = NULL;
463 
464     if (!vbasedev->ram_block_discard_allowed) {
465         iommufd_cdev_ram_block_discard_disable(false);
466     }
467 
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 
480     QLIST_FOREACH(vbasedev_iter, &vfio_device_list, global_next) {
481         if (vbasedev_iter->bcontainer->ops != &vfio_iommufd_ops) {
482             continue;
483         }
484         if (devid == vbasedev_iter->devid) {
485             return vbasedev_iter;
486         }
487     }
488     return NULL;
489 }
490 
491 static VFIOPCIDevice *
492 iommufd_cdev_dep_get_realized_vpdev(struct vfio_pci_dependent_device *dep_dev,
493                                     VFIODevice *reset_dev)
494 {
495     VFIODevice *vbasedev_tmp;
496 
497     if (dep_dev->devid == reset_dev->devid ||
498         dep_dev->devid == VFIO_PCI_DEVID_OWNED) {
499         return NULL;
500     }
501 
502     vbasedev_tmp = iommufd_cdev_pci_find_by_devid(dep_dev->devid);
503     if (!vbasedev_tmp || !vbasedev_tmp->dev->realized ||
504         vbasedev_tmp->type != VFIO_DEVICE_TYPE_PCI) {
505         return NULL;
506     }
507 
508     return container_of(vbasedev_tmp, VFIOPCIDevice, vbasedev);
509 }
510 
511 static int iommufd_cdev_pci_hot_reset(VFIODevice *vbasedev, bool single)
512 {
513     VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
514     struct vfio_pci_hot_reset_info *info = NULL;
515     struct vfio_pci_dependent_device *devices;
516     struct vfio_pci_hot_reset *reset;
517     int ret, i;
518     bool multi = false;
519 
520     trace_vfio_pci_hot_reset(vdev->vbasedev.name, single ? "one" : "multi");
521 
522     if (!single) {
523         vfio_pci_pre_reset(vdev);
524     }
525     vdev->vbasedev.needs_reset = false;
526 
527     ret = vfio_pci_get_pci_hot_reset_info(vdev, &info);
528 
529     if (ret) {
530         goto out_single;
531     }
532 
533     assert(info->flags & VFIO_PCI_HOT_RESET_FLAG_DEV_ID);
534 
535     devices = &info->devices[0];
536 
537     if (!(info->flags & VFIO_PCI_HOT_RESET_FLAG_DEV_ID_OWNED)) {
538         if (!vdev->has_pm_reset) {
539             for (i = 0; i < info->count; i++) {
540                 if (devices[i].devid == VFIO_PCI_DEVID_NOT_OWNED) {
541                     error_report("vfio: Cannot reset device %s, "
542                                  "depends on device %04x:%02x:%02x.%x "
543                                  "which is not owned.",
544                                  vdev->vbasedev.name, devices[i].segment,
545                                  devices[i].bus, PCI_SLOT(devices[i].devfn),
546                                  PCI_FUNC(devices[i].devfn));
547                 }
548             }
549         }
550         ret = -EPERM;
551         goto out_single;
552     }
553 
554     trace_vfio_pci_hot_reset_has_dep_devices(vdev->vbasedev.name);
555 
556     for (i = 0; i < info->count; i++) {
557         VFIOPCIDevice *tmp;
558 
559         trace_iommufd_cdev_pci_hot_reset_dep_devices(devices[i].segment,
560                                                      devices[i].bus,
561                                                      PCI_SLOT(devices[i].devfn),
562                                                      PCI_FUNC(devices[i].devfn),
563                                                      devices[i].devid);
564 
565         /*
566          * If a VFIO cdev device is resettable, all the dependent devices
567          * are either bound to same iommufd or within same iommu_groups as
568          * one of the iommufd bound devices.
569          */
570         assert(devices[i].devid != VFIO_PCI_DEVID_NOT_OWNED);
571 
572         tmp = iommufd_cdev_dep_get_realized_vpdev(&devices[i], &vdev->vbasedev);
573         if (!tmp) {
574             continue;
575         }
576 
577         if (single) {
578             ret = -EINVAL;
579             goto out_single;
580         }
581         vfio_pci_pre_reset(tmp);
582         tmp->vbasedev.needs_reset = false;
583         multi = true;
584     }
585 
586     if (!single && !multi) {
587         ret = -EINVAL;
588         goto out_single;
589     }
590 
591     /* Use zero length array for hot reset with iommufd backend */
592     reset = g_malloc0(sizeof(*reset));
593     reset->argsz = sizeof(*reset);
594 
595      /* Bus reset! */
596     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
597     g_free(reset);
598     if (ret) {
599         ret = -errno;
600     }
601 
602     trace_vfio_pci_hot_reset_result(vdev->vbasedev.name,
603                                     ret ? strerror(errno) : "Success");
604 
605     /* Re-enable INTx on affected devices */
606     for (i = 0; i < info->count; i++) {
607         VFIOPCIDevice *tmp;
608 
609         tmp = iommufd_cdev_dep_get_realized_vpdev(&devices[i], &vdev->vbasedev);
610         if (!tmp) {
611             continue;
612         }
613         vfio_pci_post_reset(tmp);
614     }
615 out_single:
616     if (!single) {
617         vfio_pci_post_reset(vdev);
618     }
619     g_free(info);
620 
621     return ret;
622 }
623 
624 const VFIOIOMMUOps vfio_iommufd_ops = {
625     .dma_map = iommufd_cdev_map,
626     .dma_unmap = iommufd_cdev_unmap,
627     .attach_device = iommufd_cdev_attach,
628     .detach_device = iommufd_cdev_detach,
629     .pci_hot_reset = iommufd_cdev_pci_hot_reset,
630 };
631