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