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