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