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