1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2012 Red Hat, Inc.  All rights reserved.
4  *     Author: Alex Williamson <alex.williamson@redhat.com>
5  *
6  * Derived from original vfio:
7  * Copyright 2010 Cisco Systems, Inc.  All rights reserved.
8  * Author: Tom Lyon, pugs@cisco.com
9  */
10 
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 
13 #include <linux/aperture.h>
14 #include <linux/device.h>
15 #include <linux/eventfd.h>
16 #include <linux/file.h>
17 #include <linux/interrupt.h>
18 #include <linux/iommu.h>
19 #include <linux/module.h>
20 #include <linux/mutex.h>
21 #include <linux/notifier.h>
22 #include <linux/pci.h>
23 #include <linux/pfn_t.h>
24 #include <linux/pm_runtime.h>
25 #include <linux/slab.h>
26 #include <linux/types.h>
27 #include <linux/uaccess.h>
28 #include <linux/vgaarb.h>
29 #include <linux/nospec.h>
30 #include <linux/sched/mm.h>
31 #include <linux/iommufd.h>
32 #if IS_ENABLED(CONFIG_EEH)
33 #include <asm/eeh.h>
34 #endif
35 
36 #include "vfio_pci_priv.h"
37 
38 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
39 #define DRIVER_DESC "core driver for VFIO based PCI devices"
40 
41 static bool nointxmask;
42 static bool disable_vga;
43 static bool disable_idle_d3;
44 
45 /* List of PF's that vfio_pci_core_sriov_configure() has been called on */
46 static DEFINE_MUTEX(vfio_pci_sriov_pfs_mutex);
47 static LIST_HEAD(vfio_pci_sriov_pfs);
48 
49 struct vfio_pci_dummy_resource {
50 	struct resource		resource;
51 	int			index;
52 	struct list_head	res_next;
53 };
54 
55 struct vfio_pci_vf_token {
56 	struct mutex		lock;
57 	uuid_t			uuid;
58 	int			users;
59 };
60 
61 static inline bool vfio_vga_disabled(void)
62 {
63 #ifdef CONFIG_VFIO_PCI_VGA
64 	return disable_vga;
65 #else
66 	return true;
67 #endif
68 }
69 
70 /*
71  * Our VGA arbiter participation is limited since we don't know anything
72  * about the device itself.  However, if the device is the only VGA device
73  * downstream of a bridge and VFIO VGA support is disabled, then we can
74  * safely return legacy VGA IO and memory as not decoded since the user
75  * has no way to get to it and routing can be disabled externally at the
76  * bridge.
77  */
78 static unsigned int vfio_pci_set_decode(struct pci_dev *pdev, bool single_vga)
79 {
80 	struct pci_dev *tmp = NULL;
81 	unsigned char max_busnr;
82 	unsigned int decodes;
83 
84 	if (single_vga || !vfio_vga_disabled() || pci_is_root_bus(pdev->bus))
85 		return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
86 		       VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
87 
88 	max_busnr = pci_bus_max_busnr(pdev->bus);
89 	decodes = VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
90 
91 	while ((tmp = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, tmp)) != NULL) {
92 		if (tmp == pdev ||
93 		    pci_domain_nr(tmp->bus) != pci_domain_nr(pdev->bus) ||
94 		    pci_is_root_bus(tmp->bus))
95 			continue;
96 
97 		if (tmp->bus->number >= pdev->bus->number &&
98 		    tmp->bus->number <= max_busnr) {
99 			pci_dev_put(tmp);
100 			decodes |= VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
101 			break;
102 		}
103 	}
104 
105 	return decodes;
106 }
107 
108 static void vfio_pci_probe_mmaps(struct vfio_pci_core_device *vdev)
109 {
110 	struct resource *res;
111 	int i;
112 	struct vfio_pci_dummy_resource *dummy_res;
113 
114 	for (i = 0; i < PCI_STD_NUM_BARS; i++) {
115 		int bar = i + PCI_STD_RESOURCES;
116 
117 		res = &vdev->pdev->resource[bar];
118 
119 		if (vdev->pdev->non_mappable_bars)
120 			goto no_mmap;
121 
122 		if (!(res->flags & IORESOURCE_MEM))
123 			goto no_mmap;
124 
125 		/*
126 		 * The PCI core shouldn't set up a resource with a
127 		 * type but zero size. But there may be bugs that
128 		 * cause us to do that.
129 		 */
130 		if (!resource_size(res))
131 			goto no_mmap;
132 
133 		if (resource_size(res) >= PAGE_SIZE) {
134 			vdev->bar_mmap_supported[bar] = true;
135 			continue;
136 		}
137 
138 		if (!(res->start & ~PAGE_MASK)) {
139 			/*
140 			 * Add a dummy resource to reserve the remainder
141 			 * of the exclusive page in case that hot-add
142 			 * device's bar is assigned into it.
143 			 */
144 			dummy_res =
145 				kzalloc(sizeof(*dummy_res), GFP_KERNEL_ACCOUNT);
146 			if (dummy_res == NULL)
147 				goto no_mmap;
148 
149 			dummy_res->resource.name = "vfio sub-page reserved";
150 			dummy_res->resource.start = res->end + 1;
151 			dummy_res->resource.end = res->start + PAGE_SIZE - 1;
152 			dummy_res->resource.flags = res->flags;
153 			if (request_resource(res->parent,
154 						&dummy_res->resource)) {
155 				kfree(dummy_res);
156 				goto no_mmap;
157 			}
158 			dummy_res->index = bar;
159 			list_add(&dummy_res->res_next,
160 					&vdev->dummy_resources_list);
161 			vdev->bar_mmap_supported[bar] = true;
162 			continue;
163 		}
164 		/*
165 		 * Here we don't handle the case when the BAR is not page
166 		 * aligned because we can't expect the BAR will be
167 		 * assigned into the same location in a page in guest
168 		 * when we passthrough the BAR. And it's hard to access
169 		 * this BAR in userspace because we have no way to get
170 		 * the BAR's location in a page.
171 		 */
172 no_mmap:
173 		vdev->bar_mmap_supported[bar] = false;
174 	}
175 }
176 
177 struct vfio_pci_group_info;
178 static void vfio_pci_dev_set_try_reset(struct vfio_device_set *dev_set);
179 static int vfio_pci_dev_set_hot_reset(struct vfio_device_set *dev_set,
180 				      struct vfio_pci_group_info *groups,
181 				      struct iommufd_ctx *iommufd_ctx);
182 
183 /*
184  * INTx masking requires the ability to disable INTx signaling via PCI_COMMAND
185  * _and_ the ability detect when the device is asserting INTx via PCI_STATUS.
186  * If a device implements the former but not the latter we would typically
187  * expect broken_intx_masking be set and require an exclusive interrupt.
188  * However since we do have control of the device's ability to assert INTx,
189  * we can instead pretend that the device does not implement INTx, virtualizing
190  * the pin register to report zero and maintaining DisINTx set on the host.
191  */
192 static bool vfio_pci_nointx(struct pci_dev *pdev)
193 {
194 	switch (pdev->vendor) {
195 	case PCI_VENDOR_ID_INTEL:
196 		switch (pdev->device) {
197 		/* All i40e (XL710/X710/XXV710) 10/20/25/40GbE NICs */
198 		case 0x1572:
199 		case 0x1574:
200 		case 0x1580 ... 0x1581:
201 		case 0x1583 ... 0x158b:
202 		case 0x37d0 ... 0x37d2:
203 		/* X550 */
204 		case 0x1563:
205 			return true;
206 		default:
207 			return false;
208 		}
209 	}
210 
211 	return false;
212 }
213 
214 static void vfio_pci_probe_power_state(struct vfio_pci_core_device *vdev)
215 {
216 	struct pci_dev *pdev = vdev->pdev;
217 	u16 pmcsr;
218 
219 	if (!pdev->pm_cap)
220 		return;
221 
222 	pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmcsr);
223 
224 	vdev->needs_pm_restore = !(pmcsr & PCI_PM_CTRL_NO_SOFT_RESET);
225 }
226 
227 /*
228  * pci_set_power_state() wrapper handling devices which perform a soft reset on
229  * D3->D0 transition.  Save state prior to D0/1/2->D3, stash it on the vdev,
230  * restore when returned to D0.  Saved separately from pci_saved_state for use
231  * by PM capability emulation and separately from pci_dev internal saved state
232  * to avoid it being overwritten and consumed around other resets.
233  */
234 int vfio_pci_set_power_state(struct vfio_pci_core_device *vdev, pci_power_t state)
235 {
236 	struct pci_dev *pdev = vdev->pdev;
237 	bool needs_restore = false, needs_save = false;
238 	int ret;
239 
240 	/* Prevent changing power state for PFs with VFs enabled */
241 	if (pci_num_vf(pdev) && state > PCI_D0)
242 		return -EBUSY;
243 
244 	if (vdev->needs_pm_restore) {
245 		if (pdev->current_state < PCI_D3hot && state >= PCI_D3hot) {
246 			pci_save_state(pdev);
247 			needs_save = true;
248 		}
249 
250 		if (pdev->current_state >= PCI_D3hot && state <= PCI_D0)
251 			needs_restore = true;
252 	}
253 
254 	ret = pci_set_power_state(pdev, state);
255 
256 	if (!ret) {
257 		/* D3 might be unsupported via quirk, skip unless in D3 */
258 		if (needs_save && pdev->current_state >= PCI_D3hot) {
259 			/*
260 			 * The current PCI state will be saved locally in
261 			 * 'pm_save' during the D3hot transition. When the
262 			 * device state is changed to D0 again with the current
263 			 * function, then pci_store_saved_state() will restore
264 			 * the state and will free the memory pointed by
265 			 * 'pm_save'. There are few cases where the PCI power
266 			 * state can be changed to D0 without the involvement
267 			 * of the driver. For these cases, free the earlier
268 			 * allocated memory first before overwriting 'pm_save'
269 			 * to prevent the memory leak.
270 			 */
271 			kfree(vdev->pm_save);
272 			vdev->pm_save = pci_store_saved_state(pdev);
273 		} else if (needs_restore) {
274 			pci_load_and_free_saved_state(pdev, &vdev->pm_save);
275 			pci_restore_state(pdev);
276 		}
277 	}
278 
279 	return ret;
280 }
281 
282 static int vfio_pci_runtime_pm_entry(struct vfio_pci_core_device *vdev,
283 				     struct eventfd_ctx *efdctx)
284 {
285 	/*
286 	 * The vdev power related flags are protected with 'memory_lock'
287 	 * semaphore.
288 	 */
289 	vfio_pci_zap_and_down_write_memory_lock(vdev);
290 	if (vdev->pm_runtime_engaged) {
291 		up_write(&vdev->memory_lock);
292 		return -EINVAL;
293 	}
294 
295 	vdev->pm_runtime_engaged = true;
296 	vdev->pm_wake_eventfd_ctx = efdctx;
297 	pm_runtime_put_noidle(&vdev->pdev->dev);
298 	up_write(&vdev->memory_lock);
299 
300 	return 0;
301 }
302 
303 static int vfio_pci_core_pm_entry(struct vfio_device *device, u32 flags,
304 				  void __user *arg, size_t argsz)
305 {
306 	struct vfio_pci_core_device *vdev =
307 		container_of(device, struct vfio_pci_core_device, vdev);
308 	int ret;
309 
310 	ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_SET, 0);
311 	if (ret != 1)
312 		return ret;
313 
314 	/*
315 	 * Inside vfio_pci_runtime_pm_entry(), only the runtime PM usage count
316 	 * will be decremented. The pm_runtime_put() will be invoked again
317 	 * while returning from the ioctl and then the device can go into
318 	 * runtime suspended state.
319 	 */
320 	return vfio_pci_runtime_pm_entry(vdev, NULL);
321 }
322 
323 static int vfio_pci_core_pm_entry_with_wakeup(
324 	struct vfio_device *device, u32 flags,
325 	struct vfio_device_low_power_entry_with_wakeup __user *arg,
326 	size_t argsz)
327 {
328 	struct vfio_pci_core_device *vdev =
329 		container_of(device, struct vfio_pci_core_device, vdev);
330 	struct vfio_device_low_power_entry_with_wakeup entry;
331 	struct eventfd_ctx *efdctx;
332 	int ret;
333 
334 	ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_SET,
335 				 sizeof(entry));
336 	if (ret != 1)
337 		return ret;
338 
339 	if (copy_from_user(&entry, arg, sizeof(entry)))
340 		return -EFAULT;
341 
342 	if (entry.wakeup_eventfd < 0)
343 		return -EINVAL;
344 
345 	efdctx = eventfd_ctx_fdget(entry.wakeup_eventfd);
346 	if (IS_ERR(efdctx))
347 		return PTR_ERR(efdctx);
348 
349 	ret = vfio_pci_runtime_pm_entry(vdev, efdctx);
350 	if (ret)
351 		eventfd_ctx_put(efdctx);
352 
353 	return ret;
354 }
355 
356 static void __vfio_pci_runtime_pm_exit(struct vfio_pci_core_device *vdev)
357 {
358 	if (vdev->pm_runtime_engaged) {
359 		vdev->pm_runtime_engaged = false;
360 		pm_runtime_get_noresume(&vdev->pdev->dev);
361 
362 		if (vdev->pm_wake_eventfd_ctx) {
363 			eventfd_ctx_put(vdev->pm_wake_eventfd_ctx);
364 			vdev->pm_wake_eventfd_ctx = NULL;
365 		}
366 	}
367 }
368 
369 static void vfio_pci_runtime_pm_exit(struct vfio_pci_core_device *vdev)
370 {
371 	/*
372 	 * The vdev power related flags are protected with 'memory_lock'
373 	 * semaphore.
374 	 */
375 	down_write(&vdev->memory_lock);
376 	__vfio_pci_runtime_pm_exit(vdev);
377 	up_write(&vdev->memory_lock);
378 }
379 
380 static int vfio_pci_core_pm_exit(struct vfio_device *device, u32 flags,
381 				 void __user *arg, size_t argsz)
382 {
383 	struct vfio_pci_core_device *vdev =
384 		container_of(device, struct vfio_pci_core_device, vdev);
385 	int ret;
386 
387 	ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_SET, 0);
388 	if (ret != 1)
389 		return ret;
390 
391 	/*
392 	 * The device is always in the active state here due to pm wrappers
393 	 * around ioctls. If the device had entered a low power state and
394 	 * pm_wake_eventfd_ctx is valid, vfio_pci_core_runtime_resume() has
395 	 * already signaled the eventfd and exited low power mode itself.
396 	 * pm_runtime_engaged protects the redundant call here.
397 	 */
398 	vfio_pci_runtime_pm_exit(vdev);
399 	return 0;
400 }
401 
402 #ifdef CONFIG_PM
403 static int vfio_pci_core_runtime_suspend(struct device *dev)
404 {
405 	struct vfio_pci_core_device *vdev = dev_get_drvdata(dev);
406 
407 	down_write(&vdev->memory_lock);
408 	/*
409 	 * The user can move the device into D3hot state before invoking
410 	 * power management IOCTL. Move the device into D0 state here and then
411 	 * the pci-driver core runtime PM suspend function will move the device
412 	 * into the low power state. Also, for the devices which have
413 	 * NoSoftRst-, it will help in restoring the original state
414 	 * (saved locally in 'vdev->pm_save').
415 	 */
416 	vfio_pci_set_power_state(vdev, PCI_D0);
417 	up_write(&vdev->memory_lock);
418 
419 	/*
420 	 * If INTx is enabled, then mask INTx before going into the runtime
421 	 * suspended state and unmask the same in the runtime resume.
422 	 * If INTx has already been masked by the user, then
423 	 * vfio_pci_intx_mask() will return false and in that case, INTx
424 	 * should not be unmasked in the runtime resume.
425 	 */
426 	vdev->pm_intx_masked = ((vdev->irq_type == VFIO_PCI_INTX_IRQ_INDEX) &&
427 				vfio_pci_intx_mask(vdev));
428 
429 	return 0;
430 }
431 
432 static int vfio_pci_core_runtime_resume(struct device *dev)
433 {
434 	struct vfio_pci_core_device *vdev = dev_get_drvdata(dev);
435 
436 	/*
437 	 * Resume with a pm_wake_eventfd_ctx signals the eventfd and exit
438 	 * low power mode.
439 	 */
440 	down_write(&vdev->memory_lock);
441 	if (vdev->pm_wake_eventfd_ctx) {
442 		eventfd_signal(vdev->pm_wake_eventfd_ctx);
443 		__vfio_pci_runtime_pm_exit(vdev);
444 	}
445 	up_write(&vdev->memory_lock);
446 
447 	if (vdev->pm_intx_masked)
448 		vfio_pci_intx_unmask(vdev);
449 
450 	return 0;
451 }
452 #endif /* CONFIG_PM */
453 
454 /*
455  * The pci-driver core runtime PM routines always save the device state
456  * before going into suspended state. If the device is going into low power
457  * state with only with runtime PM ops, then no explicit handling is needed
458  * for the devices which have NoSoftRst-.
459  */
460 static const struct dev_pm_ops vfio_pci_core_pm_ops = {
461 	SET_RUNTIME_PM_OPS(vfio_pci_core_runtime_suspend,
462 			   vfio_pci_core_runtime_resume,
463 			   NULL)
464 };
465 
466 int vfio_pci_core_enable(struct vfio_pci_core_device *vdev)
467 {
468 	struct pci_dev *pdev = vdev->pdev;
469 	int ret;
470 	u16 cmd;
471 	u8 msix_pos;
472 
473 	if (!disable_idle_d3) {
474 		ret = pm_runtime_resume_and_get(&pdev->dev);
475 		if (ret < 0)
476 			return ret;
477 	}
478 
479 	/* Don't allow our initial saved state to include busmaster */
480 	pci_clear_master(pdev);
481 
482 	ret = pci_enable_device(pdev);
483 	if (ret)
484 		goto out_power;
485 
486 	/* If reset fails because of the device lock, fail this path entirely */
487 	ret = pci_try_reset_function(pdev);
488 	if (ret == -EAGAIN)
489 		goto out_disable_device;
490 
491 	vdev->reset_works = !ret;
492 	pci_save_state(pdev);
493 	vdev->pci_saved_state = pci_store_saved_state(pdev);
494 	if (!vdev->pci_saved_state)
495 		pci_dbg(pdev, "%s: Couldn't store saved state\n", __func__);
496 
497 	if (likely(!nointxmask)) {
498 		if (vfio_pci_nointx(pdev)) {
499 			pci_info(pdev, "Masking broken INTx support\n");
500 			vdev->nointx = true;
501 			pci_intx(pdev, 0);
502 		} else
503 			vdev->pci_2_3 = pci_intx_mask_supported(pdev);
504 	}
505 
506 	pci_read_config_word(pdev, PCI_COMMAND, &cmd);
507 	if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
508 		cmd &= ~PCI_COMMAND_INTX_DISABLE;
509 		pci_write_config_word(pdev, PCI_COMMAND, cmd);
510 	}
511 
512 	ret = vfio_pci_zdev_open_device(vdev);
513 	if (ret)
514 		goto out_free_state;
515 
516 	ret = vfio_config_init(vdev);
517 	if (ret)
518 		goto out_free_zdev;
519 
520 	msix_pos = pdev->msix_cap;
521 	if (msix_pos) {
522 		u16 flags;
523 		u32 table;
524 
525 		pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
526 		pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
527 
528 		vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
529 		vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
530 		vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
531 		vdev->has_dyn_msix = pci_msix_can_alloc_dyn(pdev);
532 	} else {
533 		vdev->msix_bar = 0xFF;
534 		vdev->has_dyn_msix = false;
535 	}
536 
537 	if (!vfio_vga_disabled() && vfio_pci_is_vga(pdev))
538 		vdev->has_vga = true;
539 
540 
541 	return 0;
542 
543 out_free_zdev:
544 	vfio_pci_zdev_close_device(vdev);
545 out_free_state:
546 	kfree(vdev->pci_saved_state);
547 	vdev->pci_saved_state = NULL;
548 out_disable_device:
549 	pci_disable_device(pdev);
550 out_power:
551 	if (!disable_idle_d3)
552 		pm_runtime_put(&pdev->dev);
553 	return ret;
554 }
555 EXPORT_SYMBOL_GPL(vfio_pci_core_enable);
556 
557 void vfio_pci_core_disable(struct vfio_pci_core_device *vdev)
558 {
559 	struct pci_dev *pdev = vdev->pdev;
560 	struct vfio_pci_dummy_resource *dummy_res, *tmp;
561 	struct vfio_pci_ioeventfd *ioeventfd, *ioeventfd_tmp;
562 	int i, bar;
563 
564 	/* For needs_reset */
565 	lockdep_assert_held(&vdev->vdev.dev_set->lock);
566 
567 	/*
568 	 * This function can be invoked while the power state is non-D0.
569 	 * This non-D0 power state can be with or without runtime PM.
570 	 * vfio_pci_runtime_pm_exit() will internally increment the usage
571 	 * count corresponding to pm_runtime_put() called during low power
572 	 * feature entry and then pm_runtime_resume() will wake up the device,
573 	 * if the device has already gone into the suspended state. Otherwise,
574 	 * the vfio_pci_set_power_state() will change the device power state
575 	 * to D0.
576 	 */
577 	vfio_pci_runtime_pm_exit(vdev);
578 	pm_runtime_resume(&pdev->dev);
579 
580 	/*
581 	 * This function calls __pci_reset_function_locked() which internally
582 	 * can use pci_pm_reset() for the function reset. pci_pm_reset() will
583 	 * fail if the power state is non-D0. Also, for the devices which
584 	 * have NoSoftRst-, the reset function can cause the PCI config space
585 	 * reset without restoring the original state (saved locally in
586 	 * 'vdev->pm_save').
587 	 */
588 	vfio_pci_set_power_state(vdev, PCI_D0);
589 
590 	/* Stop the device from further DMA */
591 	pci_clear_master(pdev);
592 
593 	vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
594 				VFIO_IRQ_SET_ACTION_TRIGGER,
595 				vdev->irq_type, 0, 0, NULL);
596 
597 	/* Device closed, don't need mutex here */
598 	list_for_each_entry_safe(ioeventfd, ioeventfd_tmp,
599 				 &vdev->ioeventfds_list, next) {
600 		vfio_virqfd_disable(&ioeventfd->virqfd);
601 		list_del(&ioeventfd->next);
602 		kfree(ioeventfd);
603 	}
604 	vdev->ioeventfds_nr = 0;
605 
606 	vdev->virq_disabled = false;
607 
608 	for (i = 0; i < vdev->num_regions; i++)
609 		vdev->region[i].ops->release(vdev, &vdev->region[i]);
610 
611 	vdev->num_regions = 0;
612 	kfree(vdev->region);
613 	vdev->region = NULL; /* don't krealloc a freed pointer */
614 
615 	vfio_config_free(vdev);
616 
617 	for (i = 0; i < PCI_STD_NUM_BARS; i++) {
618 		bar = i + PCI_STD_RESOURCES;
619 		if (!vdev->barmap[bar])
620 			continue;
621 		pci_iounmap(pdev, vdev->barmap[bar]);
622 		pci_release_selected_regions(pdev, 1 << bar);
623 		vdev->barmap[bar] = NULL;
624 	}
625 
626 	list_for_each_entry_safe(dummy_res, tmp,
627 				 &vdev->dummy_resources_list, res_next) {
628 		list_del(&dummy_res->res_next);
629 		release_resource(&dummy_res->resource);
630 		kfree(dummy_res);
631 	}
632 
633 	vdev->needs_reset = true;
634 
635 	vfio_pci_zdev_close_device(vdev);
636 
637 	/*
638 	 * If we have saved state, restore it.  If we can reset the device,
639 	 * even better.  Resetting with current state seems better than
640 	 * nothing, but saving and restoring current state without reset
641 	 * is just busy work.
642 	 */
643 	if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
644 		pci_info(pdev, "%s: Couldn't reload saved state\n", __func__);
645 
646 		if (!vdev->reset_works)
647 			goto out;
648 
649 		pci_save_state(pdev);
650 	}
651 
652 	/*
653 	 * Disable INTx and MSI, presumably to avoid spurious interrupts
654 	 * during reset.  Stolen from pci_reset_function()
655 	 */
656 	pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
657 
658 	/*
659 	 * Try to get the locks ourselves to prevent a deadlock. The
660 	 * success of this is dependent on being able to lock the device,
661 	 * which is not always possible.
662 	 * We can not use the "try" reset interface here, which will
663 	 * overwrite the previously restored configuration information.
664 	 */
665 	if (vdev->reset_works && pci_dev_trylock(pdev)) {
666 		if (!__pci_reset_function_locked(pdev))
667 			vdev->needs_reset = false;
668 		pci_dev_unlock(pdev);
669 	}
670 
671 	pci_restore_state(pdev);
672 out:
673 	pci_disable_device(pdev);
674 
675 	vfio_pci_dev_set_try_reset(vdev->vdev.dev_set);
676 
677 	/* Put the pm-runtime usage counter acquired during enable */
678 	if (!disable_idle_d3)
679 		pm_runtime_put(&pdev->dev);
680 }
681 EXPORT_SYMBOL_GPL(vfio_pci_core_disable);
682 
683 void vfio_pci_core_close_device(struct vfio_device *core_vdev)
684 {
685 	struct vfio_pci_core_device *vdev =
686 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
687 
688 	if (vdev->sriov_pf_core_dev) {
689 		mutex_lock(&vdev->sriov_pf_core_dev->vf_token->lock);
690 		WARN_ON(!vdev->sriov_pf_core_dev->vf_token->users);
691 		vdev->sriov_pf_core_dev->vf_token->users--;
692 		mutex_unlock(&vdev->sriov_pf_core_dev->vf_token->lock);
693 	}
694 #if IS_ENABLED(CONFIG_EEH)
695 	eeh_dev_release(vdev->pdev);
696 #endif
697 	vfio_pci_core_disable(vdev);
698 
699 	mutex_lock(&vdev->igate);
700 	if (vdev->err_trigger) {
701 		eventfd_ctx_put(vdev->err_trigger);
702 		vdev->err_trigger = NULL;
703 	}
704 	if (vdev->req_trigger) {
705 		eventfd_ctx_put(vdev->req_trigger);
706 		vdev->req_trigger = NULL;
707 	}
708 	mutex_unlock(&vdev->igate);
709 }
710 EXPORT_SYMBOL_GPL(vfio_pci_core_close_device);
711 
712 void vfio_pci_core_finish_enable(struct vfio_pci_core_device *vdev)
713 {
714 	vfio_pci_probe_mmaps(vdev);
715 #if IS_ENABLED(CONFIG_EEH)
716 	eeh_dev_open(vdev->pdev);
717 #endif
718 
719 	if (vdev->sriov_pf_core_dev) {
720 		mutex_lock(&vdev->sriov_pf_core_dev->vf_token->lock);
721 		vdev->sriov_pf_core_dev->vf_token->users++;
722 		mutex_unlock(&vdev->sriov_pf_core_dev->vf_token->lock);
723 	}
724 }
725 EXPORT_SYMBOL_GPL(vfio_pci_core_finish_enable);
726 
727 static int vfio_pci_get_irq_count(struct vfio_pci_core_device *vdev, int irq_type)
728 {
729 	if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
730 		return vdev->vconfig[PCI_INTERRUPT_PIN] ? 1 : 0;
731 	} else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
732 		u8 pos;
733 		u16 flags;
734 
735 		pos = vdev->pdev->msi_cap;
736 		if (pos) {
737 			pci_read_config_word(vdev->pdev,
738 					     pos + PCI_MSI_FLAGS, &flags);
739 			return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
740 		}
741 	} else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
742 		u8 pos;
743 		u16 flags;
744 
745 		pos = vdev->pdev->msix_cap;
746 		if (pos) {
747 			pci_read_config_word(vdev->pdev,
748 					     pos + PCI_MSIX_FLAGS, &flags);
749 
750 			return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
751 		}
752 	} else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX) {
753 		if (pci_is_pcie(vdev->pdev))
754 			return 1;
755 	} else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
756 		return 1;
757 	}
758 
759 	return 0;
760 }
761 
762 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
763 {
764 	(*(int *)data)++;
765 	return 0;
766 }
767 
768 struct vfio_pci_fill_info {
769 	struct vfio_device *vdev;
770 	struct vfio_pci_dependent_device *devices;
771 	int nr_devices;
772 	u32 count;
773 	u32 flags;
774 };
775 
776 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
777 {
778 	struct vfio_pci_dependent_device *info;
779 	struct vfio_pci_fill_info *fill = data;
780 
781 	/* The topology changed since we counted devices */
782 	if (fill->count >= fill->nr_devices)
783 		return -EAGAIN;
784 
785 	info = &fill->devices[fill->count++];
786 	info->segment = pci_domain_nr(pdev->bus);
787 	info->bus = pdev->bus->number;
788 	info->devfn = pdev->devfn;
789 
790 	if (fill->flags & VFIO_PCI_HOT_RESET_FLAG_DEV_ID) {
791 		struct iommufd_ctx *iommufd = vfio_iommufd_device_ictx(fill->vdev);
792 		struct vfio_device_set *dev_set = fill->vdev->dev_set;
793 		struct vfio_device *vdev;
794 
795 		/*
796 		 * hot-reset requires all affected devices be represented in
797 		 * the dev_set.
798 		 */
799 		vdev = vfio_find_device_in_devset(dev_set, &pdev->dev);
800 		if (!vdev) {
801 			info->devid = VFIO_PCI_DEVID_NOT_OWNED;
802 		} else {
803 			int id = vfio_iommufd_get_dev_id(vdev, iommufd);
804 
805 			if (id > 0)
806 				info->devid = id;
807 			else if (id == -ENOENT)
808 				info->devid = VFIO_PCI_DEVID_OWNED;
809 			else
810 				info->devid = VFIO_PCI_DEVID_NOT_OWNED;
811 		}
812 		/* If devid is VFIO_PCI_DEVID_NOT_OWNED, clear owned flag. */
813 		if (info->devid == VFIO_PCI_DEVID_NOT_OWNED)
814 			fill->flags &= ~VFIO_PCI_HOT_RESET_FLAG_DEV_ID_OWNED;
815 	} else {
816 		struct iommu_group *iommu_group;
817 
818 		iommu_group = iommu_group_get(&pdev->dev);
819 		if (!iommu_group)
820 			return -EPERM; /* Cannot reset non-isolated devices */
821 
822 		info->group_id = iommu_group_id(iommu_group);
823 		iommu_group_put(iommu_group);
824 	}
825 
826 	return 0;
827 }
828 
829 struct vfio_pci_group_info {
830 	int count;
831 	struct file **files;
832 };
833 
834 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
835 {
836 	for (; pdev; pdev = pdev->bus->self)
837 		if (pdev->bus == slot->bus)
838 			return (pdev->slot == slot);
839 	return false;
840 }
841 
842 struct vfio_pci_walk_info {
843 	int (*fn)(struct pci_dev *pdev, void *data);
844 	void *data;
845 	struct pci_dev *pdev;
846 	bool slot;
847 	int ret;
848 };
849 
850 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
851 {
852 	struct vfio_pci_walk_info *walk = data;
853 
854 	if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
855 		walk->ret = walk->fn(pdev, walk->data);
856 
857 	return walk->ret;
858 }
859 
860 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
861 					 int (*fn)(struct pci_dev *,
862 						   void *data), void *data,
863 					 bool slot)
864 {
865 	struct vfio_pci_walk_info walk = {
866 		.fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
867 	};
868 
869 	pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
870 
871 	return walk.ret;
872 }
873 
874 static int msix_mmappable_cap(struct vfio_pci_core_device *vdev,
875 			      struct vfio_info_cap *caps)
876 {
877 	struct vfio_info_cap_header header = {
878 		.id = VFIO_REGION_INFO_CAP_MSIX_MAPPABLE,
879 		.version = 1
880 	};
881 
882 	return vfio_info_add_capability(caps, &header, sizeof(header));
883 }
884 
885 int vfio_pci_core_register_dev_region(struct vfio_pci_core_device *vdev,
886 				      unsigned int type, unsigned int subtype,
887 				      const struct vfio_pci_regops *ops,
888 				      size_t size, u32 flags, void *data)
889 {
890 	struct vfio_pci_region *region;
891 
892 	region = krealloc(vdev->region,
893 			  (vdev->num_regions + 1) * sizeof(*region),
894 			  GFP_KERNEL_ACCOUNT);
895 	if (!region)
896 		return -ENOMEM;
897 
898 	vdev->region = region;
899 	vdev->region[vdev->num_regions].type = type;
900 	vdev->region[vdev->num_regions].subtype = subtype;
901 	vdev->region[vdev->num_regions].ops = ops;
902 	vdev->region[vdev->num_regions].size = size;
903 	vdev->region[vdev->num_regions].flags = flags;
904 	vdev->region[vdev->num_regions].data = data;
905 
906 	vdev->num_regions++;
907 
908 	return 0;
909 }
910 EXPORT_SYMBOL_GPL(vfio_pci_core_register_dev_region);
911 
912 static int vfio_pci_info_atomic_cap(struct vfio_pci_core_device *vdev,
913 				    struct vfio_info_cap *caps)
914 {
915 	struct vfio_device_info_cap_pci_atomic_comp cap = {
916 		.header.id = VFIO_DEVICE_INFO_CAP_PCI_ATOMIC_COMP,
917 		.header.version = 1
918 	};
919 	struct pci_dev *pdev = pci_physfn(vdev->pdev);
920 	u32 devcap2;
921 
922 	pcie_capability_read_dword(pdev, PCI_EXP_DEVCAP2, &devcap2);
923 
924 	if ((devcap2 & PCI_EXP_DEVCAP2_ATOMIC_COMP32) &&
925 	    !pci_enable_atomic_ops_to_root(pdev, PCI_EXP_DEVCAP2_ATOMIC_COMP32))
926 		cap.flags |= VFIO_PCI_ATOMIC_COMP32;
927 
928 	if ((devcap2 & PCI_EXP_DEVCAP2_ATOMIC_COMP64) &&
929 	    !pci_enable_atomic_ops_to_root(pdev, PCI_EXP_DEVCAP2_ATOMIC_COMP64))
930 		cap.flags |= VFIO_PCI_ATOMIC_COMP64;
931 
932 	if ((devcap2 & PCI_EXP_DEVCAP2_ATOMIC_COMP128) &&
933 	    !pci_enable_atomic_ops_to_root(pdev,
934 					   PCI_EXP_DEVCAP2_ATOMIC_COMP128))
935 		cap.flags |= VFIO_PCI_ATOMIC_COMP128;
936 
937 	if (!cap.flags)
938 		return -ENODEV;
939 
940 	return vfio_info_add_capability(caps, &cap.header, sizeof(cap));
941 }
942 
943 static int vfio_pci_ioctl_get_info(struct vfio_pci_core_device *vdev,
944 				   struct vfio_device_info __user *arg)
945 {
946 	unsigned long minsz = offsetofend(struct vfio_device_info, num_irqs);
947 	struct vfio_device_info info = {};
948 	struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
949 	int ret;
950 
951 	if (copy_from_user(&info, arg, minsz))
952 		return -EFAULT;
953 
954 	if (info.argsz < minsz)
955 		return -EINVAL;
956 
957 	minsz = min_t(size_t, info.argsz, sizeof(info));
958 
959 	info.flags = VFIO_DEVICE_FLAGS_PCI;
960 
961 	if (vdev->reset_works)
962 		info.flags |= VFIO_DEVICE_FLAGS_RESET;
963 
964 	info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions;
965 	info.num_irqs = VFIO_PCI_NUM_IRQS;
966 
967 	ret = vfio_pci_info_zdev_add_caps(vdev, &caps);
968 	if (ret && ret != -ENODEV) {
969 		pci_warn(vdev->pdev,
970 			 "Failed to setup zPCI info capabilities\n");
971 		return ret;
972 	}
973 
974 	ret = vfio_pci_info_atomic_cap(vdev, &caps);
975 	if (ret && ret != -ENODEV) {
976 		pci_warn(vdev->pdev,
977 			 "Failed to setup AtomicOps info capability\n");
978 		return ret;
979 	}
980 
981 	if (caps.size) {
982 		info.flags |= VFIO_DEVICE_FLAGS_CAPS;
983 		if (info.argsz < sizeof(info) + caps.size) {
984 			info.argsz = sizeof(info) + caps.size;
985 		} else {
986 			vfio_info_cap_shift(&caps, sizeof(info));
987 			if (copy_to_user(arg + 1, caps.buf, caps.size)) {
988 				kfree(caps.buf);
989 				return -EFAULT;
990 			}
991 			info.cap_offset = sizeof(*arg);
992 		}
993 
994 		kfree(caps.buf);
995 	}
996 
997 	return copy_to_user(arg, &info, minsz) ? -EFAULT : 0;
998 }
999 
1000 static int vfio_pci_ioctl_get_region_info(struct vfio_pci_core_device *vdev,
1001 					  struct vfio_region_info __user *arg)
1002 {
1003 	unsigned long minsz = offsetofend(struct vfio_region_info, offset);
1004 	struct pci_dev *pdev = vdev->pdev;
1005 	struct vfio_region_info info;
1006 	struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
1007 	int i, ret;
1008 
1009 	if (copy_from_user(&info, arg, minsz))
1010 		return -EFAULT;
1011 
1012 	if (info.argsz < minsz)
1013 		return -EINVAL;
1014 
1015 	switch (info.index) {
1016 	case VFIO_PCI_CONFIG_REGION_INDEX:
1017 		info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
1018 		info.size = pdev->cfg_size;
1019 		info.flags = VFIO_REGION_INFO_FLAG_READ |
1020 			     VFIO_REGION_INFO_FLAG_WRITE;
1021 		break;
1022 	case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
1023 		info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
1024 		info.size = pci_resource_len(pdev, info.index);
1025 		if (!info.size) {
1026 			info.flags = 0;
1027 			break;
1028 		}
1029 
1030 		info.flags = VFIO_REGION_INFO_FLAG_READ |
1031 			     VFIO_REGION_INFO_FLAG_WRITE;
1032 		if (vdev->bar_mmap_supported[info.index]) {
1033 			info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
1034 			if (info.index == vdev->msix_bar) {
1035 				ret = msix_mmappable_cap(vdev, &caps);
1036 				if (ret)
1037 					return ret;
1038 			}
1039 		}
1040 
1041 		break;
1042 	case VFIO_PCI_ROM_REGION_INDEX: {
1043 		void __iomem *io;
1044 		size_t size;
1045 		u16 cmd;
1046 
1047 		info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
1048 		info.flags = 0;
1049 		info.size = 0;
1050 
1051 		if (pci_resource_start(pdev, PCI_ROM_RESOURCE)) {
1052 			/*
1053 			 * Check ROM content is valid. Need to enable memory
1054 			 * decode for ROM access in pci_map_rom().
1055 			 */
1056 			cmd = vfio_pci_memory_lock_and_enable(vdev);
1057 			io = pci_map_rom(pdev, &size);
1058 			if (io) {
1059 				info.flags = VFIO_REGION_INFO_FLAG_READ;
1060 				/* Report the BAR size, not the ROM size. */
1061 				info.size = pci_resource_len(pdev, PCI_ROM_RESOURCE);
1062 				pci_unmap_rom(pdev, io);
1063 			}
1064 			vfio_pci_memory_unlock_and_restore(vdev, cmd);
1065 		} else if (pdev->rom && pdev->romlen) {
1066 			info.flags = VFIO_REGION_INFO_FLAG_READ;
1067 			/* Report BAR size as power of two. */
1068 			info.size = roundup_pow_of_two(pdev->romlen);
1069 		}
1070 
1071 		break;
1072 	}
1073 	case VFIO_PCI_VGA_REGION_INDEX:
1074 		if (!vdev->has_vga)
1075 			return -EINVAL;
1076 
1077 		info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
1078 		info.size = 0xc0000;
1079 		info.flags = VFIO_REGION_INFO_FLAG_READ |
1080 			     VFIO_REGION_INFO_FLAG_WRITE;
1081 
1082 		break;
1083 	default: {
1084 		struct vfio_region_info_cap_type cap_type = {
1085 			.header.id = VFIO_REGION_INFO_CAP_TYPE,
1086 			.header.version = 1
1087 		};
1088 
1089 		if (info.index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1090 			return -EINVAL;
1091 		info.index = array_index_nospec(
1092 			info.index, VFIO_PCI_NUM_REGIONS + vdev->num_regions);
1093 
1094 		i = info.index - VFIO_PCI_NUM_REGIONS;
1095 
1096 		info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
1097 		info.size = vdev->region[i].size;
1098 		info.flags = vdev->region[i].flags;
1099 
1100 		cap_type.type = vdev->region[i].type;
1101 		cap_type.subtype = vdev->region[i].subtype;
1102 
1103 		ret = vfio_info_add_capability(&caps, &cap_type.header,
1104 					       sizeof(cap_type));
1105 		if (ret)
1106 			return ret;
1107 
1108 		if (vdev->region[i].ops->add_capability) {
1109 			ret = vdev->region[i].ops->add_capability(
1110 				vdev, &vdev->region[i], &caps);
1111 			if (ret)
1112 				return ret;
1113 		}
1114 	}
1115 	}
1116 
1117 	if (caps.size) {
1118 		info.flags |= VFIO_REGION_INFO_FLAG_CAPS;
1119 		if (info.argsz < sizeof(info) + caps.size) {
1120 			info.argsz = sizeof(info) + caps.size;
1121 			info.cap_offset = 0;
1122 		} else {
1123 			vfio_info_cap_shift(&caps, sizeof(info));
1124 			if (copy_to_user(arg + 1, caps.buf, caps.size)) {
1125 				kfree(caps.buf);
1126 				return -EFAULT;
1127 			}
1128 			info.cap_offset = sizeof(*arg);
1129 		}
1130 
1131 		kfree(caps.buf);
1132 	}
1133 
1134 	return copy_to_user(arg, &info, minsz) ? -EFAULT : 0;
1135 }
1136 
1137 static int vfio_pci_ioctl_get_irq_info(struct vfio_pci_core_device *vdev,
1138 				       struct vfio_irq_info __user *arg)
1139 {
1140 	unsigned long minsz = offsetofend(struct vfio_irq_info, count);
1141 	struct vfio_irq_info info;
1142 
1143 	if (copy_from_user(&info, arg, minsz))
1144 		return -EFAULT;
1145 
1146 	if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
1147 		return -EINVAL;
1148 
1149 	switch (info.index) {
1150 	case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
1151 	case VFIO_PCI_REQ_IRQ_INDEX:
1152 		break;
1153 	case VFIO_PCI_ERR_IRQ_INDEX:
1154 		if (pci_is_pcie(vdev->pdev))
1155 			break;
1156 		fallthrough;
1157 	default:
1158 		return -EINVAL;
1159 	}
1160 
1161 	info.flags = VFIO_IRQ_INFO_EVENTFD;
1162 
1163 	info.count = vfio_pci_get_irq_count(vdev, info.index);
1164 
1165 	if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
1166 		info.flags |=
1167 			(VFIO_IRQ_INFO_MASKABLE | VFIO_IRQ_INFO_AUTOMASKED);
1168 	else if (info.index != VFIO_PCI_MSIX_IRQ_INDEX || !vdev->has_dyn_msix)
1169 		info.flags |= VFIO_IRQ_INFO_NORESIZE;
1170 
1171 	return copy_to_user(arg, &info, minsz) ? -EFAULT : 0;
1172 }
1173 
1174 static int vfio_pci_ioctl_set_irqs(struct vfio_pci_core_device *vdev,
1175 				   struct vfio_irq_set __user *arg)
1176 {
1177 	unsigned long minsz = offsetofend(struct vfio_irq_set, count);
1178 	struct vfio_irq_set hdr;
1179 	u8 *data = NULL;
1180 	int max, ret = 0;
1181 	size_t data_size = 0;
1182 
1183 	if (copy_from_user(&hdr, arg, minsz))
1184 		return -EFAULT;
1185 
1186 	max = vfio_pci_get_irq_count(vdev, hdr.index);
1187 
1188 	ret = vfio_set_irqs_validate_and_prepare(&hdr, max, VFIO_PCI_NUM_IRQS,
1189 						 &data_size);
1190 	if (ret)
1191 		return ret;
1192 
1193 	if (data_size) {
1194 		data = memdup_user(&arg->data, data_size);
1195 		if (IS_ERR(data))
1196 			return PTR_ERR(data);
1197 	}
1198 
1199 	mutex_lock(&vdev->igate);
1200 
1201 	ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index, hdr.start,
1202 				      hdr.count, data);
1203 
1204 	mutex_unlock(&vdev->igate);
1205 	kfree(data);
1206 
1207 	return ret;
1208 }
1209 
1210 static int vfio_pci_ioctl_reset(struct vfio_pci_core_device *vdev,
1211 				void __user *arg)
1212 {
1213 	int ret;
1214 
1215 	if (!vdev->reset_works)
1216 		return -EINVAL;
1217 
1218 	vfio_pci_zap_and_down_write_memory_lock(vdev);
1219 
1220 	/*
1221 	 * This function can be invoked while the power state is non-D0. If
1222 	 * pci_try_reset_function() has been called while the power state is
1223 	 * non-D0, then pci_try_reset_function() will internally set the power
1224 	 * state to D0 without vfio driver involvement. For the devices which
1225 	 * have NoSoftRst-, the reset function can cause the PCI config space
1226 	 * reset without restoring the original state (saved locally in
1227 	 * 'vdev->pm_save').
1228 	 */
1229 	vfio_pci_set_power_state(vdev, PCI_D0);
1230 
1231 	ret = pci_try_reset_function(vdev->pdev);
1232 	up_write(&vdev->memory_lock);
1233 
1234 	return ret;
1235 }
1236 
1237 static int vfio_pci_ioctl_get_pci_hot_reset_info(
1238 	struct vfio_pci_core_device *vdev,
1239 	struct vfio_pci_hot_reset_info __user *arg)
1240 {
1241 	unsigned long minsz =
1242 		offsetofend(struct vfio_pci_hot_reset_info, count);
1243 	struct vfio_pci_dependent_device *devices = NULL;
1244 	struct vfio_pci_hot_reset_info hdr;
1245 	struct vfio_pci_fill_info fill = {};
1246 	bool slot = false;
1247 	int ret, count = 0;
1248 
1249 	if (copy_from_user(&hdr, arg, minsz))
1250 		return -EFAULT;
1251 
1252 	if (hdr.argsz < minsz)
1253 		return -EINVAL;
1254 
1255 	hdr.flags = 0;
1256 
1257 	/* Can we do a slot or bus reset or neither? */
1258 	if (!pci_probe_reset_slot(vdev->pdev->slot))
1259 		slot = true;
1260 	else if (pci_probe_reset_bus(vdev->pdev->bus))
1261 		return -ENODEV;
1262 
1263 	ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
1264 					    &count, slot);
1265 	if (ret)
1266 		return ret;
1267 
1268 	if (WARN_ON(!count)) /* Should always be at least one */
1269 		return -ERANGE;
1270 
1271 	if (count > (hdr.argsz - sizeof(hdr)) / sizeof(*devices)) {
1272 		hdr.count = count;
1273 		ret = -ENOSPC;
1274 		goto header;
1275 	}
1276 
1277 	devices = kcalloc(count, sizeof(*devices), GFP_KERNEL);
1278 	if (!devices)
1279 		return -ENOMEM;
1280 
1281 	fill.devices = devices;
1282 	fill.nr_devices = count;
1283 	fill.vdev = &vdev->vdev;
1284 
1285 	if (vfio_device_cdev_opened(&vdev->vdev))
1286 		fill.flags |= VFIO_PCI_HOT_RESET_FLAG_DEV_ID |
1287 			     VFIO_PCI_HOT_RESET_FLAG_DEV_ID_OWNED;
1288 
1289 	mutex_lock(&vdev->vdev.dev_set->lock);
1290 	ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_fill_devs,
1291 					    &fill, slot);
1292 	mutex_unlock(&vdev->vdev.dev_set->lock);
1293 	if (ret)
1294 		goto out;
1295 
1296 	if (copy_to_user(arg->devices, devices,
1297 			 sizeof(*devices) * fill.count)) {
1298 		ret = -EFAULT;
1299 		goto out;
1300 	}
1301 
1302 	hdr.count = fill.count;
1303 	hdr.flags = fill.flags;
1304 
1305 header:
1306 	if (copy_to_user(arg, &hdr, minsz))
1307 		ret = -EFAULT;
1308 out:
1309 	kfree(devices);
1310 	return ret;
1311 }
1312 
1313 static int
1314 vfio_pci_ioctl_pci_hot_reset_groups(struct vfio_pci_core_device *vdev,
1315 				    u32 array_count, bool slot,
1316 				    struct vfio_pci_hot_reset __user *arg)
1317 {
1318 	int32_t *group_fds;
1319 	struct file **files;
1320 	struct vfio_pci_group_info info;
1321 	int file_idx, count = 0, ret = 0;
1322 
1323 	/*
1324 	 * We can't let userspace give us an arbitrarily large buffer to copy,
1325 	 * so verify how many we think there could be.  Note groups can have
1326 	 * multiple devices so one group per device is the max.
1327 	 */
1328 	ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
1329 					    &count, slot);
1330 	if (ret)
1331 		return ret;
1332 
1333 	if (array_count > count)
1334 		return -EINVAL;
1335 
1336 	group_fds = kcalloc(array_count, sizeof(*group_fds), GFP_KERNEL);
1337 	files = kcalloc(array_count, sizeof(*files), GFP_KERNEL);
1338 	if (!group_fds || !files) {
1339 		kfree(group_fds);
1340 		kfree(files);
1341 		return -ENOMEM;
1342 	}
1343 
1344 	if (copy_from_user(group_fds, arg->group_fds,
1345 			   array_count * sizeof(*group_fds))) {
1346 		kfree(group_fds);
1347 		kfree(files);
1348 		return -EFAULT;
1349 	}
1350 
1351 	/*
1352 	 * Get the group file for each fd to ensure the group is held across
1353 	 * the reset
1354 	 */
1355 	for (file_idx = 0; file_idx < array_count; file_idx++) {
1356 		struct file *file = fget(group_fds[file_idx]);
1357 
1358 		if (!file) {
1359 			ret = -EBADF;
1360 			break;
1361 		}
1362 
1363 		/* Ensure the FD is a vfio group FD.*/
1364 		if (!vfio_file_is_group(file)) {
1365 			fput(file);
1366 			ret = -EINVAL;
1367 			break;
1368 		}
1369 
1370 		files[file_idx] = file;
1371 	}
1372 
1373 	kfree(group_fds);
1374 
1375 	/* release reference to groups on error */
1376 	if (ret)
1377 		goto hot_reset_release;
1378 
1379 	info.count = array_count;
1380 	info.files = files;
1381 
1382 	ret = vfio_pci_dev_set_hot_reset(vdev->vdev.dev_set, &info, NULL);
1383 
1384 hot_reset_release:
1385 	for (file_idx--; file_idx >= 0; file_idx--)
1386 		fput(files[file_idx]);
1387 
1388 	kfree(files);
1389 	return ret;
1390 }
1391 
1392 static int vfio_pci_ioctl_pci_hot_reset(struct vfio_pci_core_device *vdev,
1393 					struct vfio_pci_hot_reset __user *arg)
1394 {
1395 	unsigned long minsz = offsetofend(struct vfio_pci_hot_reset, count);
1396 	struct vfio_pci_hot_reset hdr;
1397 	bool slot = false;
1398 
1399 	if (copy_from_user(&hdr, arg, minsz))
1400 		return -EFAULT;
1401 
1402 	if (hdr.argsz < minsz || hdr.flags)
1403 		return -EINVAL;
1404 
1405 	/* zero-length array is only for cdev opened devices */
1406 	if (!!hdr.count == vfio_device_cdev_opened(&vdev->vdev))
1407 		return -EINVAL;
1408 
1409 	/* Can we do a slot or bus reset or neither? */
1410 	if (!pci_probe_reset_slot(vdev->pdev->slot))
1411 		slot = true;
1412 	else if (pci_probe_reset_bus(vdev->pdev->bus))
1413 		return -ENODEV;
1414 
1415 	if (hdr.count)
1416 		return vfio_pci_ioctl_pci_hot_reset_groups(vdev, hdr.count, slot, arg);
1417 
1418 	return vfio_pci_dev_set_hot_reset(vdev->vdev.dev_set, NULL,
1419 					  vfio_iommufd_device_ictx(&vdev->vdev));
1420 }
1421 
1422 static int vfio_pci_ioctl_ioeventfd(struct vfio_pci_core_device *vdev,
1423 				    struct vfio_device_ioeventfd __user *arg)
1424 {
1425 	unsigned long minsz = offsetofend(struct vfio_device_ioeventfd, fd);
1426 	struct vfio_device_ioeventfd ioeventfd;
1427 	int count;
1428 
1429 	if (copy_from_user(&ioeventfd, arg, minsz))
1430 		return -EFAULT;
1431 
1432 	if (ioeventfd.argsz < minsz)
1433 		return -EINVAL;
1434 
1435 	if (ioeventfd.flags & ~VFIO_DEVICE_IOEVENTFD_SIZE_MASK)
1436 		return -EINVAL;
1437 
1438 	count = ioeventfd.flags & VFIO_DEVICE_IOEVENTFD_SIZE_MASK;
1439 
1440 	if (hweight8(count) != 1 || ioeventfd.fd < -1)
1441 		return -EINVAL;
1442 
1443 	return vfio_pci_ioeventfd(vdev, ioeventfd.offset, ioeventfd.data, count,
1444 				  ioeventfd.fd);
1445 }
1446 
1447 long vfio_pci_core_ioctl(struct vfio_device *core_vdev, unsigned int cmd,
1448 			 unsigned long arg)
1449 {
1450 	struct vfio_pci_core_device *vdev =
1451 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1452 	void __user *uarg = (void __user *)arg;
1453 
1454 	switch (cmd) {
1455 	case VFIO_DEVICE_GET_INFO:
1456 		return vfio_pci_ioctl_get_info(vdev, uarg);
1457 	case VFIO_DEVICE_GET_IRQ_INFO:
1458 		return vfio_pci_ioctl_get_irq_info(vdev, uarg);
1459 	case VFIO_DEVICE_GET_PCI_HOT_RESET_INFO:
1460 		return vfio_pci_ioctl_get_pci_hot_reset_info(vdev, uarg);
1461 	case VFIO_DEVICE_GET_REGION_INFO:
1462 		return vfio_pci_ioctl_get_region_info(vdev, uarg);
1463 	case VFIO_DEVICE_IOEVENTFD:
1464 		return vfio_pci_ioctl_ioeventfd(vdev, uarg);
1465 	case VFIO_DEVICE_PCI_HOT_RESET:
1466 		return vfio_pci_ioctl_pci_hot_reset(vdev, uarg);
1467 	case VFIO_DEVICE_RESET:
1468 		return vfio_pci_ioctl_reset(vdev, uarg);
1469 	case VFIO_DEVICE_SET_IRQS:
1470 		return vfio_pci_ioctl_set_irqs(vdev, uarg);
1471 	default:
1472 		return -ENOTTY;
1473 	}
1474 }
1475 EXPORT_SYMBOL_GPL(vfio_pci_core_ioctl);
1476 
1477 static int vfio_pci_core_feature_token(struct vfio_device *device, u32 flags,
1478 				       uuid_t __user *arg, size_t argsz)
1479 {
1480 	struct vfio_pci_core_device *vdev =
1481 		container_of(device, struct vfio_pci_core_device, vdev);
1482 	uuid_t uuid;
1483 	int ret;
1484 
1485 	if (!vdev->vf_token)
1486 		return -ENOTTY;
1487 	/*
1488 	 * We do not support GET of the VF Token UUID as this could
1489 	 * expose the token of the previous device user.
1490 	 */
1491 	ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_SET,
1492 				 sizeof(uuid));
1493 	if (ret != 1)
1494 		return ret;
1495 
1496 	if (copy_from_user(&uuid, arg, sizeof(uuid)))
1497 		return -EFAULT;
1498 
1499 	mutex_lock(&vdev->vf_token->lock);
1500 	uuid_copy(&vdev->vf_token->uuid, &uuid);
1501 	mutex_unlock(&vdev->vf_token->lock);
1502 	return 0;
1503 }
1504 
1505 int vfio_pci_core_ioctl_feature(struct vfio_device *device, u32 flags,
1506 				void __user *arg, size_t argsz)
1507 {
1508 	switch (flags & VFIO_DEVICE_FEATURE_MASK) {
1509 	case VFIO_DEVICE_FEATURE_LOW_POWER_ENTRY:
1510 		return vfio_pci_core_pm_entry(device, flags, arg, argsz);
1511 	case VFIO_DEVICE_FEATURE_LOW_POWER_ENTRY_WITH_WAKEUP:
1512 		return vfio_pci_core_pm_entry_with_wakeup(device, flags,
1513 							  arg, argsz);
1514 	case VFIO_DEVICE_FEATURE_LOW_POWER_EXIT:
1515 		return vfio_pci_core_pm_exit(device, flags, arg, argsz);
1516 	case VFIO_DEVICE_FEATURE_PCI_VF_TOKEN:
1517 		return vfio_pci_core_feature_token(device, flags, arg, argsz);
1518 	default:
1519 		return -ENOTTY;
1520 	}
1521 }
1522 EXPORT_SYMBOL_GPL(vfio_pci_core_ioctl_feature);
1523 
1524 static ssize_t vfio_pci_rw(struct vfio_pci_core_device *vdev, char __user *buf,
1525 			   size_t count, loff_t *ppos, bool iswrite)
1526 {
1527 	unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
1528 	int ret;
1529 
1530 	if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1531 		return -EINVAL;
1532 
1533 	ret = pm_runtime_resume_and_get(&vdev->pdev->dev);
1534 	if (ret) {
1535 		pci_info_ratelimited(vdev->pdev, "runtime resume failed %d\n",
1536 				     ret);
1537 		return -EIO;
1538 	}
1539 
1540 	switch (index) {
1541 	case VFIO_PCI_CONFIG_REGION_INDEX:
1542 		ret = vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
1543 		break;
1544 
1545 	case VFIO_PCI_ROM_REGION_INDEX:
1546 		if (iswrite)
1547 			ret = -EINVAL;
1548 		else
1549 			ret = vfio_pci_bar_rw(vdev, buf, count, ppos, false);
1550 		break;
1551 
1552 	case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
1553 		ret = vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
1554 		break;
1555 
1556 	case VFIO_PCI_VGA_REGION_INDEX:
1557 		ret = vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
1558 		break;
1559 
1560 	default:
1561 		index -= VFIO_PCI_NUM_REGIONS;
1562 		ret = vdev->region[index].ops->rw(vdev, buf,
1563 						   count, ppos, iswrite);
1564 		break;
1565 	}
1566 
1567 	pm_runtime_put(&vdev->pdev->dev);
1568 	return ret;
1569 }
1570 
1571 ssize_t vfio_pci_core_read(struct vfio_device *core_vdev, char __user *buf,
1572 		size_t count, loff_t *ppos)
1573 {
1574 	struct vfio_pci_core_device *vdev =
1575 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1576 
1577 	if (!count)
1578 		return 0;
1579 
1580 	return vfio_pci_rw(vdev, buf, count, ppos, false);
1581 }
1582 EXPORT_SYMBOL_GPL(vfio_pci_core_read);
1583 
1584 ssize_t vfio_pci_core_write(struct vfio_device *core_vdev, const char __user *buf,
1585 		size_t count, loff_t *ppos)
1586 {
1587 	struct vfio_pci_core_device *vdev =
1588 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1589 
1590 	if (!count)
1591 		return 0;
1592 
1593 	return vfio_pci_rw(vdev, (char __user *)buf, count, ppos, true);
1594 }
1595 EXPORT_SYMBOL_GPL(vfio_pci_core_write);
1596 
1597 static void vfio_pci_zap_bars(struct vfio_pci_core_device *vdev)
1598 {
1599 	struct vfio_device *core_vdev = &vdev->vdev;
1600 	loff_t start = VFIO_PCI_INDEX_TO_OFFSET(VFIO_PCI_BAR0_REGION_INDEX);
1601 	loff_t end = VFIO_PCI_INDEX_TO_OFFSET(VFIO_PCI_ROM_REGION_INDEX);
1602 	loff_t len = end - start;
1603 
1604 	unmap_mapping_range(core_vdev->inode->i_mapping, start, len, true);
1605 }
1606 
1607 void vfio_pci_zap_and_down_write_memory_lock(struct vfio_pci_core_device *vdev)
1608 {
1609 	down_write(&vdev->memory_lock);
1610 	vfio_pci_zap_bars(vdev);
1611 }
1612 
1613 u16 vfio_pci_memory_lock_and_enable(struct vfio_pci_core_device *vdev)
1614 {
1615 	u16 cmd;
1616 
1617 	down_write(&vdev->memory_lock);
1618 	pci_read_config_word(vdev->pdev, PCI_COMMAND, &cmd);
1619 	if (!(cmd & PCI_COMMAND_MEMORY))
1620 		pci_write_config_word(vdev->pdev, PCI_COMMAND,
1621 				      cmd | PCI_COMMAND_MEMORY);
1622 
1623 	return cmd;
1624 }
1625 
1626 void vfio_pci_memory_unlock_and_restore(struct vfio_pci_core_device *vdev, u16 cmd)
1627 {
1628 	pci_write_config_word(vdev->pdev, PCI_COMMAND, cmd);
1629 	up_write(&vdev->memory_lock);
1630 }
1631 
1632 static unsigned long vma_to_pfn(struct vm_area_struct *vma)
1633 {
1634 	struct vfio_pci_core_device *vdev = vma->vm_private_data;
1635 	int index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1636 	u64 pgoff;
1637 
1638 	pgoff = vma->vm_pgoff &
1639 		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1640 
1641 	return (pci_resource_start(vdev->pdev, index) >> PAGE_SHIFT) + pgoff;
1642 }
1643 
1644 static vm_fault_t vfio_pci_mmap_huge_fault(struct vm_fault *vmf,
1645 					   unsigned int order)
1646 {
1647 	struct vm_area_struct *vma = vmf->vma;
1648 	struct vfio_pci_core_device *vdev = vma->vm_private_data;
1649 	unsigned long addr = vmf->address & ~((PAGE_SIZE << order) - 1);
1650 	unsigned long pgoff = (addr - vma->vm_start) >> PAGE_SHIFT;
1651 	unsigned long pfn = vma_to_pfn(vma) + pgoff;
1652 	vm_fault_t ret = VM_FAULT_SIGBUS;
1653 
1654 	if (order && (addr < vma->vm_start ||
1655 		      addr + (PAGE_SIZE << order) > vma->vm_end ||
1656 		      pfn & ((1 << order) - 1))) {
1657 		ret = VM_FAULT_FALLBACK;
1658 		goto out;
1659 	}
1660 
1661 	down_read(&vdev->memory_lock);
1662 
1663 	if (vdev->pm_runtime_engaged || !__vfio_pci_memory_enabled(vdev))
1664 		goto out_unlock;
1665 
1666 	switch (order) {
1667 	case 0:
1668 		ret = vmf_insert_pfn(vma, vmf->address, pfn);
1669 		break;
1670 #ifdef CONFIG_ARCH_SUPPORTS_PMD_PFNMAP
1671 	case PMD_ORDER:
1672 		ret = vmf_insert_pfn_pmd(vmf,
1673 					 __pfn_to_pfn_t(pfn, PFN_DEV), false);
1674 		break;
1675 #endif
1676 #ifdef CONFIG_ARCH_SUPPORTS_PUD_PFNMAP
1677 	case PUD_ORDER:
1678 		ret = vmf_insert_pfn_pud(vmf,
1679 					 __pfn_to_pfn_t(pfn, PFN_DEV), false);
1680 		break;
1681 #endif
1682 	default:
1683 		ret = VM_FAULT_FALLBACK;
1684 	}
1685 
1686 out_unlock:
1687 	up_read(&vdev->memory_lock);
1688 out:
1689 	dev_dbg_ratelimited(&vdev->pdev->dev,
1690 			   "%s(,order = %d) BAR %ld page offset 0x%lx: 0x%x\n",
1691 			    __func__, order,
1692 			    vma->vm_pgoff >>
1693 				(VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT),
1694 			    pgoff, (unsigned int)ret);
1695 
1696 	return ret;
1697 }
1698 
1699 static vm_fault_t vfio_pci_mmap_page_fault(struct vm_fault *vmf)
1700 {
1701 	return vfio_pci_mmap_huge_fault(vmf, 0);
1702 }
1703 
1704 static const struct vm_operations_struct vfio_pci_mmap_ops = {
1705 	.fault = vfio_pci_mmap_page_fault,
1706 #ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
1707 	.huge_fault = vfio_pci_mmap_huge_fault,
1708 #endif
1709 };
1710 
1711 int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma)
1712 {
1713 	struct vfio_pci_core_device *vdev =
1714 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1715 	struct pci_dev *pdev = vdev->pdev;
1716 	unsigned int index;
1717 	u64 phys_len, req_len, pgoff, req_start;
1718 	int ret;
1719 
1720 	index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1721 
1722 	if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1723 		return -EINVAL;
1724 	if (vma->vm_end < vma->vm_start)
1725 		return -EINVAL;
1726 	if ((vma->vm_flags & VM_SHARED) == 0)
1727 		return -EINVAL;
1728 	if (index >= VFIO_PCI_NUM_REGIONS) {
1729 		int regnum = index - VFIO_PCI_NUM_REGIONS;
1730 		struct vfio_pci_region *region = vdev->region + regnum;
1731 
1732 		if (region->ops && region->ops->mmap &&
1733 		    (region->flags & VFIO_REGION_INFO_FLAG_MMAP))
1734 			return region->ops->mmap(vdev, region, vma);
1735 		return -EINVAL;
1736 	}
1737 	if (index >= VFIO_PCI_ROM_REGION_INDEX)
1738 		return -EINVAL;
1739 	if (!vdev->bar_mmap_supported[index])
1740 		return -EINVAL;
1741 
1742 	phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1743 	req_len = vma->vm_end - vma->vm_start;
1744 	pgoff = vma->vm_pgoff &
1745 		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1746 	req_start = pgoff << PAGE_SHIFT;
1747 
1748 	if (req_start + req_len > phys_len)
1749 		return -EINVAL;
1750 
1751 	/*
1752 	 * Even though we don't make use of the barmap for the mmap,
1753 	 * we need to request the region and the barmap tracks that.
1754 	 */
1755 	if (!vdev->barmap[index]) {
1756 		ret = pci_request_selected_regions(pdev,
1757 						   1 << index, "vfio-pci");
1758 		if (ret)
1759 			return ret;
1760 
1761 		vdev->barmap[index] = pci_iomap(pdev, index, 0);
1762 		if (!vdev->barmap[index]) {
1763 			pci_release_selected_regions(pdev, 1 << index);
1764 			return -ENOMEM;
1765 		}
1766 	}
1767 
1768 	vma->vm_private_data = vdev;
1769 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1770 	vma->vm_page_prot = pgprot_decrypted(vma->vm_page_prot);
1771 
1772 	/*
1773 	 * Set vm_flags now, they should not be changed in the fault handler.
1774 	 * We want the same flags and page protection (decrypted above) as
1775 	 * io_remap_pfn_range() would set.
1776 	 *
1777 	 * VM_ALLOW_ANY_UNCACHED: The VMA flag is implemented for ARM64,
1778 	 * allowing KVM stage 2 device mapping attributes to use Normal-NC
1779 	 * rather than DEVICE_nGnRE, which allows guest mappings
1780 	 * supporting write-combining attributes (WC). ARM does not
1781 	 * architecturally guarantee this is safe, and indeed some MMIO
1782 	 * regions like the GICv2 VCPU interface can trigger uncontained
1783 	 * faults if Normal-NC is used.
1784 	 *
1785 	 * To safely use VFIO in KVM the platform must guarantee full
1786 	 * safety in the guest where no action taken against a MMIO
1787 	 * mapping can trigger an uncontained failure. The assumption is
1788 	 * that most VFIO PCI platforms support this for both mapping types,
1789 	 * at least in common flows, based on some expectations of how
1790 	 * PCI IP is integrated. Hence VM_ALLOW_ANY_UNCACHED is set in
1791 	 * the VMA flags.
1792 	 */
1793 	vm_flags_set(vma, VM_ALLOW_ANY_UNCACHED | VM_IO | VM_PFNMAP |
1794 			VM_DONTEXPAND | VM_DONTDUMP);
1795 	vma->vm_ops = &vfio_pci_mmap_ops;
1796 
1797 	return 0;
1798 }
1799 EXPORT_SYMBOL_GPL(vfio_pci_core_mmap);
1800 
1801 void vfio_pci_core_request(struct vfio_device *core_vdev, unsigned int count)
1802 {
1803 	struct vfio_pci_core_device *vdev =
1804 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1805 	struct pci_dev *pdev = vdev->pdev;
1806 
1807 	mutex_lock(&vdev->igate);
1808 
1809 	if (vdev->req_trigger) {
1810 		if (!(count % 10))
1811 			pci_notice_ratelimited(pdev,
1812 				"Relaying device request to user (#%u)\n",
1813 				count);
1814 		eventfd_signal(vdev->req_trigger);
1815 	} else if (count == 0) {
1816 		pci_warn(pdev,
1817 			"No device request channel registered, blocked until released by user\n");
1818 	}
1819 
1820 	mutex_unlock(&vdev->igate);
1821 }
1822 EXPORT_SYMBOL_GPL(vfio_pci_core_request);
1823 
1824 static int vfio_pci_validate_vf_token(struct vfio_pci_core_device *vdev,
1825 				      bool vf_token, uuid_t *uuid)
1826 {
1827 	/*
1828 	 * There's always some degree of trust or collaboration between SR-IOV
1829 	 * PF and VFs, even if just that the PF hosts the SR-IOV capability and
1830 	 * can disrupt VFs with a reset, but often the PF has more explicit
1831 	 * access to deny service to the VF or access data passed through the
1832 	 * VF.  We therefore require an opt-in via a shared VF token (UUID) to
1833 	 * represent this trust.  This both prevents that a VF driver might
1834 	 * assume the PF driver is a trusted, in-kernel driver, and also that
1835 	 * a PF driver might be replaced with a rogue driver, unknown to in-use
1836 	 * VF drivers.
1837 	 *
1838 	 * Therefore when presented with a VF, if the PF is a vfio device and
1839 	 * it is bound to the vfio-pci driver, the user needs to provide a VF
1840 	 * token to access the device, in the form of appending a vf_token to
1841 	 * the device name, for example:
1842 	 *
1843 	 * "0000:04:10.0 vf_token=bd8d9d2b-5a5f-4f5a-a211-f591514ba1f3"
1844 	 *
1845 	 * When presented with a PF which has VFs in use, the user must also
1846 	 * provide the current VF token to prove collaboration with existing
1847 	 * VF users.  If VFs are not in use, the VF token provided for the PF
1848 	 * device will act to set the VF token.
1849 	 *
1850 	 * If the VF token is provided but unused, an error is generated.
1851 	 */
1852 	if (vdev->pdev->is_virtfn) {
1853 		struct vfio_pci_core_device *pf_vdev = vdev->sriov_pf_core_dev;
1854 		bool match;
1855 
1856 		if (!pf_vdev) {
1857 			if (!vf_token)
1858 				return 0; /* PF is not vfio-pci, no VF token */
1859 
1860 			pci_info_ratelimited(vdev->pdev,
1861 				"VF token incorrectly provided, PF not bound to vfio-pci\n");
1862 			return -EINVAL;
1863 		}
1864 
1865 		if (!vf_token) {
1866 			pci_info_ratelimited(vdev->pdev,
1867 				"VF token required to access device\n");
1868 			return -EACCES;
1869 		}
1870 
1871 		mutex_lock(&pf_vdev->vf_token->lock);
1872 		match = uuid_equal(uuid, &pf_vdev->vf_token->uuid);
1873 		mutex_unlock(&pf_vdev->vf_token->lock);
1874 
1875 		if (!match) {
1876 			pci_info_ratelimited(vdev->pdev,
1877 				"Incorrect VF token provided for device\n");
1878 			return -EACCES;
1879 		}
1880 	} else if (vdev->vf_token) {
1881 		mutex_lock(&vdev->vf_token->lock);
1882 		if (vdev->vf_token->users) {
1883 			if (!vf_token) {
1884 				mutex_unlock(&vdev->vf_token->lock);
1885 				pci_info_ratelimited(vdev->pdev,
1886 					"VF token required to access device\n");
1887 				return -EACCES;
1888 			}
1889 
1890 			if (!uuid_equal(uuid, &vdev->vf_token->uuid)) {
1891 				mutex_unlock(&vdev->vf_token->lock);
1892 				pci_info_ratelimited(vdev->pdev,
1893 					"Incorrect VF token provided for device\n");
1894 				return -EACCES;
1895 			}
1896 		} else if (vf_token) {
1897 			uuid_copy(&vdev->vf_token->uuid, uuid);
1898 		}
1899 
1900 		mutex_unlock(&vdev->vf_token->lock);
1901 	} else if (vf_token) {
1902 		pci_info_ratelimited(vdev->pdev,
1903 			"VF token incorrectly provided, not a PF or VF\n");
1904 		return -EINVAL;
1905 	}
1906 
1907 	return 0;
1908 }
1909 
1910 #define VF_TOKEN_ARG "vf_token="
1911 
1912 int vfio_pci_core_match(struct vfio_device *core_vdev, char *buf)
1913 {
1914 	struct vfio_pci_core_device *vdev =
1915 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1916 	bool vf_token = false;
1917 	uuid_t uuid;
1918 	int ret;
1919 
1920 	if (strncmp(pci_name(vdev->pdev), buf, strlen(pci_name(vdev->pdev))))
1921 		return 0; /* No match */
1922 
1923 	if (strlen(buf) > strlen(pci_name(vdev->pdev))) {
1924 		buf += strlen(pci_name(vdev->pdev));
1925 
1926 		if (*buf != ' ')
1927 			return 0; /* No match: non-whitespace after name */
1928 
1929 		while (*buf) {
1930 			if (*buf == ' ') {
1931 				buf++;
1932 				continue;
1933 			}
1934 
1935 			if (!vf_token && !strncmp(buf, VF_TOKEN_ARG,
1936 						  strlen(VF_TOKEN_ARG))) {
1937 				buf += strlen(VF_TOKEN_ARG);
1938 
1939 				if (strlen(buf) < UUID_STRING_LEN)
1940 					return -EINVAL;
1941 
1942 				ret = uuid_parse(buf, &uuid);
1943 				if (ret)
1944 					return ret;
1945 
1946 				vf_token = true;
1947 				buf += UUID_STRING_LEN;
1948 			} else {
1949 				/* Unknown/duplicate option */
1950 				return -EINVAL;
1951 			}
1952 		}
1953 	}
1954 
1955 	ret = vfio_pci_validate_vf_token(vdev, vf_token, &uuid);
1956 	if (ret)
1957 		return ret;
1958 
1959 	return 1; /* Match */
1960 }
1961 EXPORT_SYMBOL_GPL(vfio_pci_core_match);
1962 
1963 static int vfio_pci_bus_notifier(struct notifier_block *nb,
1964 				 unsigned long action, void *data)
1965 {
1966 	struct vfio_pci_core_device *vdev = container_of(nb,
1967 						    struct vfio_pci_core_device, nb);
1968 	struct device *dev = data;
1969 	struct pci_dev *pdev = to_pci_dev(dev);
1970 	struct pci_dev *physfn = pci_physfn(pdev);
1971 
1972 	if (action == BUS_NOTIFY_ADD_DEVICE &&
1973 	    pdev->is_virtfn && physfn == vdev->pdev) {
1974 		pci_info(vdev->pdev, "Captured SR-IOV VF %s driver_override\n",
1975 			 pci_name(pdev));
1976 		pdev->driver_override = kasprintf(GFP_KERNEL, "%s",
1977 						  vdev->vdev.ops->name);
1978 		WARN_ON(!pdev->driver_override);
1979 	} else if (action == BUS_NOTIFY_BOUND_DRIVER &&
1980 		   pdev->is_virtfn && physfn == vdev->pdev) {
1981 		struct pci_driver *drv = pci_dev_driver(pdev);
1982 
1983 		if (drv && drv != pci_dev_driver(vdev->pdev))
1984 			pci_warn(vdev->pdev,
1985 				 "VF %s bound to driver %s while PF bound to driver %s\n",
1986 				 pci_name(pdev), drv->name,
1987 				 pci_dev_driver(vdev->pdev)->name);
1988 	}
1989 
1990 	return 0;
1991 }
1992 
1993 static int vfio_pci_vf_init(struct vfio_pci_core_device *vdev)
1994 {
1995 	struct pci_dev *pdev = vdev->pdev;
1996 	struct vfio_pci_core_device *cur;
1997 	struct pci_dev *physfn;
1998 	int ret;
1999 
2000 	if (pdev->is_virtfn) {
2001 		/*
2002 		 * If this VF was created by our vfio_pci_core_sriov_configure()
2003 		 * then we can find the PF vfio_pci_core_device now, and due to
2004 		 * the locking in pci_disable_sriov() it cannot change until
2005 		 * this VF device driver is removed.
2006 		 */
2007 		physfn = pci_physfn(vdev->pdev);
2008 		mutex_lock(&vfio_pci_sriov_pfs_mutex);
2009 		list_for_each_entry(cur, &vfio_pci_sriov_pfs, sriov_pfs_item) {
2010 			if (cur->pdev == physfn) {
2011 				vdev->sriov_pf_core_dev = cur;
2012 				break;
2013 			}
2014 		}
2015 		mutex_unlock(&vfio_pci_sriov_pfs_mutex);
2016 		return 0;
2017 	}
2018 
2019 	/* Not a SRIOV PF */
2020 	if (!pdev->is_physfn)
2021 		return 0;
2022 
2023 	vdev->vf_token = kzalloc(sizeof(*vdev->vf_token), GFP_KERNEL);
2024 	if (!vdev->vf_token)
2025 		return -ENOMEM;
2026 
2027 	mutex_init(&vdev->vf_token->lock);
2028 	uuid_gen(&vdev->vf_token->uuid);
2029 
2030 	vdev->nb.notifier_call = vfio_pci_bus_notifier;
2031 	ret = bus_register_notifier(&pci_bus_type, &vdev->nb);
2032 	if (ret) {
2033 		kfree(vdev->vf_token);
2034 		return ret;
2035 	}
2036 	return 0;
2037 }
2038 
2039 static void vfio_pci_vf_uninit(struct vfio_pci_core_device *vdev)
2040 {
2041 	if (!vdev->vf_token)
2042 		return;
2043 
2044 	bus_unregister_notifier(&pci_bus_type, &vdev->nb);
2045 	WARN_ON(vdev->vf_token->users);
2046 	mutex_destroy(&vdev->vf_token->lock);
2047 	kfree(vdev->vf_token);
2048 }
2049 
2050 static int vfio_pci_vga_init(struct vfio_pci_core_device *vdev)
2051 {
2052 	struct pci_dev *pdev = vdev->pdev;
2053 	int ret;
2054 
2055 	if (!vfio_pci_is_vga(pdev))
2056 		return 0;
2057 
2058 	ret = aperture_remove_conflicting_pci_devices(pdev, vdev->vdev.ops->name);
2059 	if (ret)
2060 		return ret;
2061 
2062 	ret = vga_client_register(pdev, vfio_pci_set_decode);
2063 	if (ret)
2064 		return ret;
2065 	vga_set_legacy_decoding(pdev, vfio_pci_set_decode(pdev, false));
2066 	return 0;
2067 }
2068 
2069 static void vfio_pci_vga_uninit(struct vfio_pci_core_device *vdev)
2070 {
2071 	struct pci_dev *pdev = vdev->pdev;
2072 
2073 	if (!vfio_pci_is_vga(pdev))
2074 		return;
2075 	vga_client_unregister(pdev);
2076 	vga_set_legacy_decoding(pdev, VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
2077 					      VGA_RSRC_LEGACY_IO |
2078 					      VGA_RSRC_LEGACY_MEM);
2079 }
2080 
2081 int vfio_pci_core_init_dev(struct vfio_device *core_vdev)
2082 {
2083 	struct vfio_pci_core_device *vdev =
2084 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
2085 
2086 	vdev->pdev = to_pci_dev(core_vdev->dev);
2087 	vdev->irq_type = VFIO_PCI_NUM_IRQS;
2088 	mutex_init(&vdev->igate);
2089 	spin_lock_init(&vdev->irqlock);
2090 	mutex_init(&vdev->ioeventfds_lock);
2091 	INIT_LIST_HEAD(&vdev->dummy_resources_list);
2092 	INIT_LIST_HEAD(&vdev->ioeventfds_list);
2093 	INIT_LIST_HEAD(&vdev->sriov_pfs_item);
2094 	init_rwsem(&vdev->memory_lock);
2095 	xa_init(&vdev->ctx);
2096 
2097 	return 0;
2098 }
2099 EXPORT_SYMBOL_GPL(vfio_pci_core_init_dev);
2100 
2101 void vfio_pci_core_release_dev(struct vfio_device *core_vdev)
2102 {
2103 	struct vfio_pci_core_device *vdev =
2104 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
2105 
2106 	mutex_destroy(&vdev->igate);
2107 	mutex_destroy(&vdev->ioeventfds_lock);
2108 	kfree(vdev->region);
2109 	kfree(vdev->pm_save);
2110 }
2111 EXPORT_SYMBOL_GPL(vfio_pci_core_release_dev);
2112 
2113 int vfio_pci_core_register_device(struct vfio_pci_core_device *vdev)
2114 {
2115 	struct pci_dev *pdev = vdev->pdev;
2116 	struct device *dev = &pdev->dev;
2117 	int ret;
2118 
2119 	/* Drivers must set the vfio_pci_core_device to their drvdata */
2120 	if (WARN_ON(vdev != dev_get_drvdata(dev)))
2121 		return -EINVAL;
2122 
2123 	if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
2124 		return -EINVAL;
2125 
2126 	if (vdev->vdev.mig_ops) {
2127 		if (!(vdev->vdev.mig_ops->migration_get_state &&
2128 		      vdev->vdev.mig_ops->migration_set_state &&
2129 		      vdev->vdev.mig_ops->migration_get_data_size) ||
2130 		    !(vdev->vdev.migration_flags & VFIO_MIGRATION_STOP_COPY))
2131 			return -EINVAL;
2132 	}
2133 
2134 	if (vdev->vdev.log_ops && !(vdev->vdev.log_ops->log_start &&
2135 	    vdev->vdev.log_ops->log_stop &&
2136 	    vdev->vdev.log_ops->log_read_and_clear))
2137 		return -EINVAL;
2138 
2139 	/*
2140 	 * Prevent binding to PFs with VFs enabled, the VFs might be in use
2141 	 * by the host or other users.  We cannot capture the VFs if they
2142 	 * already exist, nor can we track VF users.  Disabling SR-IOV here
2143 	 * would initiate removing the VFs, which would unbind the driver,
2144 	 * which is prone to blocking if that VF is also in use by vfio-pci.
2145 	 * Just reject these PFs and let the user sort it out.
2146 	 */
2147 	if (pci_num_vf(pdev)) {
2148 		pci_warn(pdev, "Cannot bind to PF with SR-IOV enabled\n");
2149 		return -EBUSY;
2150 	}
2151 
2152 	if (pci_is_root_bus(pdev->bus)) {
2153 		ret = vfio_assign_device_set(&vdev->vdev, vdev);
2154 	} else if (!pci_probe_reset_slot(pdev->slot)) {
2155 		ret = vfio_assign_device_set(&vdev->vdev, pdev->slot);
2156 	} else {
2157 		/*
2158 		 * If there is no slot reset support for this device, the whole
2159 		 * bus needs to be grouped together to support bus-wide resets.
2160 		 */
2161 		ret = vfio_assign_device_set(&vdev->vdev, pdev->bus);
2162 	}
2163 
2164 	if (ret)
2165 		return ret;
2166 	ret = vfio_pci_vf_init(vdev);
2167 	if (ret)
2168 		return ret;
2169 	ret = vfio_pci_vga_init(vdev);
2170 	if (ret)
2171 		goto out_vf;
2172 
2173 	vfio_pci_probe_power_state(vdev);
2174 
2175 	/*
2176 	 * pci-core sets the device power state to an unknown value at
2177 	 * bootup and after being removed from a driver.  The only
2178 	 * transition it allows from this unknown state is to D0, which
2179 	 * typically happens when a driver calls pci_enable_device().
2180 	 * We're not ready to enable the device yet, but we do want to
2181 	 * be able to get to D3.  Therefore first do a D0 transition
2182 	 * before enabling runtime PM.
2183 	 */
2184 	vfio_pci_set_power_state(vdev, PCI_D0);
2185 
2186 	dev->driver->pm = &vfio_pci_core_pm_ops;
2187 	pm_runtime_allow(dev);
2188 	if (!disable_idle_d3)
2189 		pm_runtime_put(dev);
2190 
2191 	ret = vfio_register_group_dev(&vdev->vdev);
2192 	if (ret)
2193 		goto out_power;
2194 	return 0;
2195 
2196 out_power:
2197 	if (!disable_idle_d3)
2198 		pm_runtime_get_noresume(dev);
2199 
2200 	pm_runtime_forbid(dev);
2201 out_vf:
2202 	vfio_pci_vf_uninit(vdev);
2203 	return ret;
2204 }
2205 EXPORT_SYMBOL_GPL(vfio_pci_core_register_device);
2206 
2207 void vfio_pci_core_unregister_device(struct vfio_pci_core_device *vdev)
2208 {
2209 	vfio_pci_core_sriov_configure(vdev, 0);
2210 
2211 	vfio_unregister_group_dev(&vdev->vdev);
2212 
2213 	vfio_pci_vf_uninit(vdev);
2214 	vfio_pci_vga_uninit(vdev);
2215 
2216 	if (!disable_idle_d3)
2217 		pm_runtime_get_noresume(&vdev->pdev->dev);
2218 
2219 	pm_runtime_forbid(&vdev->pdev->dev);
2220 }
2221 EXPORT_SYMBOL_GPL(vfio_pci_core_unregister_device);
2222 
2223 pci_ers_result_t vfio_pci_core_aer_err_detected(struct pci_dev *pdev,
2224 						pci_channel_state_t state)
2225 {
2226 	struct vfio_pci_core_device *vdev = dev_get_drvdata(&pdev->dev);
2227 
2228 	mutex_lock(&vdev->igate);
2229 
2230 	if (vdev->err_trigger)
2231 		eventfd_signal(vdev->err_trigger);
2232 
2233 	mutex_unlock(&vdev->igate);
2234 
2235 	return PCI_ERS_RESULT_CAN_RECOVER;
2236 }
2237 EXPORT_SYMBOL_GPL(vfio_pci_core_aer_err_detected);
2238 
2239 int vfio_pci_core_sriov_configure(struct vfio_pci_core_device *vdev,
2240 				  int nr_virtfn)
2241 {
2242 	struct pci_dev *pdev = vdev->pdev;
2243 	int ret = 0;
2244 
2245 	device_lock_assert(&pdev->dev);
2246 
2247 	if (nr_virtfn) {
2248 		mutex_lock(&vfio_pci_sriov_pfs_mutex);
2249 		/*
2250 		 * The thread that adds the vdev to the list is the only thread
2251 		 * that gets to call pci_enable_sriov() and we will only allow
2252 		 * it to be called once without going through
2253 		 * pci_disable_sriov()
2254 		 */
2255 		if (!list_empty(&vdev->sriov_pfs_item)) {
2256 			ret = -EINVAL;
2257 			goto out_unlock;
2258 		}
2259 		list_add_tail(&vdev->sriov_pfs_item, &vfio_pci_sriov_pfs);
2260 		mutex_unlock(&vfio_pci_sriov_pfs_mutex);
2261 
2262 		/*
2263 		 * The PF power state should always be higher than the VF power
2264 		 * state. The PF can be in low power state either with runtime
2265 		 * power management (when there is no user) or PCI_PM_CTRL
2266 		 * register write by the user. If PF is in the low power state,
2267 		 * then change the power state to D0 first before enabling
2268 		 * SR-IOV. Also, this function can be called at any time, and
2269 		 * userspace PCI_PM_CTRL write can race against this code path,
2270 		 * so protect the same with 'memory_lock'.
2271 		 */
2272 		ret = pm_runtime_resume_and_get(&pdev->dev);
2273 		if (ret)
2274 			goto out_del;
2275 
2276 		down_write(&vdev->memory_lock);
2277 		vfio_pci_set_power_state(vdev, PCI_D0);
2278 		ret = pci_enable_sriov(pdev, nr_virtfn);
2279 		up_write(&vdev->memory_lock);
2280 		if (ret) {
2281 			pm_runtime_put(&pdev->dev);
2282 			goto out_del;
2283 		}
2284 		return nr_virtfn;
2285 	}
2286 
2287 	if (pci_num_vf(pdev)) {
2288 		pci_disable_sriov(pdev);
2289 		pm_runtime_put(&pdev->dev);
2290 	}
2291 
2292 out_del:
2293 	mutex_lock(&vfio_pci_sriov_pfs_mutex);
2294 	list_del_init(&vdev->sriov_pfs_item);
2295 out_unlock:
2296 	mutex_unlock(&vfio_pci_sriov_pfs_mutex);
2297 	return ret;
2298 }
2299 EXPORT_SYMBOL_GPL(vfio_pci_core_sriov_configure);
2300 
2301 const struct pci_error_handlers vfio_pci_core_err_handlers = {
2302 	.error_detected = vfio_pci_core_aer_err_detected,
2303 };
2304 EXPORT_SYMBOL_GPL(vfio_pci_core_err_handlers);
2305 
2306 static bool vfio_dev_in_groups(struct vfio_device *vdev,
2307 			       struct vfio_pci_group_info *groups)
2308 {
2309 	unsigned int i;
2310 
2311 	if (!groups)
2312 		return false;
2313 
2314 	for (i = 0; i < groups->count; i++)
2315 		if (vfio_file_has_dev(groups->files[i], vdev))
2316 			return true;
2317 	return false;
2318 }
2319 
2320 static int vfio_pci_is_device_in_set(struct pci_dev *pdev, void *data)
2321 {
2322 	struct vfio_device_set *dev_set = data;
2323 
2324 	return vfio_find_device_in_devset(dev_set, &pdev->dev) ? 0 : -ENODEV;
2325 }
2326 
2327 /*
2328  * vfio-core considers a group to be viable and will create a vfio_device even
2329  * if some devices are bound to drivers like pci-stub or pcieport. Here we
2330  * require all PCI devices to be inside our dev_set since that ensures they stay
2331  * put and that every driver controlling the device can co-ordinate with the
2332  * device reset.
2333  *
2334  * Returns the pci_dev to pass to pci_reset_bus() if every PCI device to be
2335  * reset is inside the dev_set, and pci_reset_bus() can succeed. NULL otherwise.
2336  */
2337 static struct pci_dev *
2338 vfio_pci_dev_set_resettable(struct vfio_device_set *dev_set)
2339 {
2340 	struct pci_dev *pdev;
2341 
2342 	lockdep_assert_held(&dev_set->lock);
2343 
2344 	/*
2345 	 * By definition all PCI devices in the dev_set share the same PCI
2346 	 * reset, so any pci_dev will have the same outcomes for
2347 	 * pci_probe_reset_*() and pci_reset_bus().
2348 	 */
2349 	pdev = list_first_entry(&dev_set->device_list,
2350 				struct vfio_pci_core_device,
2351 				vdev.dev_set_list)->pdev;
2352 
2353 	/* pci_reset_bus() is supported */
2354 	if (pci_probe_reset_slot(pdev->slot) && pci_probe_reset_bus(pdev->bus))
2355 		return NULL;
2356 
2357 	if (vfio_pci_for_each_slot_or_bus(pdev, vfio_pci_is_device_in_set,
2358 					  dev_set,
2359 					  !pci_probe_reset_slot(pdev->slot)))
2360 		return NULL;
2361 	return pdev;
2362 }
2363 
2364 static int vfio_pci_dev_set_pm_runtime_get(struct vfio_device_set *dev_set)
2365 {
2366 	struct vfio_pci_core_device *cur;
2367 	int ret;
2368 
2369 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2370 		ret = pm_runtime_resume_and_get(&cur->pdev->dev);
2371 		if (ret)
2372 			goto unwind;
2373 	}
2374 
2375 	return 0;
2376 
2377 unwind:
2378 	list_for_each_entry_continue_reverse(cur, &dev_set->device_list,
2379 					     vdev.dev_set_list)
2380 		pm_runtime_put(&cur->pdev->dev);
2381 
2382 	return ret;
2383 }
2384 
2385 static int vfio_pci_dev_set_hot_reset(struct vfio_device_set *dev_set,
2386 				      struct vfio_pci_group_info *groups,
2387 				      struct iommufd_ctx *iommufd_ctx)
2388 {
2389 	struct vfio_pci_core_device *vdev;
2390 	struct pci_dev *pdev;
2391 	int ret;
2392 
2393 	mutex_lock(&dev_set->lock);
2394 
2395 	pdev = vfio_pci_dev_set_resettable(dev_set);
2396 	if (!pdev) {
2397 		ret = -EINVAL;
2398 		goto err_unlock;
2399 	}
2400 
2401 	/*
2402 	 * Some of the devices in the dev_set can be in the runtime suspended
2403 	 * state. Increment the usage count for all the devices in the dev_set
2404 	 * before reset and decrement the same after reset.
2405 	 */
2406 	ret = vfio_pci_dev_set_pm_runtime_get(dev_set);
2407 	if (ret)
2408 		goto err_unlock;
2409 
2410 	list_for_each_entry(vdev, &dev_set->device_list, vdev.dev_set_list) {
2411 		bool owned;
2412 
2413 		/*
2414 		 * Test whether all the affected devices can be reset by the
2415 		 * user.
2416 		 *
2417 		 * If called from a group opened device and the user provides
2418 		 * a set of groups, all the devices in the dev_set should be
2419 		 * contained by the set of groups provided by the user.
2420 		 *
2421 		 * If called from a cdev opened device and the user provides
2422 		 * a zero-length array, all the devices in the dev_set must
2423 		 * be bound to the same iommufd_ctx as the input iommufd_ctx.
2424 		 * If there is any device that has not been bound to any
2425 		 * iommufd_ctx yet, check if its iommu_group has any device
2426 		 * bound to the input iommufd_ctx.  Such devices can be
2427 		 * considered owned by the input iommufd_ctx as the device
2428 		 * cannot be owned by another iommufd_ctx when its iommu_group
2429 		 * is owned.
2430 		 *
2431 		 * Otherwise, reset is not allowed.
2432 		 */
2433 		if (iommufd_ctx) {
2434 			int devid = vfio_iommufd_get_dev_id(&vdev->vdev,
2435 							    iommufd_ctx);
2436 
2437 			owned = (devid > 0 || devid == -ENOENT);
2438 		} else {
2439 			owned = vfio_dev_in_groups(&vdev->vdev, groups);
2440 		}
2441 
2442 		if (!owned) {
2443 			ret = -EINVAL;
2444 			break;
2445 		}
2446 
2447 		/*
2448 		 * Take the memory write lock for each device and zap BAR
2449 		 * mappings to prevent the user accessing the device while in
2450 		 * reset.  Locking multiple devices is prone to deadlock,
2451 		 * runaway and unwind if we hit contention.
2452 		 */
2453 		if (!down_write_trylock(&vdev->memory_lock)) {
2454 			ret = -EBUSY;
2455 			break;
2456 		}
2457 
2458 		vfio_pci_zap_bars(vdev);
2459 	}
2460 
2461 	if (!list_entry_is_head(vdev,
2462 				&dev_set->device_list, vdev.dev_set_list)) {
2463 		vdev = list_prev_entry(vdev, vdev.dev_set_list);
2464 		goto err_undo;
2465 	}
2466 
2467 	/*
2468 	 * The pci_reset_bus() will reset all the devices in the bus.
2469 	 * The power state can be non-D0 for some of the devices in the bus.
2470 	 * For these devices, the pci_reset_bus() will internally set
2471 	 * the power state to D0 without vfio driver involvement.
2472 	 * For the devices which have NoSoftRst-, the reset function can
2473 	 * cause the PCI config space reset without restoring the original
2474 	 * state (saved locally in 'vdev->pm_save').
2475 	 */
2476 	list_for_each_entry(vdev, &dev_set->device_list, vdev.dev_set_list)
2477 		vfio_pci_set_power_state(vdev, PCI_D0);
2478 
2479 	ret = pci_reset_bus(pdev);
2480 
2481 	vdev = list_last_entry(&dev_set->device_list,
2482 			       struct vfio_pci_core_device, vdev.dev_set_list);
2483 
2484 err_undo:
2485 	list_for_each_entry_from_reverse(vdev, &dev_set->device_list,
2486 					 vdev.dev_set_list)
2487 		up_write(&vdev->memory_lock);
2488 
2489 	list_for_each_entry(vdev, &dev_set->device_list, vdev.dev_set_list)
2490 		pm_runtime_put(&vdev->pdev->dev);
2491 
2492 err_unlock:
2493 	mutex_unlock(&dev_set->lock);
2494 	return ret;
2495 }
2496 
2497 static bool vfio_pci_dev_set_needs_reset(struct vfio_device_set *dev_set)
2498 {
2499 	struct vfio_pci_core_device *cur;
2500 	bool needs_reset = false;
2501 
2502 	/* No other VFIO device in the set can be open. */
2503 	if (vfio_device_set_open_count(dev_set) > 1)
2504 		return false;
2505 
2506 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list)
2507 		needs_reset |= cur->needs_reset;
2508 	return needs_reset;
2509 }
2510 
2511 /*
2512  * If a bus or slot reset is available for the provided dev_set and:
2513  *  - All of the devices affected by that bus or slot reset are unused
2514  *  - At least one of the affected devices is marked dirty via
2515  *    needs_reset (such as by lack of FLR support)
2516  * Then attempt to perform that bus or slot reset.
2517  */
2518 static void vfio_pci_dev_set_try_reset(struct vfio_device_set *dev_set)
2519 {
2520 	struct vfio_pci_core_device *cur;
2521 	struct pci_dev *pdev;
2522 	bool reset_done = false;
2523 
2524 	if (!vfio_pci_dev_set_needs_reset(dev_set))
2525 		return;
2526 
2527 	pdev = vfio_pci_dev_set_resettable(dev_set);
2528 	if (!pdev)
2529 		return;
2530 
2531 	/*
2532 	 * Some of the devices in the bus can be in the runtime suspended
2533 	 * state. Increment the usage count for all the devices in the dev_set
2534 	 * before reset and decrement the same after reset.
2535 	 */
2536 	if (!disable_idle_d3 && vfio_pci_dev_set_pm_runtime_get(dev_set))
2537 		return;
2538 
2539 	if (!pci_reset_bus(pdev))
2540 		reset_done = true;
2541 
2542 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2543 		if (reset_done)
2544 			cur->needs_reset = false;
2545 
2546 		if (!disable_idle_d3)
2547 			pm_runtime_put(&cur->pdev->dev);
2548 	}
2549 }
2550 
2551 void vfio_pci_core_set_params(bool is_nointxmask, bool is_disable_vga,
2552 			      bool is_disable_idle_d3)
2553 {
2554 	nointxmask = is_nointxmask;
2555 	disable_vga = is_disable_vga;
2556 	disable_idle_d3 = is_disable_idle_d3;
2557 }
2558 EXPORT_SYMBOL_GPL(vfio_pci_core_set_params);
2559 
2560 static void vfio_pci_core_cleanup(void)
2561 {
2562 	vfio_pci_uninit_perm_bits();
2563 }
2564 
2565 static int __init vfio_pci_core_init(void)
2566 {
2567 	/* Allocate shared config space permission data used by all devices */
2568 	return vfio_pci_init_perm_bits();
2569 }
2570 
2571 module_init(vfio_pci_core_init);
2572 module_exit(vfio_pci_core_cleanup);
2573 
2574 MODULE_LICENSE("GPL v2");
2575 MODULE_AUTHOR(DRIVER_AUTHOR);
2576 MODULE_DESCRIPTION(DRIVER_DESC);
2577