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