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