xref: /qemu/hw/vfio/iommufd.c (revision 2e6a9f03ba1e8145cf71eced2b97611cfa754898)
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-device.h"
19 #include "qemu/error-report.h"
20 #include "trace.h"
21 #include "qapi/error.h"
22 #include "system/iommufd.h"
23 #include "hw/qdev-core.h"
24 #include "system/reset.h"
25 #include "qemu/cutils.h"
26 #include "qemu/chardev_open.h"
27 #include "pci.h"
28 #include "vfio-iommufd.h"
29 #include "vfio-helpers.h"
30 #include "vfio-cpr.h"
31 #include "vfio-listener.h"
32 
33 #define TYPE_HOST_IOMMU_DEVICE_IOMMUFD_VFIO             \
34             TYPE_HOST_IOMMU_DEVICE_IOMMUFD "-vfio"
35 
36 static int iommufd_cdev_map(const VFIOContainerBase *bcontainer, hwaddr iova,
37                             ram_addr_t size, void *vaddr, bool readonly)
38 {
39     const VFIOIOMMUFDContainer *container =
40         container_of(bcontainer, VFIOIOMMUFDContainer, bcontainer);
41 
42     return iommufd_backend_map_dma(container->be,
43                                    container->ioas_id,
44                                    iova, size, vaddr, readonly);
45 }
46 
47 static int iommufd_cdev_unmap(const VFIOContainerBase *bcontainer,
48                               hwaddr iova, ram_addr_t size,
49                               IOMMUTLBEntry *iotlb)
50 {
51     const VFIOIOMMUFDContainer *container =
52         container_of(bcontainer, VFIOIOMMUFDContainer, bcontainer);
53 
54     /* TODO: Handle dma_unmap_bitmap with iotlb args (migration) */
55     return iommufd_backend_unmap_dma(container->be,
56                                      container->ioas_id, iova, size);
57 }
58 
59 static bool iommufd_cdev_kvm_device_add(VFIODevice *vbasedev, Error **errp)
60 {
61     return !vfio_kvm_device_add_fd(vbasedev->fd, errp);
62 }
63 
64 static void iommufd_cdev_kvm_device_del(VFIODevice *vbasedev)
65 {
66     Error *err = NULL;
67 
68     if (vfio_kvm_device_del_fd(vbasedev->fd, &err)) {
69         error_report_err(err);
70     }
71 }
72 
73 static bool iommufd_cdev_connect_and_bind(VFIODevice *vbasedev, Error **errp)
74 {
75     IOMMUFDBackend *iommufd = vbasedev->iommufd;
76     struct vfio_device_bind_iommufd bind = {
77         .argsz = sizeof(bind),
78         .flags = 0,
79     };
80 
81     if (!iommufd_backend_connect(iommufd, errp)) {
82         return false;
83     }
84 
85     /*
86      * Add device to kvm-vfio to be prepared for the tracking
87      * in KVM. Especially for some emulated devices, it requires
88      * to have kvm information in the device open.
89      */
90     if (!iommufd_cdev_kvm_device_add(vbasedev, errp)) {
91         goto err_kvm_device_add;
92     }
93 
94     /* Bind device to iommufd */
95     bind.iommufd = iommufd->fd;
96     if (ioctl(vbasedev->fd, VFIO_DEVICE_BIND_IOMMUFD, &bind)) {
97         error_setg_errno(errp, errno, "error bind device fd=%d to iommufd=%d",
98                          vbasedev->fd, bind.iommufd);
99         goto err_bind;
100     }
101 
102     vbasedev->devid = bind.out_devid;
103     trace_iommufd_cdev_connect_and_bind(bind.iommufd, vbasedev->name,
104                                         vbasedev->fd, vbasedev->devid);
105     return true;
106 err_bind:
107     iommufd_cdev_kvm_device_del(vbasedev);
108 err_kvm_device_add:
109     iommufd_backend_disconnect(iommufd);
110     return false;
111 }
112 
113 static void iommufd_cdev_unbind_and_disconnect(VFIODevice *vbasedev)
114 {
115     /* Unbind is automatically conducted when device fd is closed */
116     iommufd_cdev_kvm_device_del(vbasedev);
117     iommufd_backend_disconnect(vbasedev->iommufd);
118 }
119 
120 static bool iommufd_hwpt_dirty_tracking(VFIOIOASHwpt *hwpt)
121 {
122     return hwpt && hwpt->hwpt_flags & IOMMU_HWPT_ALLOC_DIRTY_TRACKING;
123 }
124 
125 static int iommufd_set_dirty_page_tracking(const VFIOContainerBase *bcontainer,
126                                            bool start, Error **errp)
127 {
128     const VFIOIOMMUFDContainer *container =
129         container_of(bcontainer, VFIOIOMMUFDContainer, bcontainer);
130     VFIOIOASHwpt *hwpt;
131 
132     QLIST_FOREACH(hwpt, &container->hwpt_list, next) {
133         if (!iommufd_hwpt_dirty_tracking(hwpt)) {
134             continue;
135         }
136 
137         if (!iommufd_backend_set_dirty_tracking(container->be,
138                                                 hwpt->hwpt_id, start, errp)) {
139             goto err;
140         }
141     }
142 
143     return 0;
144 
145 err:
146     QLIST_FOREACH(hwpt, &container->hwpt_list, next) {
147         if (!iommufd_hwpt_dirty_tracking(hwpt)) {
148             continue;
149         }
150         iommufd_backend_set_dirty_tracking(container->be,
151                                            hwpt->hwpt_id, !start, NULL);
152     }
153     return -EINVAL;
154 }
155 
156 static int iommufd_query_dirty_bitmap(const VFIOContainerBase *bcontainer,
157                                       VFIOBitmap *vbmap, hwaddr iova,
158                                       hwaddr size, Error **errp)
159 {
160     VFIOIOMMUFDContainer *container = container_of(bcontainer,
161                                                    VFIOIOMMUFDContainer,
162                                                    bcontainer);
163     unsigned long page_size = qemu_real_host_page_size();
164     VFIOIOASHwpt *hwpt;
165 
166     QLIST_FOREACH(hwpt, &container->hwpt_list, next) {
167         if (!iommufd_hwpt_dirty_tracking(hwpt)) {
168             continue;
169         }
170 
171         if (!iommufd_backend_get_dirty_bitmap(container->be, hwpt->hwpt_id,
172                                               iova, size, page_size,
173                                               (uint64_t *)vbmap->bitmap,
174                                               errp)) {
175             return -EINVAL;
176         }
177     }
178 
179     return 0;
180 }
181 
182 static int iommufd_cdev_getfd(const char *sysfs_path, Error **errp)
183 {
184     ERRP_GUARD();
185     long int ret = -ENOTTY;
186     g_autofree char *path = NULL;
187     g_autofree char *vfio_dev_path = NULL;
188     g_autofree char *vfio_path = NULL;
189     DIR *dir = NULL;
190     struct dirent *dent;
191     g_autofree gchar *contents = NULL;
192     gsize length;
193     int major, minor;
194     dev_t vfio_devt;
195 
196     path = g_strdup_printf("%s/vfio-dev", sysfs_path);
197     dir = opendir(path);
198     if (!dir) {
199         error_setg_errno(errp, errno, "couldn't open directory %s", path);
200         goto out;
201     }
202 
203     while ((dent = readdir(dir))) {
204         if (!strncmp(dent->d_name, "vfio", 4)) {
205             vfio_dev_path = g_strdup_printf("%s/%s/dev", path, dent->d_name);
206             break;
207         }
208     }
209 
210     if (!vfio_dev_path) {
211         error_setg(errp, "failed to find vfio-dev/vfioX/dev");
212         goto out_close_dir;
213     }
214 
215     if (!g_file_get_contents(vfio_dev_path, &contents, &length, NULL)) {
216         error_setg(errp, "failed to load \"%s\"", vfio_dev_path);
217         goto out_close_dir;
218     }
219 
220     if (sscanf(contents, "%d:%d", &major, &minor) != 2) {
221         error_setg(errp, "failed to get major:minor for \"%s\"", vfio_dev_path);
222         goto out_close_dir;
223     }
224     vfio_devt = makedev(major, minor);
225 
226     vfio_path = g_strdup_printf("/dev/vfio/devices/%s", dent->d_name);
227     ret = open_cdev(vfio_path, vfio_devt);
228     if (ret < 0) {
229         error_setg(errp, "Failed to open %s", vfio_path);
230     }
231 
232     trace_iommufd_cdev_getfd(vfio_path, ret);
233 
234 out_close_dir:
235     closedir(dir);
236 out:
237     if (*errp) {
238         error_prepend(errp, VFIO_MSG_PREFIX, path);
239     }
240 
241     return ret;
242 }
243 
244 static int iommufd_cdev_attach_ioas_hwpt(VFIODevice *vbasedev, uint32_t id,
245                                          Error **errp)
246 {
247     int iommufd = vbasedev->iommufd->fd;
248     struct vfio_device_attach_iommufd_pt attach_data = {
249         .argsz = sizeof(attach_data),
250         .flags = 0,
251         .pt_id = id,
252     };
253 
254     /* Attach device to an IOAS or hwpt within iommufd */
255     if (ioctl(vbasedev->fd, VFIO_DEVICE_ATTACH_IOMMUFD_PT, &attach_data)) {
256         error_setg_errno(errp, errno,
257                          "[iommufd=%d] error attach %s (%d) to id=%d",
258                          iommufd, vbasedev->name, vbasedev->fd, id);
259         return -errno;
260     }
261 
262     trace_iommufd_cdev_attach_ioas_hwpt(iommufd, vbasedev->name,
263                                         vbasedev->fd, id);
264     return 0;
265 }
266 
267 static bool iommufd_cdev_detach_ioas_hwpt(VFIODevice *vbasedev, Error **errp)
268 {
269     int iommufd = vbasedev->iommufd->fd;
270     struct vfio_device_detach_iommufd_pt detach_data = {
271         .argsz = sizeof(detach_data),
272         .flags = 0,
273     };
274 
275     if (ioctl(vbasedev->fd, VFIO_DEVICE_DETACH_IOMMUFD_PT, &detach_data)) {
276         error_setg_errno(errp, errno, "detach %s failed", vbasedev->name);
277         return false;
278     }
279 
280     trace_iommufd_cdev_detach_ioas_hwpt(iommufd, vbasedev->name);
281     return true;
282 }
283 
284 static bool iommufd_cdev_autodomains_get(VFIODevice *vbasedev,
285                                          VFIOIOMMUFDContainer *container,
286                                          Error **errp)
287 {
288     ERRP_GUARD();
289     IOMMUFDBackend *iommufd = vbasedev->iommufd;
290     uint32_t type, flags = 0;
291     uint64_t hw_caps;
292     VFIOIOASHwpt *hwpt;
293     uint32_t hwpt_id;
294     int ret;
295 
296     /* Try to find a domain */
297     QLIST_FOREACH(hwpt, &container->hwpt_list, next) {
298         ret = iommufd_cdev_attach_ioas_hwpt(vbasedev, hwpt->hwpt_id, errp);
299         if (ret) {
300             /* -EINVAL means the domain is incompatible with the device. */
301             if (ret == -EINVAL) {
302                 /*
303                  * It is an expected failure and it just means we will try
304                  * another domain, or create one if no existing compatible
305                  * domain is found. Hence why the error is discarded below.
306                  */
307                 error_free(*errp);
308                 *errp = NULL;
309                 continue;
310             }
311 
312             return false;
313         } else {
314             vbasedev->hwpt = hwpt;
315             QLIST_INSERT_HEAD(&hwpt->device_list, vbasedev, hwpt_next);
316             vbasedev->iommu_dirty_tracking = iommufd_hwpt_dirty_tracking(hwpt);
317             return true;
318         }
319     }
320 
321     /*
322      * This is quite early and VFIO Migration state isn't yet fully
323      * initialized, thus rely only on IOMMU hardware capabilities as to
324      * whether IOMMU dirty tracking is going to be requested. Later
325      * vfio_migration_realize() may decide to use VF dirty tracking
326      * instead.
327      */
328     if (!iommufd_backend_get_device_info(vbasedev->iommufd, vbasedev->devid,
329                                          &type, NULL, 0, &hw_caps, errp)) {
330         return false;
331     }
332 
333     if (hw_caps & IOMMU_HW_CAP_DIRTY_TRACKING) {
334         flags = IOMMU_HWPT_ALLOC_DIRTY_TRACKING;
335     }
336 
337     if (!iommufd_backend_alloc_hwpt(iommufd, vbasedev->devid,
338                                     container->ioas_id, flags,
339                                     IOMMU_HWPT_DATA_NONE, 0, NULL,
340                                     &hwpt_id, errp)) {
341         return false;
342     }
343 
344     hwpt = g_malloc0(sizeof(*hwpt));
345     hwpt->hwpt_id = hwpt_id;
346     hwpt->hwpt_flags = flags;
347     QLIST_INIT(&hwpt->device_list);
348 
349     ret = iommufd_cdev_attach_ioas_hwpt(vbasedev, hwpt->hwpt_id, errp);
350     if (ret) {
351         iommufd_backend_free_id(container->be, hwpt->hwpt_id);
352         g_free(hwpt);
353         return false;
354     }
355 
356     vbasedev->hwpt = hwpt;
357     vbasedev->iommu_dirty_tracking = iommufd_hwpt_dirty_tracking(hwpt);
358     QLIST_INSERT_HEAD(&hwpt->device_list, vbasedev, hwpt_next);
359     QLIST_INSERT_HEAD(&container->hwpt_list, hwpt, next);
360     container->bcontainer.dirty_pages_supported |=
361                                 vbasedev->iommu_dirty_tracking;
362     if (container->bcontainer.dirty_pages_supported &&
363         !vbasedev->iommu_dirty_tracking) {
364         warn_report("IOMMU instance for device %s doesn't support dirty tracking",
365                     vbasedev->name);
366     }
367     return true;
368 }
369 
370 static void iommufd_cdev_autodomains_put(VFIODevice *vbasedev,
371                                          VFIOIOMMUFDContainer *container)
372 {
373     VFIOIOASHwpt *hwpt = vbasedev->hwpt;
374 
375     QLIST_REMOVE(vbasedev, hwpt_next);
376     vbasedev->hwpt = NULL;
377 
378     if (QLIST_EMPTY(&hwpt->device_list)) {
379         QLIST_REMOVE(hwpt, next);
380         iommufd_backend_free_id(container->be, hwpt->hwpt_id);
381         g_free(hwpt);
382     }
383 }
384 
385 static bool iommufd_cdev_attach_container(VFIODevice *vbasedev,
386                                           VFIOIOMMUFDContainer *container,
387                                           Error **errp)
388 {
389     /* mdevs aren't physical devices and will fail with auto domains */
390     if (!vbasedev->mdev) {
391         return iommufd_cdev_autodomains_get(vbasedev, container, errp);
392     }
393 
394     return !iommufd_cdev_attach_ioas_hwpt(vbasedev, container->ioas_id, errp);
395 }
396 
397 static void iommufd_cdev_detach_container(VFIODevice *vbasedev,
398                                           VFIOIOMMUFDContainer *container)
399 {
400     Error *err = NULL;
401 
402     if (!iommufd_cdev_detach_ioas_hwpt(vbasedev, &err)) {
403         error_report_err(err);
404     }
405 
406     if (vbasedev->hwpt) {
407         iommufd_cdev_autodomains_put(vbasedev, container);
408     }
409 
410 }
411 
412 static void iommufd_cdev_container_destroy(VFIOIOMMUFDContainer *container)
413 {
414     VFIOContainerBase *bcontainer = &container->bcontainer;
415 
416     if (!QLIST_EMPTY(&bcontainer->device_list)) {
417         return;
418     }
419     vfio_cpr_unregister_container(bcontainer);
420     vfio_listener_unregister(bcontainer);
421     iommufd_backend_free_id(container->be, container->ioas_id);
422     object_unref(container);
423 }
424 
425 static int iommufd_cdev_ram_block_discard_disable(bool state)
426 {
427     /*
428      * We support coordinated discarding of RAM via the RamDiscardManager.
429      */
430     return ram_block_uncoordinated_discard_disable(state);
431 }
432 
433 static bool iommufd_cdev_get_info_iova_range(VFIOIOMMUFDContainer *container,
434                                              uint32_t ioas_id, Error **errp)
435 {
436     VFIOContainerBase *bcontainer = &container->bcontainer;
437     g_autofree struct iommu_ioas_iova_ranges *info = NULL;
438     struct iommu_iova_range *iova_ranges;
439     int sz, fd = container->be->fd;
440 
441     info = g_malloc0(sizeof(*info));
442     info->size = sizeof(*info);
443     info->ioas_id = ioas_id;
444 
445     if (ioctl(fd, IOMMU_IOAS_IOVA_RANGES, info) && errno != EMSGSIZE) {
446         goto error;
447     }
448 
449     sz = info->num_iovas * sizeof(struct iommu_iova_range);
450     info = g_realloc(info, sizeof(*info) + sz);
451     info->allowed_iovas = (uintptr_t)(info + 1);
452 
453     if (ioctl(fd, IOMMU_IOAS_IOVA_RANGES, info)) {
454         goto error;
455     }
456 
457     iova_ranges = (struct iommu_iova_range *)(uintptr_t)info->allowed_iovas;
458 
459     for (int i = 0; i < info->num_iovas; i++) {
460         Range *range = g_new(Range, 1);
461 
462         range_set_bounds(range, iova_ranges[i].start, iova_ranges[i].last);
463         bcontainer->iova_ranges =
464             range_list_insert(bcontainer->iova_ranges, range);
465     }
466     bcontainer->pgsizes = info->out_iova_alignment;
467 
468     return true;
469 
470 error:
471     error_setg_errno(errp, errno, "Cannot get IOVA ranges");
472     return false;
473 }
474 
475 static bool iommufd_cdev_attach(const char *name, VFIODevice *vbasedev,
476                                 AddressSpace *as, Error **errp)
477 {
478     VFIOContainerBase *bcontainer;
479     VFIOIOMMUFDContainer *container;
480     VFIOAddressSpace *space;
481     struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
482     int ret, devfd;
483     uint32_t ioas_id;
484     Error *err = NULL;
485     const VFIOIOMMUClass *iommufd_vioc =
486         VFIO_IOMMU_CLASS(object_class_by_name(TYPE_VFIO_IOMMU_IOMMUFD));
487 
488     if (vbasedev->fd < 0) {
489         devfd = iommufd_cdev_getfd(vbasedev->sysfsdev, errp);
490         if (devfd < 0) {
491             return false;
492         }
493         vbasedev->fd = devfd;
494     } else {
495         devfd = vbasedev->fd;
496     }
497 
498     if (!iommufd_cdev_connect_and_bind(vbasedev, errp)) {
499         goto err_connect_bind;
500     }
501 
502     space = vfio_address_space_get(as);
503 
504     /* try to attach to an existing container in this space */
505     QLIST_FOREACH(bcontainer, &space->containers, next) {
506         container = container_of(bcontainer, VFIOIOMMUFDContainer, bcontainer);
507         if (VFIO_IOMMU_GET_CLASS(bcontainer) != iommufd_vioc ||
508             vbasedev->iommufd != container->be) {
509             continue;
510         }
511         if (!iommufd_cdev_attach_container(vbasedev, container, &err)) {
512             const char *msg = error_get_pretty(err);
513 
514             trace_iommufd_cdev_fail_attach_existing_container(msg);
515             error_free(err);
516             err = NULL;
517         } else {
518             ret = iommufd_cdev_ram_block_discard_disable(true);
519             if (ret) {
520                 error_setg_errno(errp, -ret,
521                                  "Cannot set discarding of RAM broken");
522                 goto err_discard_disable;
523             }
524             goto found_container;
525         }
526     }
527 
528     /* Need to allocate a new dedicated container */
529     if (!iommufd_backend_alloc_ioas(vbasedev->iommufd, &ioas_id, errp)) {
530         goto err_alloc_ioas;
531     }
532 
533     trace_iommufd_cdev_alloc_ioas(vbasedev->iommufd->fd, ioas_id);
534 
535     container = VFIO_IOMMU_IOMMUFD(object_new(TYPE_VFIO_IOMMU_IOMMUFD));
536     container->be = vbasedev->iommufd;
537     container->ioas_id = ioas_id;
538     QLIST_INIT(&container->hwpt_list);
539 
540     bcontainer = &container->bcontainer;
541     vfio_address_space_insert(space, bcontainer);
542 
543     if (!iommufd_cdev_attach_container(vbasedev, container, errp)) {
544         goto err_attach_container;
545     }
546 
547     ret = iommufd_cdev_ram_block_discard_disable(true);
548     if (ret) {
549         error_setg_errno(errp, -ret, "Cannot set discarding of RAM broken");
550         goto err_discard_disable;
551     }
552 
553     if (!iommufd_cdev_get_info_iova_range(container, ioas_id, &err)) {
554         error_append_hint(&err,
555                    "Fallback to default 64bit IOVA range and 4K page size\n");
556         warn_report_err(err);
557         err = NULL;
558         bcontainer->pgsizes = qemu_real_host_page_size();
559     }
560 
561     if (!vfio_listener_register(bcontainer, errp)) {
562         goto err_listener_register;
563     }
564 
565     if (!vfio_cpr_register_container(bcontainer, errp)) {
566         goto err_listener_register;
567     }
568 
569     bcontainer->initialized = true;
570 
571 found_container:
572     ret = ioctl(devfd, VFIO_DEVICE_GET_INFO, &dev_info);
573     if (ret) {
574         error_setg_errno(errp, errno, "error getting device info");
575         goto err_listener_register;
576     }
577 
578     if (!vfio_device_hiod_create_and_realize(vbasedev,
579                      TYPE_HOST_IOMMU_DEVICE_IOMMUFD_VFIO, errp)) {
580         goto err_listener_register;
581     }
582 
583     /*
584      * TODO: examine RAM_BLOCK_DISCARD stuff, should we do group level
585      * for discarding incompatibility check as well?
586      */
587     if (vbasedev->ram_block_discard_allowed) {
588         iommufd_cdev_ram_block_discard_disable(false);
589     }
590 
591     vbasedev->group = 0;
592     vbasedev->num_irqs = dev_info.num_irqs;
593     vbasedev->num_regions = dev_info.num_regions;
594     vbasedev->flags = dev_info.flags;
595     vbasedev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
596     vbasedev->bcontainer = bcontainer;
597     QLIST_INSERT_HEAD(&bcontainer->device_list, vbasedev, container_next);
598     QLIST_INSERT_HEAD(&vfio_device_list, vbasedev, global_next);
599 
600     trace_iommufd_cdev_device_info(vbasedev->name, devfd, vbasedev->num_irqs,
601                                    vbasedev->num_regions, vbasedev->flags);
602     return true;
603 
604 err_listener_register:
605     iommufd_cdev_ram_block_discard_disable(false);
606 err_discard_disable:
607     iommufd_cdev_detach_container(vbasedev, container);
608 err_attach_container:
609     iommufd_cdev_container_destroy(container);
610 err_alloc_ioas:
611     vfio_address_space_put(space);
612     iommufd_cdev_unbind_and_disconnect(vbasedev);
613 err_connect_bind:
614     close(vbasedev->fd);
615     return false;
616 }
617 
618 static void iommufd_cdev_detach(VFIODevice *vbasedev)
619 {
620     VFIOContainerBase *bcontainer = vbasedev->bcontainer;
621     VFIOAddressSpace *space = bcontainer->space;
622     VFIOIOMMUFDContainer *container = container_of(bcontainer,
623                                                    VFIOIOMMUFDContainer,
624                                                    bcontainer);
625     QLIST_REMOVE(vbasedev, global_next);
626     QLIST_REMOVE(vbasedev, container_next);
627     vbasedev->bcontainer = NULL;
628 
629     if (!vbasedev->ram_block_discard_allowed) {
630         iommufd_cdev_ram_block_discard_disable(false);
631     }
632 
633     object_unref(vbasedev->hiod);
634     iommufd_cdev_detach_container(vbasedev, container);
635     iommufd_cdev_container_destroy(container);
636     vfio_address_space_put(space);
637 
638     iommufd_cdev_unbind_and_disconnect(vbasedev);
639     close(vbasedev->fd);
640 }
641 
642 static VFIODevice *iommufd_cdev_pci_find_by_devid(__u32 devid)
643 {
644     VFIODevice *vbasedev_iter;
645     const VFIOIOMMUClass *iommufd_vioc =
646         VFIO_IOMMU_CLASS(object_class_by_name(TYPE_VFIO_IOMMU_IOMMUFD));
647 
648     QLIST_FOREACH(vbasedev_iter, &vfio_device_list, global_next) {
649         if (VFIO_IOMMU_GET_CLASS(vbasedev_iter->bcontainer) != iommufd_vioc) {
650             continue;
651         }
652         if (devid == vbasedev_iter->devid) {
653             return vbasedev_iter;
654         }
655     }
656     return NULL;
657 }
658 
659 static VFIOPCIDevice *
660 iommufd_cdev_dep_get_realized_vpdev(struct vfio_pci_dependent_device *dep_dev,
661                                     VFIODevice *reset_dev)
662 {
663     VFIODevice *vbasedev_tmp;
664 
665     if (dep_dev->devid == reset_dev->devid ||
666         dep_dev->devid == VFIO_PCI_DEVID_OWNED) {
667         return NULL;
668     }
669 
670     vbasedev_tmp = iommufd_cdev_pci_find_by_devid(dep_dev->devid);
671     if (!vbasedev_tmp || !vbasedev_tmp->dev->realized ||
672         vbasedev_tmp->type != VFIO_DEVICE_TYPE_PCI) {
673         return NULL;
674     }
675 
676     return container_of(vbasedev_tmp, VFIOPCIDevice, vbasedev);
677 }
678 
679 static int iommufd_cdev_pci_hot_reset(VFIODevice *vbasedev, bool single)
680 {
681     VFIOPCIDevice *vdev = container_of(vbasedev, VFIOPCIDevice, vbasedev);
682     struct vfio_pci_hot_reset_info *info = NULL;
683     struct vfio_pci_dependent_device *devices;
684     struct vfio_pci_hot_reset *reset;
685     int ret, i;
686     bool multi = false;
687 
688     trace_vfio_pci_hot_reset(vdev->vbasedev.name, single ? "one" : "multi");
689 
690     if (!single) {
691         vfio_pci_pre_reset(vdev);
692     }
693     vdev->vbasedev.needs_reset = false;
694 
695     ret = vfio_pci_get_pci_hot_reset_info(vdev, &info);
696 
697     if (ret) {
698         goto out_single;
699     }
700 
701     assert(info->flags & VFIO_PCI_HOT_RESET_FLAG_DEV_ID);
702 
703     devices = &info->devices[0];
704 
705     if (!(info->flags & VFIO_PCI_HOT_RESET_FLAG_DEV_ID_OWNED)) {
706         if (!vdev->has_pm_reset) {
707             for (i = 0; i < info->count; i++) {
708                 if (devices[i].devid == VFIO_PCI_DEVID_NOT_OWNED) {
709                     error_report("vfio: Cannot reset device %s, "
710                                  "depends on device %04x:%02x:%02x.%x "
711                                  "which is not owned.",
712                                  vdev->vbasedev.name, devices[i].segment,
713                                  devices[i].bus, PCI_SLOT(devices[i].devfn),
714                                  PCI_FUNC(devices[i].devfn));
715                 }
716             }
717         }
718         ret = -EPERM;
719         goto out_single;
720     }
721 
722     trace_vfio_pci_hot_reset_has_dep_devices(vdev->vbasedev.name);
723 
724     for (i = 0; i < info->count; i++) {
725         VFIOPCIDevice *tmp;
726 
727         trace_iommufd_cdev_pci_hot_reset_dep_devices(devices[i].segment,
728                                                      devices[i].bus,
729                                                      PCI_SLOT(devices[i].devfn),
730                                                      PCI_FUNC(devices[i].devfn),
731                                                      devices[i].devid);
732 
733         /*
734          * If a VFIO cdev device is resettable, all the dependent devices
735          * are either bound to same iommufd or within same iommu_groups as
736          * one of the iommufd bound devices.
737          */
738         assert(devices[i].devid != VFIO_PCI_DEVID_NOT_OWNED);
739 
740         tmp = iommufd_cdev_dep_get_realized_vpdev(&devices[i], &vdev->vbasedev);
741         if (!tmp) {
742             continue;
743         }
744 
745         if (single) {
746             ret = -EINVAL;
747             goto out_single;
748         }
749         vfio_pci_pre_reset(tmp);
750         tmp->vbasedev.needs_reset = false;
751         multi = true;
752     }
753 
754     if (!single && !multi) {
755         ret = -EINVAL;
756         goto out_single;
757     }
758 
759     /* Use zero length array for hot reset with iommufd backend */
760     reset = g_malloc0(sizeof(*reset));
761     reset->argsz = sizeof(*reset);
762 
763      /* Bus reset! */
764     ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
765     g_free(reset);
766     if (ret) {
767         ret = -errno;
768     }
769 
770     trace_vfio_pci_hot_reset_result(vdev->vbasedev.name,
771                                     ret ? strerror(errno) : "Success");
772 
773     /* Re-enable INTx on affected devices */
774     for (i = 0; i < info->count; i++) {
775         VFIOPCIDevice *tmp;
776 
777         tmp = iommufd_cdev_dep_get_realized_vpdev(&devices[i], &vdev->vbasedev);
778         if (!tmp) {
779             continue;
780         }
781         vfio_pci_post_reset(tmp);
782     }
783 out_single:
784     if (!single) {
785         vfio_pci_post_reset(vdev);
786     }
787     g_free(info);
788 
789     return ret;
790 }
791 
792 static void vfio_iommu_iommufd_class_init(ObjectClass *klass, const void *data)
793 {
794     VFIOIOMMUClass *vioc = VFIO_IOMMU_CLASS(klass);
795 
796     vioc->dma_map = iommufd_cdev_map;
797     vioc->dma_unmap = iommufd_cdev_unmap;
798     vioc->attach_device = iommufd_cdev_attach;
799     vioc->detach_device = iommufd_cdev_detach;
800     vioc->pci_hot_reset = iommufd_cdev_pci_hot_reset;
801     vioc->set_dirty_page_tracking = iommufd_set_dirty_page_tracking;
802     vioc->query_dirty_bitmap = iommufd_query_dirty_bitmap;
803 };
804 
805 static bool hiod_iommufd_vfio_realize(HostIOMMUDevice *hiod, void *opaque,
806                                       Error **errp)
807 {
808     VFIODevice *vdev = opaque;
809     HostIOMMUDeviceCaps *caps = &hiod->caps;
810     enum iommu_hw_info_type type;
811     union {
812         struct iommu_hw_info_vtd vtd;
813     } data;
814     uint64_t hw_caps;
815 
816     hiod->agent = opaque;
817 
818     if (!iommufd_backend_get_device_info(vdev->iommufd, vdev->devid,
819                                          &type, &data, sizeof(data),
820                                          &hw_caps, errp)) {
821         return false;
822     }
823 
824     hiod->name = g_strdup(vdev->name);
825     caps->type = type;
826     caps->hw_caps = hw_caps;
827 
828     return true;
829 }
830 
831 static GList *
832 hiod_iommufd_vfio_get_iova_ranges(HostIOMMUDevice *hiod)
833 {
834     VFIODevice *vdev = hiod->agent;
835 
836     g_assert(vdev);
837     return vfio_container_get_iova_ranges(vdev->bcontainer);
838 }
839 
840 static uint64_t
841 hiod_iommufd_vfio_get_page_size_mask(HostIOMMUDevice *hiod)
842 {
843     VFIODevice *vdev = hiod->agent;
844 
845     g_assert(vdev);
846     return vfio_container_get_page_size_mask(vdev->bcontainer);
847 }
848 
849 
850 static void hiod_iommufd_vfio_class_init(ObjectClass *oc, const void *data)
851 {
852     HostIOMMUDeviceClass *hiodc = HOST_IOMMU_DEVICE_CLASS(oc);
853 
854     hiodc->realize = hiod_iommufd_vfio_realize;
855     hiodc->get_iova_ranges = hiod_iommufd_vfio_get_iova_ranges;
856     hiodc->get_page_size_mask = hiod_iommufd_vfio_get_page_size_mask;
857 };
858 
859 static const TypeInfo types[] = {
860     {
861         .name = TYPE_VFIO_IOMMU_IOMMUFD,
862         .parent = TYPE_VFIO_IOMMU,
863         .instance_size = sizeof(VFIOIOMMUFDContainer),
864         .class_init = vfio_iommu_iommufd_class_init,
865     }, {
866         .name = TYPE_HOST_IOMMU_DEVICE_IOMMUFD_VFIO,
867         .parent = TYPE_HOST_IOMMU_DEVICE_IOMMUFD,
868         .class_init = hiod_iommufd_vfio_class_init,
869     }
870 };
871 
872 DEFINE_TYPES(types)
873