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