xref: /linux/drivers/vfio/pci/vfio_pci.c (revision 9a6b55ac)
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 #define dev_fmt pr_fmt
13 
14 #include <linux/device.h>
15 #include <linux/eventfd.h>
16 #include <linux/file.h>
17 #include <linux/interrupt.h>
18 #include <linux/iommu.h>
19 #include <linux/module.h>
20 #include <linux/mutex.h>
21 #include <linux/notifier.h>
22 #include <linux/pci.h>
23 #include <linux/pm_runtime.h>
24 #include <linux/slab.h>
25 #include <linux/types.h>
26 #include <linux/uaccess.h>
27 #include <linux/vfio.h>
28 #include <linux/vgaarb.h>
29 #include <linux/nospec.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 inline bool vfio_vga_disabled(void)
58 {
59 #ifdef CONFIG_VFIO_PCI_VGA
60 	return disable_vga;
61 #else
62 	return true;
63 #endif
64 }
65 
66 /*
67  * Our VGA arbiter participation is limited since we don't know anything
68  * about the device itself.  However, if the device is the only VGA device
69  * downstream of a bridge and VFIO VGA support is disabled, then we can
70  * safely return legacy VGA IO and memory as not decoded since the user
71  * has no way to get to it and routing can be disabled externally at the
72  * bridge.
73  */
74 static unsigned int vfio_pci_set_vga_decode(void *opaque, bool single_vga)
75 {
76 	struct vfio_pci_device *vdev = opaque;
77 	struct pci_dev *tmp = NULL, *pdev = vdev->pdev;
78 	unsigned char max_busnr;
79 	unsigned int decodes;
80 
81 	if (single_vga || !vfio_vga_disabled() || pci_is_root_bus(pdev->bus))
82 		return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
83 		       VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
84 
85 	max_busnr = pci_bus_max_busnr(pdev->bus);
86 	decodes = VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
87 
88 	while ((tmp = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, tmp)) != NULL) {
89 		if (tmp == pdev ||
90 		    pci_domain_nr(tmp->bus) != pci_domain_nr(pdev->bus) ||
91 		    pci_is_root_bus(tmp->bus))
92 			continue;
93 
94 		if (tmp->bus->number >= pdev->bus->number &&
95 		    tmp->bus->number <= max_busnr) {
96 			pci_dev_put(tmp);
97 			decodes |= VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
98 			break;
99 		}
100 	}
101 
102 	return decodes;
103 }
104 
105 static inline bool vfio_pci_is_vga(struct pci_dev *pdev)
106 {
107 	return (pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA;
108 }
109 
110 static void vfio_pci_probe_mmaps(struct vfio_pci_device *vdev)
111 {
112 	struct resource *res;
113 	int i;
114 	struct vfio_pci_dummy_resource *dummy_res;
115 
116 	INIT_LIST_HEAD(&vdev->dummy_resources_list);
117 
118 	for (i = 0; i < PCI_STD_NUM_BARS; i++) {
119 		int bar = i + PCI_STD_RESOURCES;
120 
121 		res = &vdev->pdev->resource[bar];
122 
123 		if (!IS_ENABLED(CONFIG_VFIO_PCI_MMAP))
124 			goto no_mmap;
125 
126 		if (!(res->flags & IORESOURCE_MEM))
127 			goto no_mmap;
128 
129 		/*
130 		 * The PCI core shouldn't set up a resource with a
131 		 * type but zero size. But there may be bugs that
132 		 * cause us to do that.
133 		 */
134 		if (!resource_size(res))
135 			goto no_mmap;
136 
137 		if (resource_size(res) >= PAGE_SIZE) {
138 			vdev->bar_mmap_supported[bar] = true;
139 			continue;
140 		}
141 
142 		if (!(res->start & ~PAGE_MASK)) {
143 			/*
144 			 * Add a dummy resource to reserve the remainder
145 			 * of the exclusive page in case that hot-add
146 			 * device's bar is assigned into it.
147 			 */
148 			dummy_res = kzalloc(sizeof(*dummy_res), GFP_KERNEL);
149 			if (dummy_res == NULL)
150 				goto no_mmap;
151 
152 			dummy_res->resource.name = "vfio sub-page reserved";
153 			dummy_res->resource.start = res->end + 1;
154 			dummy_res->resource.end = res->start + PAGE_SIZE - 1;
155 			dummy_res->resource.flags = res->flags;
156 			if (request_resource(res->parent,
157 						&dummy_res->resource)) {
158 				kfree(dummy_res);
159 				goto no_mmap;
160 			}
161 			dummy_res->index = bar;
162 			list_add(&dummy_res->res_next,
163 					&vdev->dummy_resources_list);
164 			vdev->bar_mmap_supported[bar] = true;
165 			continue;
166 		}
167 		/*
168 		 * Here we don't handle the case when the BAR is not page
169 		 * aligned because we can't expect the BAR will be
170 		 * assigned into the same location in a page in guest
171 		 * when we passthrough the BAR. And it's hard to access
172 		 * this BAR in userspace because we have no way to get
173 		 * the BAR's location in a page.
174 		 */
175 no_mmap:
176 		vdev->bar_mmap_supported[bar] = false;
177 	}
178 }
179 
180 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev);
181 static void vfio_pci_disable(struct vfio_pci_device *vdev);
182 
183 /*
184  * INTx masking requires the ability to disable INTx signaling via PCI_COMMAND
185  * _and_ the ability detect when the device is asserting INTx via PCI_STATUS.
186  * If a device implements the former but not the latter we would typically
187  * expect broken_intx_masking be set and require an exclusive interrupt.
188  * However since we do have control of the device's ability to assert INTx,
189  * we can instead pretend that the device does not implement INTx, virtualizing
190  * the pin register to report zero and maintaining DisINTx set on the host.
191  */
192 static bool vfio_pci_nointx(struct pci_dev *pdev)
193 {
194 	switch (pdev->vendor) {
195 	case PCI_VENDOR_ID_INTEL:
196 		switch (pdev->device) {
197 		/* All i40e (XL710/X710/XXV710) 10/20/25/40GbE NICs */
198 		case 0x1572:
199 		case 0x1574:
200 		case 0x1580 ... 0x1581:
201 		case 0x1583 ... 0x158b:
202 		case 0x37d0 ... 0x37d2:
203 			return true;
204 		default:
205 			return false;
206 		}
207 	}
208 
209 	return false;
210 }
211 
212 static void vfio_pci_probe_power_state(struct vfio_pci_device *vdev)
213 {
214 	struct pci_dev *pdev = vdev->pdev;
215 	u16 pmcsr;
216 
217 	if (!pdev->pm_cap)
218 		return;
219 
220 	pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmcsr);
221 
222 	vdev->needs_pm_restore = !(pmcsr & PCI_PM_CTRL_NO_SOFT_RESET);
223 }
224 
225 /*
226  * pci_set_power_state() wrapper handling devices which perform a soft reset on
227  * D3->D0 transition.  Save state prior to D0/1/2->D3, stash it on the vdev,
228  * restore when returned to D0.  Saved separately from pci_saved_state for use
229  * by PM capability emulation and separately from pci_dev internal saved state
230  * to avoid it being overwritten and consumed around other resets.
231  */
232 int vfio_pci_set_power_state(struct vfio_pci_device *vdev, pci_power_t state)
233 {
234 	struct pci_dev *pdev = vdev->pdev;
235 	bool needs_restore = false, needs_save = false;
236 	int ret;
237 
238 	if (vdev->needs_pm_restore) {
239 		if (pdev->current_state < PCI_D3hot && state >= PCI_D3hot) {
240 			pci_save_state(pdev);
241 			needs_save = true;
242 		}
243 
244 		if (pdev->current_state >= PCI_D3hot && state <= PCI_D0)
245 			needs_restore = true;
246 	}
247 
248 	ret = pci_set_power_state(pdev, state);
249 
250 	if (!ret) {
251 		/* D3 might be unsupported via quirk, skip unless in D3 */
252 		if (needs_save && pdev->current_state >= PCI_D3hot) {
253 			vdev->pm_save = pci_store_saved_state(pdev);
254 		} else if (needs_restore) {
255 			pci_load_and_free_saved_state(pdev, &vdev->pm_save);
256 			pci_restore_state(pdev);
257 		}
258 	}
259 
260 	return ret;
261 }
262 
263 static int vfio_pci_enable(struct vfio_pci_device *vdev)
264 {
265 	struct pci_dev *pdev = vdev->pdev;
266 	int ret;
267 	u16 cmd;
268 	u8 msix_pos;
269 
270 	vfio_pci_set_power_state(vdev, PCI_D0);
271 
272 	/* Don't allow our initial saved state to include busmaster */
273 	pci_clear_master(pdev);
274 
275 	ret = pci_enable_device(pdev);
276 	if (ret)
277 		return ret;
278 
279 	/* If reset fails because of the device lock, fail this path entirely */
280 	ret = pci_try_reset_function(pdev);
281 	if (ret == -EAGAIN) {
282 		pci_disable_device(pdev);
283 		return ret;
284 	}
285 
286 	vdev->reset_works = !ret;
287 	pci_save_state(pdev);
288 	vdev->pci_saved_state = pci_store_saved_state(pdev);
289 	if (!vdev->pci_saved_state)
290 		pci_dbg(pdev, "%s: Couldn't store saved state\n", __func__);
291 
292 	if (likely(!nointxmask)) {
293 		if (vfio_pci_nointx(pdev)) {
294 			pci_info(pdev, "Masking broken INTx support\n");
295 			vdev->nointx = true;
296 			pci_intx(pdev, 0);
297 		} else
298 			vdev->pci_2_3 = pci_intx_mask_supported(pdev);
299 	}
300 
301 	pci_read_config_word(pdev, PCI_COMMAND, &cmd);
302 	if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
303 		cmd &= ~PCI_COMMAND_INTX_DISABLE;
304 		pci_write_config_word(pdev, PCI_COMMAND, cmd);
305 	}
306 
307 	ret = vfio_config_init(vdev);
308 	if (ret) {
309 		kfree(vdev->pci_saved_state);
310 		vdev->pci_saved_state = NULL;
311 		pci_disable_device(pdev);
312 		return ret;
313 	}
314 
315 	msix_pos = pdev->msix_cap;
316 	if (msix_pos) {
317 		u16 flags;
318 		u32 table;
319 
320 		pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
321 		pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
322 
323 		vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
324 		vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
325 		vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
326 	} else
327 		vdev->msix_bar = 0xFF;
328 
329 	if (!vfio_vga_disabled() && vfio_pci_is_vga(pdev))
330 		vdev->has_vga = true;
331 
332 
333 	if (vfio_pci_is_vga(pdev) &&
334 	    pdev->vendor == PCI_VENDOR_ID_INTEL &&
335 	    IS_ENABLED(CONFIG_VFIO_PCI_IGD)) {
336 		ret = vfio_pci_igd_init(vdev);
337 		if (ret) {
338 			pci_warn(pdev, "Failed to setup Intel IGD regions\n");
339 			goto disable_exit;
340 		}
341 	}
342 
343 	if (pdev->vendor == PCI_VENDOR_ID_NVIDIA &&
344 	    IS_ENABLED(CONFIG_VFIO_PCI_NVLINK2)) {
345 		ret = vfio_pci_nvdia_v100_nvlink2_init(vdev);
346 		if (ret && ret != -ENODEV) {
347 			pci_warn(pdev, "Failed to setup NVIDIA NV2 RAM region\n");
348 			goto disable_exit;
349 		}
350 	}
351 
352 	if (pdev->vendor == PCI_VENDOR_ID_IBM &&
353 	    IS_ENABLED(CONFIG_VFIO_PCI_NVLINK2)) {
354 		ret = vfio_pci_ibm_npu2_init(vdev);
355 		if (ret && ret != -ENODEV) {
356 			pci_warn(pdev, "Failed to setup NVIDIA NV2 ATSD region\n");
357 			goto disable_exit;
358 		}
359 	}
360 
361 	vfio_pci_probe_mmaps(vdev);
362 
363 	return 0;
364 
365 disable_exit:
366 	vfio_pci_disable(vdev);
367 	return ret;
368 }
369 
370 static void vfio_pci_disable(struct vfio_pci_device *vdev)
371 {
372 	struct pci_dev *pdev = vdev->pdev;
373 	struct vfio_pci_dummy_resource *dummy_res, *tmp;
374 	struct vfio_pci_ioeventfd *ioeventfd, *ioeventfd_tmp;
375 	int i, bar;
376 
377 	/* Stop the device from further DMA */
378 	pci_clear_master(pdev);
379 
380 	vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
381 				VFIO_IRQ_SET_ACTION_TRIGGER,
382 				vdev->irq_type, 0, 0, NULL);
383 
384 	/* Device closed, don't need mutex here */
385 	list_for_each_entry_safe(ioeventfd, ioeventfd_tmp,
386 				 &vdev->ioeventfds_list, next) {
387 		vfio_virqfd_disable(&ioeventfd->virqfd);
388 		list_del(&ioeventfd->next);
389 		kfree(ioeventfd);
390 	}
391 	vdev->ioeventfds_nr = 0;
392 
393 	vdev->virq_disabled = false;
394 
395 	for (i = 0; i < vdev->num_regions; i++)
396 		vdev->region[i].ops->release(vdev, &vdev->region[i]);
397 
398 	vdev->num_regions = 0;
399 	kfree(vdev->region);
400 	vdev->region = NULL; /* don't krealloc a freed pointer */
401 
402 	vfio_config_free(vdev);
403 
404 	for (i = 0; i < PCI_STD_NUM_BARS; i++) {
405 		bar = i + PCI_STD_RESOURCES;
406 		if (!vdev->barmap[bar])
407 			continue;
408 		pci_iounmap(pdev, vdev->barmap[bar]);
409 		pci_release_selected_regions(pdev, 1 << bar);
410 		vdev->barmap[bar] = NULL;
411 	}
412 
413 	list_for_each_entry_safe(dummy_res, tmp,
414 				 &vdev->dummy_resources_list, res_next) {
415 		list_del(&dummy_res->res_next);
416 		release_resource(&dummy_res->resource);
417 		kfree(dummy_res);
418 	}
419 
420 	vdev->needs_reset = true;
421 
422 	/*
423 	 * If we have saved state, restore it.  If we can reset the device,
424 	 * even better.  Resetting with current state seems better than
425 	 * nothing, but saving and restoring current state without reset
426 	 * is just busy work.
427 	 */
428 	if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
429 		pci_info(pdev, "%s: Couldn't reload saved state\n", __func__);
430 
431 		if (!vdev->reset_works)
432 			goto out;
433 
434 		pci_save_state(pdev);
435 	}
436 
437 	/*
438 	 * Disable INTx and MSI, presumably to avoid spurious interrupts
439 	 * during reset.  Stolen from pci_reset_function()
440 	 */
441 	pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
442 
443 	/*
444 	 * Try to get the locks ourselves to prevent a deadlock. The
445 	 * success of this is dependent on being able to lock the device,
446 	 * which is not always possible.
447 	 * We can not use the "try" reset interface here, which will
448 	 * overwrite the previously restored configuration information.
449 	 */
450 	if (vdev->reset_works && pci_cfg_access_trylock(pdev)) {
451 		if (device_trylock(&pdev->dev)) {
452 			if (!__pci_reset_function_locked(pdev))
453 				vdev->needs_reset = false;
454 			device_unlock(&pdev->dev);
455 		}
456 		pci_cfg_access_unlock(pdev);
457 	}
458 
459 	pci_restore_state(pdev);
460 out:
461 	pci_disable_device(pdev);
462 
463 	vfio_pci_try_bus_reset(vdev);
464 
465 	if (!disable_idle_d3)
466 		vfio_pci_set_power_state(vdev, PCI_D3hot);
467 }
468 
469 static void vfio_pci_release(void *device_data)
470 {
471 	struct vfio_pci_device *vdev = device_data;
472 
473 	mutex_lock(&vdev->reflck->lock);
474 
475 	if (!(--vdev->refcnt)) {
476 		vfio_spapr_pci_eeh_release(vdev->pdev);
477 		vfio_pci_disable(vdev);
478 	}
479 
480 	mutex_unlock(&vdev->reflck->lock);
481 
482 	module_put(THIS_MODULE);
483 }
484 
485 static int vfio_pci_open(void *device_data)
486 {
487 	struct vfio_pci_device *vdev = device_data;
488 	int ret = 0;
489 
490 	if (!try_module_get(THIS_MODULE))
491 		return -ENODEV;
492 
493 	mutex_lock(&vdev->reflck->lock);
494 
495 	if (!vdev->refcnt) {
496 		ret = vfio_pci_enable(vdev);
497 		if (ret)
498 			goto error;
499 
500 		vfio_spapr_pci_eeh_open(vdev->pdev);
501 	}
502 	vdev->refcnt++;
503 error:
504 	mutex_unlock(&vdev->reflck->lock);
505 	if (ret)
506 		module_put(THIS_MODULE);
507 	return ret;
508 }
509 
510 static int vfio_pci_get_irq_count(struct vfio_pci_device *vdev, int irq_type)
511 {
512 	if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
513 		u8 pin;
514 
515 		if (!IS_ENABLED(CONFIG_VFIO_PCI_INTX) ||
516 		    vdev->nointx || vdev->pdev->is_virtfn)
517 			return 0;
518 
519 		pci_read_config_byte(vdev->pdev, PCI_INTERRUPT_PIN, &pin);
520 
521 		return pin ? 1 : 0;
522 	} else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
523 		u8 pos;
524 		u16 flags;
525 
526 		pos = vdev->pdev->msi_cap;
527 		if (pos) {
528 			pci_read_config_word(vdev->pdev,
529 					     pos + PCI_MSI_FLAGS, &flags);
530 			return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
531 		}
532 	} else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
533 		u8 pos;
534 		u16 flags;
535 
536 		pos = vdev->pdev->msix_cap;
537 		if (pos) {
538 			pci_read_config_word(vdev->pdev,
539 					     pos + PCI_MSIX_FLAGS, &flags);
540 
541 			return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
542 		}
543 	} else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX) {
544 		if (pci_is_pcie(vdev->pdev))
545 			return 1;
546 	} else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
547 		return 1;
548 	}
549 
550 	return 0;
551 }
552 
553 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
554 {
555 	(*(int *)data)++;
556 	return 0;
557 }
558 
559 struct vfio_pci_fill_info {
560 	int max;
561 	int cur;
562 	struct vfio_pci_dependent_device *devices;
563 };
564 
565 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
566 {
567 	struct vfio_pci_fill_info *fill = data;
568 	struct iommu_group *iommu_group;
569 
570 	if (fill->cur == fill->max)
571 		return -EAGAIN; /* Something changed, try again */
572 
573 	iommu_group = iommu_group_get(&pdev->dev);
574 	if (!iommu_group)
575 		return -EPERM; /* Cannot reset non-isolated devices */
576 
577 	fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
578 	fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
579 	fill->devices[fill->cur].bus = pdev->bus->number;
580 	fill->devices[fill->cur].devfn = pdev->devfn;
581 	fill->cur++;
582 	iommu_group_put(iommu_group);
583 	return 0;
584 }
585 
586 struct vfio_pci_group_entry {
587 	struct vfio_group *group;
588 	int id;
589 };
590 
591 struct vfio_pci_group_info {
592 	int count;
593 	struct vfio_pci_group_entry *groups;
594 };
595 
596 static int vfio_pci_validate_devs(struct pci_dev *pdev, void *data)
597 {
598 	struct vfio_pci_group_info *info = data;
599 	struct iommu_group *group;
600 	int id, i;
601 
602 	group = iommu_group_get(&pdev->dev);
603 	if (!group)
604 		return -EPERM;
605 
606 	id = iommu_group_id(group);
607 
608 	for (i = 0; i < info->count; i++)
609 		if (info->groups[i].id == id)
610 			break;
611 
612 	iommu_group_put(group);
613 
614 	return (i == info->count) ? -EINVAL : 0;
615 }
616 
617 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
618 {
619 	for (; pdev; pdev = pdev->bus->self)
620 		if (pdev->bus == slot->bus)
621 			return (pdev->slot == slot);
622 	return false;
623 }
624 
625 struct vfio_pci_walk_info {
626 	int (*fn)(struct pci_dev *, void *data);
627 	void *data;
628 	struct pci_dev *pdev;
629 	bool slot;
630 	int ret;
631 };
632 
633 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
634 {
635 	struct vfio_pci_walk_info *walk = data;
636 
637 	if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
638 		walk->ret = walk->fn(pdev, walk->data);
639 
640 	return walk->ret;
641 }
642 
643 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
644 					 int (*fn)(struct pci_dev *,
645 						   void *data), void *data,
646 					 bool slot)
647 {
648 	struct vfio_pci_walk_info walk = {
649 		.fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
650 	};
651 
652 	pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
653 
654 	return walk.ret;
655 }
656 
657 static int msix_mmappable_cap(struct vfio_pci_device *vdev,
658 			      struct vfio_info_cap *caps)
659 {
660 	struct vfio_info_cap_header header = {
661 		.id = VFIO_REGION_INFO_CAP_MSIX_MAPPABLE,
662 		.version = 1
663 	};
664 
665 	return vfio_info_add_capability(caps, &header, sizeof(header));
666 }
667 
668 int vfio_pci_register_dev_region(struct vfio_pci_device *vdev,
669 				 unsigned int type, unsigned int subtype,
670 				 const struct vfio_pci_regops *ops,
671 				 size_t size, u32 flags, void *data)
672 {
673 	struct vfio_pci_region *region;
674 
675 	region = krealloc(vdev->region,
676 			  (vdev->num_regions + 1) * sizeof(*region),
677 			  GFP_KERNEL);
678 	if (!region)
679 		return -ENOMEM;
680 
681 	vdev->region = region;
682 	vdev->region[vdev->num_regions].type = type;
683 	vdev->region[vdev->num_regions].subtype = subtype;
684 	vdev->region[vdev->num_regions].ops = ops;
685 	vdev->region[vdev->num_regions].size = size;
686 	vdev->region[vdev->num_regions].flags = flags;
687 	vdev->region[vdev->num_regions].data = data;
688 
689 	vdev->num_regions++;
690 
691 	return 0;
692 }
693 
694 static long vfio_pci_ioctl(void *device_data,
695 			   unsigned int cmd, unsigned long arg)
696 {
697 	struct vfio_pci_device *vdev = device_data;
698 	unsigned long minsz;
699 
700 	if (cmd == VFIO_DEVICE_GET_INFO) {
701 		struct vfio_device_info info;
702 
703 		minsz = offsetofend(struct vfio_device_info, num_irqs);
704 
705 		if (copy_from_user(&info, (void __user *)arg, minsz))
706 			return -EFAULT;
707 
708 		if (info.argsz < minsz)
709 			return -EINVAL;
710 
711 		info.flags = VFIO_DEVICE_FLAGS_PCI;
712 
713 		if (vdev->reset_works)
714 			info.flags |= VFIO_DEVICE_FLAGS_RESET;
715 
716 		info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions;
717 		info.num_irqs = VFIO_PCI_NUM_IRQS;
718 
719 		return copy_to_user((void __user *)arg, &info, minsz) ?
720 			-EFAULT : 0;
721 
722 	} else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
723 		struct pci_dev *pdev = vdev->pdev;
724 		struct vfio_region_info info;
725 		struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
726 		int i, ret;
727 
728 		minsz = offsetofend(struct vfio_region_info, offset);
729 
730 		if (copy_from_user(&info, (void __user *)arg, minsz))
731 			return -EFAULT;
732 
733 		if (info.argsz < minsz)
734 			return -EINVAL;
735 
736 		switch (info.index) {
737 		case VFIO_PCI_CONFIG_REGION_INDEX:
738 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
739 			info.size = pdev->cfg_size;
740 			info.flags = VFIO_REGION_INFO_FLAG_READ |
741 				     VFIO_REGION_INFO_FLAG_WRITE;
742 			break;
743 		case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
744 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
745 			info.size = pci_resource_len(pdev, info.index);
746 			if (!info.size) {
747 				info.flags = 0;
748 				break;
749 			}
750 
751 			info.flags = VFIO_REGION_INFO_FLAG_READ |
752 				     VFIO_REGION_INFO_FLAG_WRITE;
753 			if (vdev->bar_mmap_supported[info.index]) {
754 				info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
755 				if (info.index == vdev->msix_bar) {
756 					ret = msix_mmappable_cap(vdev, &caps);
757 					if (ret)
758 						return ret;
759 				}
760 			}
761 
762 			break;
763 		case VFIO_PCI_ROM_REGION_INDEX:
764 		{
765 			void __iomem *io;
766 			size_t size;
767 			u16 orig_cmd;
768 
769 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
770 			info.flags = 0;
771 
772 			/* Report the BAR size, not the ROM size */
773 			info.size = pci_resource_len(pdev, info.index);
774 			if (!info.size) {
775 				/* Shadow ROMs appear as PCI option ROMs */
776 				if (pdev->resource[PCI_ROM_RESOURCE].flags &
777 							IORESOURCE_ROM_SHADOW)
778 					info.size = 0x20000;
779 				else
780 					break;
781 			}
782 
783 			/*
784 			 * Is it really there?  Enable memory decode for
785 			 * implicit access in pci_map_rom().
786 			 */
787 			pci_read_config_word(pdev, PCI_COMMAND, &orig_cmd);
788 			pci_write_config_word(pdev, PCI_COMMAND,
789 					      orig_cmd | PCI_COMMAND_MEMORY);
790 
791 			io = pci_map_rom(pdev, &size);
792 			if (io) {
793 				info.flags = VFIO_REGION_INFO_FLAG_READ;
794 				pci_unmap_rom(pdev, io);
795 			} else {
796 				info.size = 0;
797 			}
798 
799 			pci_write_config_word(pdev, PCI_COMMAND, orig_cmd);
800 			break;
801 		}
802 		case VFIO_PCI_VGA_REGION_INDEX:
803 			if (!vdev->has_vga)
804 				return -EINVAL;
805 
806 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
807 			info.size = 0xc0000;
808 			info.flags = VFIO_REGION_INFO_FLAG_READ |
809 				     VFIO_REGION_INFO_FLAG_WRITE;
810 
811 			break;
812 		default:
813 		{
814 			struct vfio_region_info_cap_type cap_type = {
815 					.header.id = VFIO_REGION_INFO_CAP_TYPE,
816 					.header.version = 1 };
817 
818 			if (info.index >=
819 			    VFIO_PCI_NUM_REGIONS + vdev->num_regions)
820 				return -EINVAL;
821 			info.index = array_index_nospec(info.index,
822 							VFIO_PCI_NUM_REGIONS +
823 							vdev->num_regions);
824 
825 			i = info.index - VFIO_PCI_NUM_REGIONS;
826 
827 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
828 			info.size = vdev->region[i].size;
829 			info.flags = vdev->region[i].flags;
830 
831 			cap_type.type = vdev->region[i].type;
832 			cap_type.subtype = vdev->region[i].subtype;
833 
834 			ret = vfio_info_add_capability(&caps, &cap_type.header,
835 						       sizeof(cap_type));
836 			if (ret)
837 				return ret;
838 
839 			if (vdev->region[i].ops->add_capability) {
840 				ret = vdev->region[i].ops->add_capability(vdev,
841 						&vdev->region[i], &caps);
842 				if (ret)
843 					return ret;
844 			}
845 		}
846 		}
847 
848 		if (caps.size) {
849 			info.flags |= VFIO_REGION_INFO_FLAG_CAPS;
850 			if (info.argsz < sizeof(info) + caps.size) {
851 				info.argsz = sizeof(info) + caps.size;
852 				info.cap_offset = 0;
853 			} else {
854 				vfio_info_cap_shift(&caps, sizeof(info));
855 				if (copy_to_user((void __user *)arg +
856 						  sizeof(info), caps.buf,
857 						  caps.size)) {
858 					kfree(caps.buf);
859 					return -EFAULT;
860 				}
861 				info.cap_offset = sizeof(info);
862 			}
863 
864 			kfree(caps.buf);
865 		}
866 
867 		return copy_to_user((void __user *)arg, &info, minsz) ?
868 			-EFAULT : 0;
869 
870 	} else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
871 		struct vfio_irq_info info;
872 
873 		minsz = offsetofend(struct vfio_irq_info, count);
874 
875 		if (copy_from_user(&info, (void __user *)arg, minsz))
876 			return -EFAULT;
877 
878 		if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
879 			return -EINVAL;
880 
881 		switch (info.index) {
882 		case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
883 		case VFIO_PCI_REQ_IRQ_INDEX:
884 			break;
885 		case VFIO_PCI_ERR_IRQ_INDEX:
886 			if (pci_is_pcie(vdev->pdev))
887 				break;
888 		/* fall through */
889 		default:
890 			return -EINVAL;
891 		}
892 
893 		info.flags = VFIO_IRQ_INFO_EVENTFD;
894 
895 		info.count = vfio_pci_get_irq_count(vdev, info.index);
896 
897 		if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
898 			info.flags |= (VFIO_IRQ_INFO_MASKABLE |
899 				       VFIO_IRQ_INFO_AUTOMASKED);
900 		else
901 			info.flags |= VFIO_IRQ_INFO_NORESIZE;
902 
903 		return copy_to_user((void __user *)arg, &info, minsz) ?
904 			-EFAULT : 0;
905 
906 	} else if (cmd == VFIO_DEVICE_SET_IRQS) {
907 		struct vfio_irq_set hdr;
908 		u8 *data = NULL;
909 		int max, ret = 0;
910 		size_t data_size = 0;
911 
912 		minsz = offsetofend(struct vfio_irq_set, count);
913 
914 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
915 			return -EFAULT;
916 
917 		max = vfio_pci_get_irq_count(vdev, hdr.index);
918 
919 		ret = vfio_set_irqs_validate_and_prepare(&hdr, max,
920 						 VFIO_PCI_NUM_IRQS, &data_size);
921 		if (ret)
922 			return ret;
923 
924 		if (data_size) {
925 			data = memdup_user((void __user *)(arg + minsz),
926 					    data_size);
927 			if (IS_ERR(data))
928 				return PTR_ERR(data);
929 		}
930 
931 		mutex_lock(&vdev->igate);
932 
933 		ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
934 					      hdr.start, hdr.count, data);
935 
936 		mutex_unlock(&vdev->igate);
937 		kfree(data);
938 
939 		return ret;
940 
941 	} else if (cmd == VFIO_DEVICE_RESET) {
942 		return vdev->reset_works ?
943 			pci_try_reset_function(vdev->pdev) : -EINVAL;
944 
945 	} else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
946 		struct vfio_pci_hot_reset_info hdr;
947 		struct vfio_pci_fill_info fill = { 0 };
948 		struct vfio_pci_dependent_device *devices = NULL;
949 		bool slot = false;
950 		int ret = 0;
951 
952 		minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
953 
954 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
955 			return -EFAULT;
956 
957 		if (hdr.argsz < minsz)
958 			return -EINVAL;
959 
960 		hdr.flags = 0;
961 
962 		/* Can we do a slot or bus reset or neither? */
963 		if (!pci_probe_reset_slot(vdev->pdev->slot))
964 			slot = true;
965 		else if (pci_probe_reset_bus(vdev->pdev->bus))
966 			return -ENODEV;
967 
968 		/* How many devices are affected? */
969 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
970 						    vfio_pci_count_devs,
971 						    &fill.max, slot);
972 		if (ret)
973 			return ret;
974 
975 		WARN_ON(!fill.max); /* Should always be at least one */
976 
977 		/*
978 		 * If there's enough space, fill it now, otherwise return
979 		 * -ENOSPC and the number of devices affected.
980 		 */
981 		if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
982 			ret = -ENOSPC;
983 			hdr.count = fill.max;
984 			goto reset_info_exit;
985 		}
986 
987 		devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
988 		if (!devices)
989 			return -ENOMEM;
990 
991 		fill.devices = devices;
992 
993 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
994 						    vfio_pci_fill_devs,
995 						    &fill, slot);
996 
997 		/*
998 		 * If a device was removed between counting and filling,
999 		 * we may come up short of fill.max.  If a device was
1000 		 * added, we'll have a return of -EAGAIN above.
1001 		 */
1002 		if (!ret)
1003 			hdr.count = fill.cur;
1004 
1005 reset_info_exit:
1006 		if (copy_to_user((void __user *)arg, &hdr, minsz))
1007 			ret = -EFAULT;
1008 
1009 		if (!ret) {
1010 			if (copy_to_user((void __user *)(arg + minsz), devices,
1011 					 hdr.count * sizeof(*devices)))
1012 				ret = -EFAULT;
1013 		}
1014 
1015 		kfree(devices);
1016 		return ret;
1017 
1018 	} else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
1019 		struct vfio_pci_hot_reset hdr;
1020 		int32_t *group_fds;
1021 		struct vfio_pci_group_entry *groups;
1022 		struct vfio_pci_group_info info;
1023 		bool slot = false;
1024 		int i, count = 0, ret = 0;
1025 
1026 		minsz = offsetofend(struct vfio_pci_hot_reset, count);
1027 
1028 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
1029 			return -EFAULT;
1030 
1031 		if (hdr.argsz < minsz || hdr.flags)
1032 			return -EINVAL;
1033 
1034 		/* Can we do a slot or bus reset or neither? */
1035 		if (!pci_probe_reset_slot(vdev->pdev->slot))
1036 			slot = true;
1037 		else if (pci_probe_reset_bus(vdev->pdev->bus))
1038 			return -ENODEV;
1039 
1040 		/*
1041 		 * We can't let userspace give us an arbitrarily large
1042 		 * buffer to copy, so verify how many we think there
1043 		 * could be.  Note groups can have multiple devices so
1044 		 * one group per device is the max.
1045 		 */
1046 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1047 						    vfio_pci_count_devs,
1048 						    &count, slot);
1049 		if (ret)
1050 			return ret;
1051 
1052 		/* Somewhere between 1 and count is OK */
1053 		if (!hdr.count || hdr.count > count)
1054 			return -EINVAL;
1055 
1056 		group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
1057 		groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);
1058 		if (!group_fds || !groups) {
1059 			kfree(group_fds);
1060 			kfree(groups);
1061 			return -ENOMEM;
1062 		}
1063 
1064 		if (copy_from_user(group_fds, (void __user *)(arg + minsz),
1065 				   hdr.count * sizeof(*group_fds))) {
1066 			kfree(group_fds);
1067 			kfree(groups);
1068 			return -EFAULT;
1069 		}
1070 
1071 		/*
1072 		 * For each group_fd, get the group through the vfio external
1073 		 * user interface and store the group and iommu ID.  This
1074 		 * ensures the group is held across the reset.
1075 		 */
1076 		for (i = 0; i < hdr.count; i++) {
1077 			struct vfio_group *group;
1078 			struct fd f = fdget(group_fds[i]);
1079 			if (!f.file) {
1080 				ret = -EBADF;
1081 				break;
1082 			}
1083 
1084 			group = vfio_group_get_external_user(f.file);
1085 			fdput(f);
1086 			if (IS_ERR(group)) {
1087 				ret = PTR_ERR(group);
1088 				break;
1089 			}
1090 
1091 			groups[i].group = group;
1092 			groups[i].id = vfio_external_user_iommu_id(group);
1093 		}
1094 
1095 		kfree(group_fds);
1096 
1097 		/* release reference to groups on error */
1098 		if (ret)
1099 			goto hot_reset_release;
1100 
1101 		info.count = hdr.count;
1102 		info.groups = groups;
1103 
1104 		/*
1105 		 * Test whether all the affected devices are contained
1106 		 * by the set of groups provided by the user.
1107 		 */
1108 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1109 						    vfio_pci_validate_devs,
1110 						    &info, slot);
1111 		if (!ret)
1112 			/* User has access, do the reset */
1113 			ret = pci_reset_bus(vdev->pdev);
1114 
1115 hot_reset_release:
1116 		for (i--; i >= 0; i--)
1117 			vfio_group_put_external_user(groups[i].group);
1118 
1119 		kfree(groups);
1120 		return ret;
1121 	} else if (cmd == VFIO_DEVICE_IOEVENTFD) {
1122 		struct vfio_device_ioeventfd ioeventfd;
1123 		int count;
1124 
1125 		minsz = offsetofend(struct vfio_device_ioeventfd, fd);
1126 
1127 		if (copy_from_user(&ioeventfd, (void __user *)arg, minsz))
1128 			return -EFAULT;
1129 
1130 		if (ioeventfd.argsz < minsz)
1131 			return -EINVAL;
1132 
1133 		if (ioeventfd.flags & ~VFIO_DEVICE_IOEVENTFD_SIZE_MASK)
1134 			return -EINVAL;
1135 
1136 		count = ioeventfd.flags & VFIO_DEVICE_IOEVENTFD_SIZE_MASK;
1137 
1138 		if (hweight8(count) != 1 || ioeventfd.fd < -1)
1139 			return -EINVAL;
1140 
1141 		return vfio_pci_ioeventfd(vdev, ioeventfd.offset,
1142 					  ioeventfd.data, count, ioeventfd.fd);
1143 	}
1144 
1145 	return -ENOTTY;
1146 }
1147 
1148 static ssize_t vfio_pci_rw(void *device_data, char __user *buf,
1149 			   size_t count, loff_t *ppos, bool iswrite)
1150 {
1151 	unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
1152 	struct vfio_pci_device *vdev = device_data;
1153 
1154 	if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1155 		return -EINVAL;
1156 
1157 	switch (index) {
1158 	case VFIO_PCI_CONFIG_REGION_INDEX:
1159 		return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
1160 
1161 	case VFIO_PCI_ROM_REGION_INDEX:
1162 		if (iswrite)
1163 			return -EINVAL;
1164 		return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
1165 
1166 	case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
1167 		return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
1168 
1169 	case VFIO_PCI_VGA_REGION_INDEX:
1170 		return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
1171 	default:
1172 		index -= VFIO_PCI_NUM_REGIONS;
1173 		return vdev->region[index].ops->rw(vdev, buf,
1174 						   count, ppos, iswrite);
1175 	}
1176 
1177 	return -EINVAL;
1178 }
1179 
1180 static ssize_t vfio_pci_read(void *device_data, char __user *buf,
1181 			     size_t count, loff_t *ppos)
1182 {
1183 	if (!count)
1184 		return 0;
1185 
1186 	return vfio_pci_rw(device_data, buf, count, ppos, false);
1187 }
1188 
1189 static ssize_t vfio_pci_write(void *device_data, const char __user *buf,
1190 			      size_t count, loff_t *ppos)
1191 {
1192 	if (!count)
1193 		return 0;
1194 
1195 	return vfio_pci_rw(device_data, (char __user *)buf, count, ppos, true);
1196 }
1197 
1198 static int vfio_pci_mmap(void *device_data, struct vm_area_struct *vma)
1199 {
1200 	struct vfio_pci_device *vdev = device_data;
1201 	struct pci_dev *pdev = vdev->pdev;
1202 	unsigned int index;
1203 	u64 phys_len, req_len, pgoff, req_start;
1204 	int ret;
1205 
1206 	index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1207 
1208 	if (vma->vm_end < vma->vm_start)
1209 		return -EINVAL;
1210 	if ((vma->vm_flags & VM_SHARED) == 0)
1211 		return -EINVAL;
1212 	if (index >= VFIO_PCI_NUM_REGIONS) {
1213 		int regnum = index - VFIO_PCI_NUM_REGIONS;
1214 		struct vfio_pci_region *region = vdev->region + regnum;
1215 
1216 		if (region && region->ops && region->ops->mmap &&
1217 		    (region->flags & VFIO_REGION_INFO_FLAG_MMAP))
1218 			return region->ops->mmap(vdev, region, vma);
1219 		return -EINVAL;
1220 	}
1221 	if (index >= VFIO_PCI_ROM_REGION_INDEX)
1222 		return -EINVAL;
1223 	if (!vdev->bar_mmap_supported[index])
1224 		return -EINVAL;
1225 
1226 	phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1227 	req_len = vma->vm_end - vma->vm_start;
1228 	pgoff = vma->vm_pgoff &
1229 		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1230 	req_start = pgoff << PAGE_SHIFT;
1231 
1232 	if (req_start + req_len > phys_len)
1233 		return -EINVAL;
1234 
1235 	/*
1236 	 * Even though we don't make use of the barmap for the mmap,
1237 	 * we need to request the region and the barmap tracks that.
1238 	 */
1239 	if (!vdev->barmap[index]) {
1240 		ret = pci_request_selected_regions(pdev,
1241 						   1 << index, "vfio-pci");
1242 		if (ret)
1243 			return ret;
1244 
1245 		vdev->barmap[index] = pci_iomap(pdev, index, 0);
1246 		if (!vdev->barmap[index]) {
1247 			pci_release_selected_regions(pdev, 1 << index);
1248 			return -ENOMEM;
1249 		}
1250 	}
1251 
1252 	vma->vm_private_data = vdev;
1253 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1254 	vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
1255 
1256 	return remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
1257 			       req_len, vma->vm_page_prot);
1258 }
1259 
1260 static void vfio_pci_request(void *device_data, unsigned int count)
1261 {
1262 	struct vfio_pci_device *vdev = device_data;
1263 	struct pci_dev *pdev = vdev->pdev;
1264 
1265 	mutex_lock(&vdev->igate);
1266 
1267 	if (vdev->req_trigger) {
1268 		if (!(count % 10))
1269 			pci_notice_ratelimited(pdev,
1270 				"Relaying device request to user (#%u)\n",
1271 				count);
1272 		eventfd_signal(vdev->req_trigger, 1);
1273 	} else if (count == 0) {
1274 		pci_warn(pdev,
1275 			"No device request channel registered, blocked until released by user\n");
1276 	}
1277 
1278 	mutex_unlock(&vdev->igate);
1279 }
1280 
1281 static const struct vfio_device_ops vfio_pci_ops = {
1282 	.name		= "vfio-pci",
1283 	.open		= vfio_pci_open,
1284 	.release	= vfio_pci_release,
1285 	.ioctl		= vfio_pci_ioctl,
1286 	.read		= vfio_pci_read,
1287 	.write		= vfio_pci_write,
1288 	.mmap		= vfio_pci_mmap,
1289 	.request	= vfio_pci_request,
1290 };
1291 
1292 static int vfio_pci_reflck_attach(struct vfio_pci_device *vdev);
1293 static void vfio_pci_reflck_put(struct vfio_pci_reflck *reflck);
1294 
1295 static int vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1296 {
1297 	struct vfio_pci_device *vdev;
1298 	struct iommu_group *group;
1299 	int ret;
1300 
1301 	if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
1302 		return -EINVAL;
1303 
1304 	/*
1305 	 * Prevent binding to PFs with VFs enabled, this too easily allows
1306 	 * userspace instance with VFs and PFs from the same device, which
1307 	 * cannot work.  Disabling SR-IOV here would initiate removing the
1308 	 * VFs, which would unbind the driver, which is prone to blocking
1309 	 * if that VF is also in use by vfio-pci.  Just reject these PFs
1310 	 * and let the user sort it out.
1311 	 */
1312 	if (pci_num_vf(pdev)) {
1313 		pci_warn(pdev, "Cannot bind to PF with SR-IOV enabled\n");
1314 		return -EBUSY;
1315 	}
1316 
1317 	group = vfio_iommu_group_get(&pdev->dev);
1318 	if (!group)
1319 		return -EINVAL;
1320 
1321 	vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
1322 	if (!vdev) {
1323 		vfio_iommu_group_put(group, &pdev->dev);
1324 		return -ENOMEM;
1325 	}
1326 
1327 	vdev->pdev = pdev;
1328 	vdev->irq_type = VFIO_PCI_NUM_IRQS;
1329 	mutex_init(&vdev->igate);
1330 	spin_lock_init(&vdev->irqlock);
1331 	mutex_init(&vdev->ioeventfds_lock);
1332 	INIT_LIST_HEAD(&vdev->ioeventfds_list);
1333 
1334 	ret = vfio_add_group_dev(&pdev->dev, &vfio_pci_ops, vdev);
1335 	if (ret) {
1336 		vfio_iommu_group_put(group, &pdev->dev);
1337 		kfree(vdev);
1338 		return ret;
1339 	}
1340 
1341 	ret = vfio_pci_reflck_attach(vdev);
1342 	if (ret) {
1343 		vfio_del_group_dev(&pdev->dev);
1344 		vfio_iommu_group_put(group, &pdev->dev);
1345 		kfree(vdev);
1346 		return ret;
1347 	}
1348 
1349 	if (vfio_pci_is_vga(pdev)) {
1350 		vga_client_register(pdev, vdev, NULL, vfio_pci_set_vga_decode);
1351 		vga_set_legacy_decoding(pdev,
1352 					vfio_pci_set_vga_decode(vdev, false));
1353 	}
1354 
1355 	vfio_pci_probe_power_state(vdev);
1356 
1357 	if (!disable_idle_d3) {
1358 		/*
1359 		 * pci-core sets the device power state to an unknown value at
1360 		 * bootup and after being removed from a driver.  The only
1361 		 * transition it allows from this unknown state is to D0, which
1362 		 * typically happens when a driver calls pci_enable_device().
1363 		 * We're not ready to enable the device yet, but we do want to
1364 		 * be able to get to D3.  Therefore first do a D0 transition
1365 		 * before going to D3.
1366 		 */
1367 		vfio_pci_set_power_state(vdev, PCI_D0);
1368 		vfio_pci_set_power_state(vdev, PCI_D3hot);
1369 	}
1370 
1371 	return ret;
1372 }
1373 
1374 static void vfio_pci_remove(struct pci_dev *pdev)
1375 {
1376 	struct vfio_pci_device *vdev;
1377 
1378 	vdev = vfio_del_group_dev(&pdev->dev);
1379 	if (!vdev)
1380 		return;
1381 
1382 	vfio_pci_reflck_put(vdev->reflck);
1383 
1384 	vfio_iommu_group_put(pdev->dev.iommu_group, &pdev->dev);
1385 	kfree(vdev->region);
1386 	mutex_destroy(&vdev->ioeventfds_lock);
1387 
1388 	if (!disable_idle_d3)
1389 		vfio_pci_set_power_state(vdev, PCI_D0);
1390 
1391 	kfree(vdev->pm_save);
1392 	kfree(vdev);
1393 
1394 	if (vfio_pci_is_vga(pdev)) {
1395 		vga_client_register(pdev, NULL, NULL, NULL);
1396 		vga_set_legacy_decoding(pdev,
1397 				VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
1398 				VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM);
1399 	}
1400 }
1401 
1402 static pci_ers_result_t vfio_pci_aer_err_detected(struct pci_dev *pdev,
1403 						  pci_channel_state_t state)
1404 {
1405 	struct vfio_pci_device *vdev;
1406 	struct vfio_device *device;
1407 
1408 	device = vfio_device_get_from_dev(&pdev->dev);
1409 	if (device == NULL)
1410 		return PCI_ERS_RESULT_DISCONNECT;
1411 
1412 	vdev = vfio_device_data(device);
1413 	if (vdev == NULL) {
1414 		vfio_device_put(device);
1415 		return PCI_ERS_RESULT_DISCONNECT;
1416 	}
1417 
1418 	mutex_lock(&vdev->igate);
1419 
1420 	if (vdev->err_trigger)
1421 		eventfd_signal(vdev->err_trigger, 1);
1422 
1423 	mutex_unlock(&vdev->igate);
1424 
1425 	vfio_device_put(device);
1426 
1427 	return PCI_ERS_RESULT_CAN_RECOVER;
1428 }
1429 
1430 static const struct pci_error_handlers vfio_err_handlers = {
1431 	.error_detected = vfio_pci_aer_err_detected,
1432 };
1433 
1434 static struct pci_driver vfio_pci_driver = {
1435 	.name		= "vfio-pci",
1436 	.id_table	= NULL, /* only dynamic ids */
1437 	.probe		= vfio_pci_probe,
1438 	.remove		= vfio_pci_remove,
1439 	.err_handler	= &vfio_err_handlers,
1440 };
1441 
1442 static DEFINE_MUTEX(reflck_lock);
1443 
1444 static struct vfio_pci_reflck *vfio_pci_reflck_alloc(void)
1445 {
1446 	struct vfio_pci_reflck *reflck;
1447 
1448 	reflck = kzalloc(sizeof(*reflck), GFP_KERNEL);
1449 	if (!reflck)
1450 		return ERR_PTR(-ENOMEM);
1451 
1452 	kref_init(&reflck->kref);
1453 	mutex_init(&reflck->lock);
1454 
1455 	return reflck;
1456 }
1457 
1458 static void vfio_pci_reflck_get(struct vfio_pci_reflck *reflck)
1459 {
1460 	kref_get(&reflck->kref);
1461 }
1462 
1463 static int vfio_pci_reflck_find(struct pci_dev *pdev, void *data)
1464 {
1465 	struct vfio_pci_reflck **preflck = data;
1466 	struct vfio_device *device;
1467 	struct vfio_pci_device *vdev;
1468 
1469 	device = vfio_device_get_from_dev(&pdev->dev);
1470 	if (!device)
1471 		return 0;
1472 
1473 	if (pci_dev_driver(pdev) != &vfio_pci_driver) {
1474 		vfio_device_put(device);
1475 		return 0;
1476 	}
1477 
1478 	vdev = vfio_device_data(device);
1479 
1480 	if (vdev->reflck) {
1481 		vfio_pci_reflck_get(vdev->reflck);
1482 		*preflck = vdev->reflck;
1483 		vfio_device_put(device);
1484 		return 1;
1485 	}
1486 
1487 	vfio_device_put(device);
1488 	return 0;
1489 }
1490 
1491 static int vfio_pci_reflck_attach(struct vfio_pci_device *vdev)
1492 {
1493 	bool slot = !pci_probe_reset_slot(vdev->pdev->slot);
1494 
1495 	mutex_lock(&reflck_lock);
1496 
1497 	if (pci_is_root_bus(vdev->pdev->bus) ||
1498 	    vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_reflck_find,
1499 					  &vdev->reflck, slot) <= 0)
1500 		vdev->reflck = vfio_pci_reflck_alloc();
1501 
1502 	mutex_unlock(&reflck_lock);
1503 
1504 	return PTR_ERR_OR_ZERO(vdev->reflck);
1505 }
1506 
1507 static void vfio_pci_reflck_release(struct kref *kref)
1508 {
1509 	struct vfio_pci_reflck *reflck = container_of(kref,
1510 						      struct vfio_pci_reflck,
1511 						      kref);
1512 
1513 	kfree(reflck);
1514 	mutex_unlock(&reflck_lock);
1515 }
1516 
1517 static void vfio_pci_reflck_put(struct vfio_pci_reflck *reflck)
1518 {
1519 	kref_put_mutex(&reflck->kref, vfio_pci_reflck_release, &reflck_lock);
1520 }
1521 
1522 struct vfio_devices {
1523 	struct vfio_device **devices;
1524 	int cur_index;
1525 	int max_index;
1526 };
1527 
1528 static int vfio_pci_get_unused_devs(struct pci_dev *pdev, void *data)
1529 {
1530 	struct vfio_devices *devs = data;
1531 	struct vfio_device *device;
1532 	struct vfio_pci_device *vdev;
1533 
1534 	if (devs->cur_index == devs->max_index)
1535 		return -ENOSPC;
1536 
1537 	device = vfio_device_get_from_dev(&pdev->dev);
1538 	if (!device)
1539 		return -EINVAL;
1540 
1541 	if (pci_dev_driver(pdev) != &vfio_pci_driver) {
1542 		vfio_device_put(device);
1543 		return -EBUSY;
1544 	}
1545 
1546 	vdev = vfio_device_data(device);
1547 
1548 	/* Fault if the device is not unused */
1549 	if (vdev->refcnt) {
1550 		vfio_device_put(device);
1551 		return -EBUSY;
1552 	}
1553 
1554 	devs->devices[devs->cur_index++] = device;
1555 	return 0;
1556 }
1557 
1558 /*
1559  * If a bus or slot reset is available for the provided device and:
1560  *  - All of the devices affected by that bus or slot reset are unused
1561  *    (!refcnt)
1562  *  - At least one of the affected devices is marked dirty via
1563  *    needs_reset (such as by lack of FLR support)
1564  * Then attempt to perform that bus or slot reset.  Callers are required
1565  * to hold vdev->reflck->lock, protecting the bus/slot reset group from
1566  * concurrent opens.  A vfio_device reference is acquired for each device
1567  * to prevent unbinds during the reset operation.
1568  *
1569  * NB: vfio-core considers a group to be viable even if some devices are
1570  * bound to drivers like pci-stub or pcieport.  Here we require all devices
1571  * to be bound to vfio_pci since that's the only way we can be sure they
1572  * stay put.
1573  */
1574 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev)
1575 {
1576 	struct vfio_devices devs = { .cur_index = 0 };
1577 	int i = 0, ret = -EINVAL;
1578 	bool slot = false;
1579 	struct vfio_pci_device *tmp;
1580 
1581 	if (!pci_probe_reset_slot(vdev->pdev->slot))
1582 		slot = true;
1583 	else if (pci_probe_reset_bus(vdev->pdev->bus))
1584 		return;
1585 
1586 	if (vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
1587 					  &i, slot) || !i)
1588 		return;
1589 
1590 	devs.max_index = i;
1591 	devs.devices = kcalloc(i, sizeof(struct vfio_device *), GFP_KERNEL);
1592 	if (!devs.devices)
1593 		return;
1594 
1595 	if (vfio_pci_for_each_slot_or_bus(vdev->pdev,
1596 					  vfio_pci_get_unused_devs,
1597 					  &devs, slot))
1598 		goto put_devs;
1599 
1600 	/* Does at least one need a reset? */
1601 	for (i = 0; i < devs.cur_index; i++) {
1602 		tmp = vfio_device_data(devs.devices[i]);
1603 		if (tmp->needs_reset) {
1604 			ret = pci_reset_bus(vdev->pdev);
1605 			break;
1606 		}
1607 	}
1608 
1609 put_devs:
1610 	for (i = 0; i < devs.cur_index; i++) {
1611 		tmp = vfio_device_data(devs.devices[i]);
1612 
1613 		/*
1614 		 * If reset was successful, affected devices no longer need
1615 		 * a reset and we should return all the collateral devices
1616 		 * to low power.  If not successful, we either didn't reset
1617 		 * the bus or timed out waiting for it, so let's not touch
1618 		 * the power state.
1619 		 */
1620 		if (!ret) {
1621 			tmp->needs_reset = false;
1622 
1623 			if (tmp != vdev && !disable_idle_d3)
1624 				vfio_pci_set_power_state(tmp, PCI_D3hot);
1625 		}
1626 
1627 		vfio_device_put(devs.devices[i]);
1628 	}
1629 
1630 	kfree(devs.devices);
1631 }
1632 
1633 static void __exit vfio_pci_cleanup(void)
1634 {
1635 	pci_unregister_driver(&vfio_pci_driver);
1636 	vfio_pci_uninit_perm_bits();
1637 }
1638 
1639 static void __init vfio_pci_fill_ids(void)
1640 {
1641 	char *p, *id;
1642 	int rc;
1643 
1644 	/* no ids passed actually */
1645 	if (ids[0] == '\0')
1646 		return;
1647 
1648 	/* add ids specified in the module parameter */
1649 	p = ids;
1650 	while ((id = strsep(&p, ","))) {
1651 		unsigned int vendor, device, subvendor = PCI_ANY_ID,
1652 			subdevice = PCI_ANY_ID, class = 0, class_mask = 0;
1653 		int fields;
1654 
1655 		if (!strlen(id))
1656 			continue;
1657 
1658 		fields = sscanf(id, "%x:%x:%x:%x:%x:%x",
1659 				&vendor, &device, &subvendor, &subdevice,
1660 				&class, &class_mask);
1661 
1662 		if (fields < 2) {
1663 			pr_warn("invalid id string \"%s\"\n", id);
1664 			continue;
1665 		}
1666 
1667 		rc = pci_add_dynid(&vfio_pci_driver, vendor, device,
1668 				   subvendor, subdevice, class, class_mask, 0);
1669 		if (rc)
1670 			pr_warn("failed to add dynamic id [%04x:%04x[%04x:%04x]] class %#08x/%08x (%d)\n",
1671 				vendor, device, subvendor, subdevice,
1672 				class, class_mask, rc);
1673 		else
1674 			pr_info("add [%04x:%04x[%04x:%04x]] class %#08x/%08x\n",
1675 				vendor, device, subvendor, subdevice,
1676 				class, class_mask);
1677 	}
1678 }
1679 
1680 static int __init vfio_pci_init(void)
1681 {
1682 	int ret;
1683 
1684 	/* Allocate shared config space permision data used by all devices */
1685 	ret = vfio_pci_init_perm_bits();
1686 	if (ret)
1687 		return ret;
1688 
1689 	/* Register and scan for devices */
1690 	ret = pci_register_driver(&vfio_pci_driver);
1691 	if (ret)
1692 		goto out_driver;
1693 
1694 	vfio_pci_fill_ids();
1695 
1696 	return 0;
1697 
1698 out_driver:
1699 	vfio_pci_uninit_perm_bits();
1700 	return ret;
1701 }
1702 
1703 module_init(vfio_pci_init);
1704 module_exit(vfio_pci_cleanup);
1705 
1706 MODULE_VERSION(DRIVER_VERSION);
1707 MODULE_LICENSE("GPL v2");
1708 MODULE_AUTHOR(DRIVER_AUTHOR);
1709 MODULE_DESCRIPTION(DRIVER_DESC);
1710