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