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