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