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