xref: /linux/drivers/vfio/pci/vfio_pci.c (revision 52338415)
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 get the locks ourselves to prevent a deadlock. The
442 	 * success of this is dependent on being able to lock the device,
443 	 * which is not always possible.
444 	 * We can not use the "try" reset interface here, which will
445 	 * overwrite the previously restored configuration information.
446 	 */
447 	if (vdev->reset_works && pci_cfg_access_trylock(pdev)) {
448 		if (device_trylock(&pdev->dev)) {
449 			if (!__pci_reset_function_locked(pdev))
450 				vdev->needs_reset = false;
451 			device_unlock(&pdev->dev);
452 		}
453 		pci_cfg_access_unlock(pdev);
454 	}
455 
456 	pci_restore_state(pdev);
457 out:
458 	pci_disable_device(pdev);
459 
460 	vfio_pci_try_bus_reset(vdev);
461 
462 	if (!disable_idle_d3)
463 		vfio_pci_set_power_state(vdev, PCI_D3hot);
464 }
465 
466 static void vfio_pci_release(void *device_data)
467 {
468 	struct vfio_pci_device *vdev = device_data;
469 
470 	mutex_lock(&vdev->reflck->lock);
471 
472 	if (!(--vdev->refcnt)) {
473 		vfio_spapr_pci_eeh_release(vdev->pdev);
474 		vfio_pci_disable(vdev);
475 	}
476 
477 	mutex_unlock(&vdev->reflck->lock);
478 
479 	module_put(THIS_MODULE);
480 }
481 
482 static int vfio_pci_open(void *device_data)
483 {
484 	struct vfio_pci_device *vdev = device_data;
485 	int ret = 0;
486 
487 	if (!try_module_get(THIS_MODULE))
488 		return -ENODEV;
489 
490 	mutex_lock(&vdev->reflck->lock);
491 
492 	if (!vdev->refcnt) {
493 		ret = vfio_pci_enable(vdev);
494 		if (ret)
495 			goto error;
496 
497 		vfio_spapr_pci_eeh_open(vdev->pdev);
498 	}
499 	vdev->refcnt++;
500 error:
501 	mutex_unlock(&vdev->reflck->lock);
502 	if (ret)
503 		module_put(THIS_MODULE);
504 	return ret;
505 }
506 
507 static int vfio_pci_get_irq_count(struct vfio_pci_device *vdev, int irq_type)
508 {
509 	if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
510 		u8 pin;
511 
512 		if (!IS_ENABLED(CONFIG_VFIO_PCI_INTX) ||
513 		    vdev->nointx || vdev->pdev->is_virtfn)
514 			return 0;
515 
516 		pci_read_config_byte(vdev->pdev, PCI_INTERRUPT_PIN, &pin);
517 
518 		return pin ? 1 : 0;
519 	} else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
520 		u8 pos;
521 		u16 flags;
522 
523 		pos = vdev->pdev->msi_cap;
524 		if (pos) {
525 			pci_read_config_word(vdev->pdev,
526 					     pos + PCI_MSI_FLAGS, &flags);
527 			return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
528 		}
529 	} else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
530 		u8 pos;
531 		u16 flags;
532 
533 		pos = vdev->pdev->msix_cap;
534 		if (pos) {
535 			pci_read_config_word(vdev->pdev,
536 					     pos + PCI_MSIX_FLAGS, &flags);
537 
538 			return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
539 		}
540 	} else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX) {
541 		if (pci_is_pcie(vdev->pdev))
542 			return 1;
543 	} else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
544 		return 1;
545 	}
546 
547 	return 0;
548 }
549 
550 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
551 {
552 	(*(int *)data)++;
553 	return 0;
554 }
555 
556 struct vfio_pci_fill_info {
557 	int max;
558 	int cur;
559 	struct vfio_pci_dependent_device *devices;
560 };
561 
562 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
563 {
564 	struct vfio_pci_fill_info *fill = data;
565 	struct iommu_group *iommu_group;
566 
567 	if (fill->cur == fill->max)
568 		return -EAGAIN; /* Something changed, try again */
569 
570 	iommu_group = iommu_group_get(&pdev->dev);
571 	if (!iommu_group)
572 		return -EPERM; /* Cannot reset non-isolated devices */
573 
574 	fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
575 	fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
576 	fill->devices[fill->cur].bus = pdev->bus->number;
577 	fill->devices[fill->cur].devfn = pdev->devfn;
578 	fill->cur++;
579 	iommu_group_put(iommu_group);
580 	return 0;
581 }
582 
583 struct vfio_pci_group_entry {
584 	struct vfio_group *group;
585 	int id;
586 };
587 
588 struct vfio_pci_group_info {
589 	int count;
590 	struct vfio_pci_group_entry *groups;
591 };
592 
593 static int vfio_pci_validate_devs(struct pci_dev *pdev, void *data)
594 {
595 	struct vfio_pci_group_info *info = data;
596 	struct iommu_group *group;
597 	int id, i;
598 
599 	group = iommu_group_get(&pdev->dev);
600 	if (!group)
601 		return -EPERM;
602 
603 	id = iommu_group_id(group);
604 
605 	for (i = 0; i < info->count; i++)
606 		if (info->groups[i].id == id)
607 			break;
608 
609 	iommu_group_put(group);
610 
611 	return (i == info->count) ? -EINVAL : 0;
612 }
613 
614 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
615 {
616 	for (; pdev; pdev = pdev->bus->self)
617 		if (pdev->bus == slot->bus)
618 			return (pdev->slot == slot);
619 	return false;
620 }
621 
622 struct vfio_pci_walk_info {
623 	int (*fn)(struct pci_dev *, void *data);
624 	void *data;
625 	struct pci_dev *pdev;
626 	bool slot;
627 	int ret;
628 };
629 
630 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
631 {
632 	struct vfio_pci_walk_info *walk = data;
633 
634 	if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
635 		walk->ret = walk->fn(pdev, walk->data);
636 
637 	return walk->ret;
638 }
639 
640 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
641 					 int (*fn)(struct pci_dev *,
642 						   void *data), void *data,
643 					 bool slot)
644 {
645 	struct vfio_pci_walk_info walk = {
646 		.fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
647 	};
648 
649 	pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
650 
651 	return walk.ret;
652 }
653 
654 static int msix_mmappable_cap(struct vfio_pci_device *vdev,
655 			      struct vfio_info_cap *caps)
656 {
657 	struct vfio_info_cap_header header = {
658 		.id = VFIO_REGION_INFO_CAP_MSIX_MAPPABLE,
659 		.version = 1
660 	};
661 
662 	return vfio_info_add_capability(caps, &header, sizeof(header));
663 }
664 
665 int vfio_pci_register_dev_region(struct vfio_pci_device *vdev,
666 				 unsigned int type, unsigned int subtype,
667 				 const struct vfio_pci_regops *ops,
668 				 size_t size, u32 flags, void *data)
669 {
670 	struct vfio_pci_region *region;
671 
672 	region = krealloc(vdev->region,
673 			  (vdev->num_regions + 1) * sizeof(*region),
674 			  GFP_KERNEL);
675 	if (!region)
676 		return -ENOMEM;
677 
678 	vdev->region = region;
679 	vdev->region[vdev->num_regions].type = type;
680 	vdev->region[vdev->num_regions].subtype = subtype;
681 	vdev->region[vdev->num_regions].ops = ops;
682 	vdev->region[vdev->num_regions].size = size;
683 	vdev->region[vdev->num_regions].flags = flags;
684 	vdev->region[vdev->num_regions].data = data;
685 
686 	vdev->num_regions++;
687 
688 	return 0;
689 }
690 
691 static long vfio_pci_ioctl(void *device_data,
692 			   unsigned int cmd, unsigned long arg)
693 {
694 	struct vfio_pci_device *vdev = device_data;
695 	unsigned long minsz;
696 
697 	if (cmd == VFIO_DEVICE_GET_INFO) {
698 		struct vfio_device_info info;
699 
700 		minsz = offsetofend(struct vfio_device_info, num_irqs);
701 
702 		if (copy_from_user(&info, (void __user *)arg, minsz))
703 			return -EFAULT;
704 
705 		if (info.argsz < minsz)
706 			return -EINVAL;
707 
708 		info.flags = VFIO_DEVICE_FLAGS_PCI;
709 
710 		if (vdev->reset_works)
711 			info.flags |= VFIO_DEVICE_FLAGS_RESET;
712 
713 		info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions;
714 		info.num_irqs = VFIO_PCI_NUM_IRQS;
715 
716 		return copy_to_user((void __user *)arg, &info, minsz) ?
717 			-EFAULT : 0;
718 
719 	} else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
720 		struct pci_dev *pdev = vdev->pdev;
721 		struct vfio_region_info info;
722 		struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
723 		int i, ret;
724 
725 		minsz = offsetofend(struct vfio_region_info, offset);
726 
727 		if (copy_from_user(&info, (void __user *)arg, minsz))
728 			return -EFAULT;
729 
730 		if (info.argsz < minsz)
731 			return -EINVAL;
732 
733 		switch (info.index) {
734 		case VFIO_PCI_CONFIG_REGION_INDEX:
735 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
736 			info.size = pdev->cfg_size;
737 			info.flags = VFIO_REGION_INFO_FLAG_READ |
738 				     VFIO_REGION_INFO_FLAG_WRITE;
739 			break;
740 		case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
741 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
742 			info.size = pci_resource_len(pdev, info.index);
743 			if (!info.size) {
744 				info.flags = 0;
745 				break;
746 			}
747 
748 			info.flags = VFIO_REGION_INFO_FLAG_READ |
749 				     VFIO_REGION_INFO_FLAG_WRITE;
750 			if (vdev->bar_mmap_supported[info.index]) {
751 				info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
752 				if (info.index == vdev->msix_bar) {
753 					ret = msix_mmappable_cap(vdev, &caps);
754 					if (ret)
755 						return ret;
756 				}
757 			}
758 
759 			break;
760 		case VFIO_PCI_ROM_REGION_INDEX:
761 		{
762 			void __iomem *io;
763 			size_t size;
764 			u16 orig_cmd;
765 
766 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
767 			info.flags = 0;
768 
769 			/* Report the BAR size, not the ROM size */
770 			info.size = pci_resource_len(pdev, info.index);
771 			if (!info.size) {
772 				/* Shadow ROMs appear as PCI option ROMs */
773 				if (pdev->resource[PCI_ROM_RESOURCE].flags &
774 							IORESOURCE_ROM_SHADOW)
775 					info.size = 0x20000;
776 				else
777 					break;
778 			}
779 
780 			/*
781 			 * Is it really there?  Enable memory decode for
782 			 * implicit access in pci_map_rom().
783 			 */
784 			pci_read_config_word(pdev, PCI_COMMAND, &orig_cmd);
785 			pci_write_config_word(pdev, PCI_COMMAND,
786 					      orig_cmd | PCI_COMMAND_MEMORY);
787 
788 			io = pci_map_rom(pdev, &size);
789 			if (io) {
790 				info.flags = VFIO_REGION_INFO_FLAG_READ;
791 				pci_unmap_rom(pdev, io);
792 			} else {
793 				info.size = 0;
794 			}
795 
796 			pci_write_config_word(pdev, PCI_COMMAND, orig_cmd);
797 			break;
798 		}
799 		case VFIO_PCI_VGA_REGION_INDEX:
800 			if (!vdev->has_vga)
801 				return -EINVAL;
802 
803 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
804 			info.size = 0xc0000;
805 			info.flags = VFIO_REGION_INFO_FLAG_READ |
806 				     VFIO_REGION_INFO_FLAG_WRITE;
807 
808 			break;
809 		default:
810 		{
811 			struct vfio_region_info_cap_type cap_type = {
812 					.header.id = VFIO_REGION_INFO_CAP_TYPE,
813 					.header.version = 1 };
814 
815 			if (info.index >=
816 			    VFIO_PCI_NUM_REGIONS + vdev->num_regions)
817 				return -EINVAL;
818 			info.index = array_index_nospec(info.index,
819 							VFIO_PCI_NUM_REGIONS +
820 							vdev->num_regions);
821 
822 			i = info.index - VFIO_PCI_NUM_REGIONS;
823 
824 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
825 			info.size = vdev->region[i].size;
826 			info.flags = vdev->region[i].flags;
827 
828 			cap_type.type = vdev->region[i].type;
829 			cap_type.subtype = vdev->region[i].subtype;
830 
831 			ret = vfio_info_add_capability(&caps, &cap_type.header,
832 						       sizeof(cap_type));
833 			if (ret)
834 				return ret;
835 
836 			if (vdev->region[i].ops->add_capability) {
837 				ret = vdev->region[i].ops->add_capability(vdev,
838 						&vdev->region[i], &caps);
839 				if (ret)
840 					return ret;
841 			}
842 		}
843 		}
844 
845 		if (caps.size) {
846 			info.flags |= VFIO_REGION_INFO_FLAG_CAPS;
847 			if (info.argsz < sizeof(info) + caps.size) {
848 				info.argsz = sizeof(info) + caps.size;
849 				info.cap_offset = 0;
850 			} else {
851 				vfio_info_cap_shift(&caps, sizeof(info));
852 				if (copy_to_user((void __user *)arg +
853 						  sizeof(info), caps.buf,
854 						  caps.size)) {
855 					kfree(caps.buf);
856 					return -EFAULT;
857 				}
858 				info.cap_offset = sizeof(info);
859 			}
860 
861 			kfree(caps.buf);
862 		}
863 
864 		return copy_to_user((void __user *)arg, &info, minsz) ?
865 			-EFAULT : 0;
866 
867 	} else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
868 		struct vfio_irq_info info;
869 
870 		minsz = offsetofend(struct vfio_irq_info, count);
871 
872 		if (copy_from_user(&info, (void __user *)arg, minsz))
873 			return -EFAULT;
874 
875 		if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
876 			return -EINVAL;
877 
878 		switch (info.index) {
879 		case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
880 		case VFIO_PCI_REQ_IRQ_INDEX:
881 			break;
882 		case VFIO_PCI_ERR_IRQ_INDEX:
883 			if (pci_is_pcie(vdev->pdev))
884 				break;
885 		/* fall through */
886 		default:
887 			return -EINVAL;
888 		}
889 
890 		info.flags = VFIO_IRQ_INFO_EVENTFD;
891 
892 		info.count = vfio_pci_get_irq_count(vdev, info.index);
893 
894 		if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
895 			info.flags |= (VFIO_IRQ_INFO_MASKABLE |
896 				       VFIO_IRQ_INFO_AUTOMASKED);
897 		else
898 			info.flags |= VFIO_IRQ_INFO_NORESIZE;
899 
900 		return copy_to_user((void __user *)arg, &info, minsz) ?
901 			-EFAULT : 0;
902 
903 	} else if (cmd == VFIO_DEVICE_SET_IRQS) {
904 		struct vfio_irq_set hdr;
905 		u8 *data = NULL;
906 		int max, ret = 0;
907 		size_t data_size = 0;
908 
909 		minsz = offsetofend(struct vfio_irq_set, count);
910 
911 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
912 			return -EFAULT;
913 
914 		max = vfio_pci_get_irq_count(vdev, hdr.index);
915 
916 		ret = vfio_set_irqs_validate_and_prepare(&hdr, max,
917 						 VFIO_PCI_NUM_IRQS, &data_size);
918 		if (ret)
919 			return ret;
920 
921 		if (data_size) {
922 			data = memdup_user((void __user *)(arg + minsz),
923 					    data_size);
924 			if (IS_ERR(data))
925 				return PTR_ERR(data);
926 		}
927 
928 		mutex_lock(&vdev->igate);
929 
930 		ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
931 					      hdr.start, hdr.count, data);
932 
933 		mutex_unlock(&vdev->igate);
934 		kfree(data);
935 
936 		return ret;
937 
938 	} else if (cmd == VFIO_DEVICE_RESET) {
939 		return vdev->reset_works ?
940 			pci_try_reset_function(vdev->pdev) : -EINVAL;
941 
942 	} else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
943 		struct vfio_pci_hot_reset_info hdr;
944 		struct vfio_pci_fill_info fill = { 0 };
945 		struct vfio_pci_dependent_device *devices = NULL;
946 		bool slot = false;
947 		int ret = 0;
948 
949 		minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
950 
951 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
952 			return -EFAULT;
953 
954 		if (hdr.argsz < minsz)
955 			return -EINVAL;
956 
957 		hdr.flags = 0;
958 
959 		/* Can we do a slot or bus reset or neither? */
960 		if (!pci_probe_reset_slot(vdev->pdev->slot))
961 			slot = true;
962 		else if (pci_probe_reset_bus(vdev->pdev->bus))
963 			return -ENODEV;
964 
965 		/* How many devices are affected? */
966 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
967 						    vfio_pci_count_devs,
968 						    &fill.max, slot);
969 		if (ret)
970 			return ret;
971 
972 		WARN_ON(!fill.max); /* Should always be at least one */
973 
974 		/*
975 		 * If there's enough space, fill it now, otherwise return
976 		 * -ENOSPC and the number of devices affected.
977 		 */
978 		if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
979 			ret = -ENOSPC;
980 			hdr.count = fill.max;
981 			goto reset_info_exit;
982 		}
983 
984 		devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
985 		if (!devices)
986 			return -ENOMEM;
987 
988 		fill.devices = devices;
989 
990 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
991 						    vfio_pci_fill_devs,
992 						    &fill, slot);
993 
994 		/*
995 		 * If a device was removed between counting and filling,
996 		 * we may come up short of fill.max.  If a device was
997 		 * added, we'll have a return of -EAGAIN above.
998 		 */
999 		if (!ret)
1000 			hdr.count = fill.cur;
1001 
1002 reset_info_exit:
1003 		if (copy_to_user((void __user *)arg, &hdr, minsz))
1004 			ret = -EFAULT;
1005 
1006 		if (!ret) {
1007 			if (copy_to_user((void __user *)(arg + minsz), devices,
1008 					 hdr.count * sizeof(*devices)))
1009 				ret = -EFAULT;
1010 		}
1011 
1012 		kfree(devices);
1013 		return ret;
1014 
1015 	} else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
1016 		struct vfio_pci_hot_reset hdr;
1017 		int32_t *group_fds;
1018 		struct vfio_pci_group_entry *groups;
1019 		struct vfio_pci_group_info info;
1020 		bool slot = false;
1021 		int i, count = 0, ret = 0;
1022 
1023 		minsz = offsetofend(struct vfio_pci_hot_reset, count);
1024 
1025 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
1026 			return -EFAULT;
1027 
1028 		if (hdr.argsz < minsz || hdr.flags)
1029 			return -EINVAL;
1030 
1031 		/* Can we do a slot or bus reset or neither? */
1032 		if (!pci_probe_reset_slot(vdev->pdev->slot))
1033 			slot = true;
1034 		else if (pci_probe_reset_bus(vdev->pdev->bus))
1035 			return -ENODEV;
1036 
1037 		/*
1038 		 * We can't let userspace give us an arbitrarily large
1039 		 * buffer to copy, so verify how many we think there
1040 		 * could be.  Note groups can have multiple devices so
1041 		 * one group per device is the max.
1042 		 */
1043 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1044 						    vfio_pci_count_devs,
1045 						    &count, slot);
1046 		if (ret)
1047 			return ret;
1048 
1049 		/* Somewhere between 1 and count is OK */
1050 		if (!hdr.count || hdr.count > count)
1051 			return -EINVAL;
1052 
1053 		group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
1054 		groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);
1055 		if (!group_fds || !groups) {
1056 			kfree(group_fds);
1057 			kfree(groups);
1058 			return -ENOMEM;
1059 		}
1060 
1061 		if (copy_from_user(group_fds, (void __user *)(arg + minsz),
1062 				   hdr.count * sizeof(*group_fds))) {
1063 			kfree(group_fds);
1064 			kfree(groups);
1065 			return -EFAULT;
1066 		}
1067 
1068 		/*
1069 		 * For each group_fd, get the group through the vfio external
1070 		 * user interface and store the group and iommu ID.  This
1071 		 * ensures the group is held across the reset.
1072 		 */
1073 		for (i = 0; i < hdr.count; i++) {
1074 			struct vfio_group *group;
1075 			struct fd f = fdget(group_fds[i]);
1076 			if (!f.file) {
1077 				ret = -EBADF;
1078 				break;
1079 			}
1080 
1081 			group = vfio_group_get_external_user(f.file);
1082 			fdput(f);
1083 			if (IS_ERR(group)) {
1084 				ret = PTR_ERR(group);
1085 				break;
1086 			}
1087 
1088 			groups[i].group = group;
1089 			groups[i].id = vfio_external_user_iommu_id(group);
1090 		}
1091 
1092 		kfree(group_fds);
1093 
1094 		/* release reference to groups on error */
1095 		if (ret)
1096 			goto hot_reset_release;
1097 
1098 		info.count = hdr.count;
1099 		info.groups = groups;
1100 
1101 		/*
1102 		 * Test whether all the affected devices are contained
1103 		 * by the set of groups provided by the user.
1104 		 */
1105 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1106 						    vfio_pci_validate_devs,
1107 						    &info, slot);
1108 		if (!ret)
1109 			/* User has access, do the reset */
1110 			ret = pci_reset_bus(vdev->pdev);
1111 
1112 hot_reset_release:
1113 		for (i--; i >= 0; i--)
1114 			vfio_group_put_external_user(groups[i].group);
1115 
1116 		kfree(groups);
1117 		return ret;
1118 	} else if (cmd == VFIO_DEVICE_IOEVENTFD) {
1119 		struct vfio_device_ioeventfd ioeventfd;
1120 		int count;
1121 
1122 		minsz = offsetofend(struct vfio_device_ioeventfd, fd);
1123 
1124 		if (copy_from_user(&ioeventfd, (void __user *)arg, minsz))
1125 			return -EFAULT;
1126 
1127 		if (ioeventfd.argsz < minsz)
1128 			return -EINVAL;
1129 
1130 		if (ioeventfd.flags & ~VFIO_DEVICE_IOEVENTFD_SIZE_MASK)
1131 			return -EINVAL;
1132 
1133 		count = ioeventfd.flags & VFIO_DEVICE_IOEVENTFD_SIZE_MASK;
1134 
1135 		if (hweight8(count) != 1 || ioeventfd.fd < -1)
1136 			return -EINVAL;
1137 
1138 		return vfio_pci_ioeventfd(vdev, ioeventfd.offset,
1139 					  ioeventfd.data, count, ioeventfd.fd);
1140 	}
1141 
1142 	return -ENOTTY;
1143 }
1144 
1145 static ssize_t vfio_pci_rw(void *device_data, char __user *buf,
1146 			   size_t count, loff_t *ppos, bool iswrite)
1147 {
1148 	unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
1149 	struct vfio_pci_device *vdev = device_data;
1150 
1151 	if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1152 		return -EINVAL;
1153 
1154 	switch (index) {
1155 	case VFIO_PCI_CONFIG_REGION_INDEX:
1156 		return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
1157 
1158 	case VFIO_PCI_ROM_REGION_INDEX:
1159 		if (iswrite)
1160 			return -EINVAL;
1161 		return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
1162 
1163 	case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
1164 		return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
1165 
1166 	case VFIO_PCI_VGA_REGION_INDEX:
1167 		return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
1168 	default:
1169 		index -= VFIO_PCI_NUM_REGIONS;
1170 		return vdev->region[index].ops->rw(vdev, buf,
1171 						   count, ppos, iswrite);
1172 	}
1173 
1174 	return -EINVAL;
1175 }
1176 
1177 static ssize_t vfio_pci_read(void *device_data, 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, buf, count, ppos, false);
1184 }
1185 
1186 static ssize_t vfio_pci_write(void *device_data, const char __user *buf,
1187 			      size_t count, loff_t *ppos)
1188 {
1189 	if (!count)
1190 		return 0;
1191 
1192 	return vfio_pci_rw(device_data, (char __user *)buf, count, ppos, true);
1193 }
1194 
1195 static int vfio_pci_mmap(void *device_data, struct vm_area_struct *vma)
1196 {
1197 	struct vfio_pci_device *vdev = device_data;
1198 	struct pci_dev *pdev = vdev->pdev;
1199 	unsigned int index;
1200 	u64 phys_len, req_len, pgoff, req_start;
1201 	int ret;
1202 
1203 	index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1204 
1205 	if (vma->vm_end < vma->vm_start)
1206 		return -EINVAL;
1207 	if ((vma->vm_flags & VM_SHARED) == 0)
1208 		return -EINVAL;
1209 	if (index >= VFIO_PCI_NUM_REGIONS) {
1210 		int regnum = index - VFIO_PCI_NUM_REGIONS;
1211 		struct vfio_pci_region *region = vdev->region + regnum;
1212 
1213 		if (region && region->ops && region->ops->mmap &&
1214 		    (region->flags & VFIO_REGION_INFO_FLAG_MMAP))
1215 			return region->ops->mmap(vdev, region, vma);
1216 		return -EINVAL;
1217 	}
1218 	if (index >= VFIO_PCI_ROM_REGION_INDEX)
1219 		return -EINVAL;
1220 	if (!vdev->bar_mmap_supported[index])
1221 		return -EINVAL;
1222 
1223 	phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1224 	req_len = vma->vm_end - vma->vm_start;
1225 	pgoff = vma->vm_pgoff &
1226 		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1227 	req_start = pgoff << PAGE_SHIFT;
1228 
1229 	if (req_start + req_len > phys_len)
1230 		return -EINVAL;
1231 
1232 	/*
1233 	 * Even though we don't make use of the barmap for the mmap,
1234 	 * we need to request the region and the barmap tracks that.
1235 	 */
1236 	if (!vdev->barmap[index]) {
1237 		ret = pci_request_selected_regions(pdev,
1238 						   1 << index, "vfio-pci");
1239 		if (ret)
1240 			return ret;
1241 
1242 		vdev->barmap[index] = pci_iomap(pdev, index, 0);
1243 		if (!vdev->barmap[index]) {
1244 			pci_release_selected_regions(pdev, 1 << index);
1245 			return -ENOMEM;
1246 		}
1247 	}
1248 
1249 	vma->vm_private_data = vdev;
1250 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1251 	vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
1252 
1253 	return remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
1254 			       req_len, vma->vm_page_prot);
1255 }
1256 
1257 static void vfio_pci_request(void *device_data, unsigned int count)
1258 {
1259 	struct vfio_pci_device *vdev = device_data;
1260 	struct pci_dev *pdev = vdev->pdev;
1261 
1262 	mutex_lock(&vdev->igate);
1263 
1264 	if (vdev->req_trigger) {
1265 		if (!(count % 10))
1266 			pci_notice_ratelimited(pdev,
1267 				"Relaying device request to user (#%u)\n",
1268 				count);
1269 		eventfd_signal(vdev->req_trigger, 1);
1270 	} else if (count == 0) {
1271 		pci_warn(pdev,
1272 			"No device request channel registered, blocked until released by user\n");
1273 	}
1274 
1275 	mutex_unlock(&vdev->igate);
1276 }
1277 
1278 static const struct vfio_device_ops vfio_pci_ops = {
1279 	.name		= "vfio-pci",
1280 	.open		= vfio_pci_open,
1281 	.release	= vfio_pci_release,
1282 	.ioctl		= vfio_pci_ioctl,
1283 	.read		= vfio_pci_read,
1284 	.write		= vfio_pci_write,
1285 	.mmap		= vfio_pci_mmap,
1286 	.request	= vfio_pci_request,
1287 };
1288 
1289 static int vfio_pci_reflck_attach(struct vfio_pci_device *vdev);
1290 static void vfio_pci_reflck_put(struct vfio_pci_reflck *reflck);
1291 
1292 static int vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1293 {
1294 	struct vfio_pci_device *vdev;
1295 	struct iommu_group *group;
1296 	int ret;
1297 
1298 	if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
1299 		return -EINVAL;
1300 
1301 	/*
1302 	 * Prevent binding to PFs with VFs enabled, this too easily allows
1303 	 * userspace instance with VFs and PFs from the same device, which
1304 	 * cannot work.  Disabling SR-IOV here would initiate removing the
1305 	 * VFs, which would unbind the driver, which is prone to blocking
1306 	 * if that VF is also in use by vfio-pci.  Just reject these PFs
1307 	 * and let the user sort it out.
1308 	 */
1309 	if (pci_num_vf(pdev)) {
1310 		pci_warn(pdev, "Cannot bind to PF with SR-IOV enabled\n");
1311 		return -EBUSY;
1312 	}
1313 
1314 	group = vfio_iommu_group_get(&pdev->dev);
1315 	if (!group)
1316 		return -EINVAL;
1317 
1318 	vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
1319 	if (!vdev) {
1320 		vfio_iommu_group_put(group, &pdev->dev);
1321 		return -ENOMEM;
1322 	}
1323 
1324 	vdev->pdev = pdev;
1325 	vdev->irq_type = VFIO_PCI_NUM_IRQS;
1326 	mutex_init(&vdev->igate);
1327 	spin_lock_init(&vdev->irqlock);
1328 	mutex_init(&vdev->ioeventfds_lock);
1329 	INIT_LIST_HEAD(&vdev->ioeventfds_list);
1330 
1331 	ret = vfio_add_group_dev(&pdev->dev, &vfio_pci_ops, vdev);
1332 	if (ret) {
1333 		vfio_iommu_group_put(group, &pdev->dev);
1334 		kfree(vdev);
1335 		return ret;
1336 	}
1337 
1338 	ret = vfio_pci_reflck_attach(vdev);
1339 	if (ret) {
1340 		vfio_del_group_dev(&pdev->dev);
1341 		vfio_iommu_group_put(group, &pdev->dev);
1342 		kfree(vdev);
1343 		return ret;
1344 	}
1345 
1346 	if (vfio_pci_is_vga(pdev)) {
1347 		vga_client_register(pdev, vdev, NULL, vfio_pci_set_vga_decode);
1348 		vga_set_legacy_decoding(pdev,
1349 					vfio_pci_set_vga_decode(vdev, false));
1350 	}
1351 
1352 	vfio_pci_probe_power_state(vdev);
1353 
1354 	if (!disable_idle_d3) {
1355 		/*
1356 		 * pci-core sets the device power state to an unknown value at
1357 		 * bootup and after being removed from a driver.  The only
1358 		 * transition it allows from this unknown state is to D0, which
1359 		 * typically happens when a driver calls pci_enable_device().
1360 		 * We're not ready to enable the device yet, but we do want to
1361 		 * be able to get to D3.  Therefore first do a D0 transition
1362 		 * before going to D3.
1363 		 */
1364 		vfio_pci_set_power_state(vdev, PCI_D0);
1365 		vfio_pci_set_power_state(vdev, PCI_D3hot);
1366 	}
1367 
1368 	return ret;
1369 }
1370 
1371 static void vfio_pci_remove(struct pci_dev *pdev)
1372 {
1373 	struct vfio_pci_device *vdev;
1374 
1375 	vdev = vfio_del_group_dev(&pdev->dev);
1376 	if (!vdev)
1377 		return;
1378 
1379 	vfio_pci_reflck_put(vdev->reflck);
1380 
1381 	vfio_iommu_group_put(pdev->dev.iommu_group, &pdev->dev);
1382 	kfree(vdev->region);
1383 	mutex_destroy(&vdev->ioeventfds_lock);
1384 
1385 	if (!disable_idle_d3)
1386 		vfio_pci_set_power_state(vdev, PCI_D0);
1387 
1388 	kfree(vdev->pm_save);
1389 	kfree(vdev);
1390 
1391 	if (vfio_pci_is_vga(pdev)) {
1392 		vga_client_register(pdev, NULL, NULL, NULL);
1393 		vga_set_legacy_decoding(pdev,
1394 				VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
1395 				VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM);
1396 	}
1397 }
1398 
1399 static pci_ers_result_t vfio_pci_aer_err_detected(struct pci_dev *pdev,
1400 						  pci_channel_state_t state)
1401 {
1402 	struct vfio_pci_device *vdev;
1403 	struct vfio_device *device;
1404 
1405 	device = vfio_device_get_from_dev(&pdev->dev);
1406 	if (device == NULL)
1407 		return PCI_ERS_RESULT_DISCONNECT;
1408 
1409 	vdev = vfio_device_data(device);
1410 	if (vdev == NULL) {
1411 		vfio_device_put(device);
1412 		return PCI_ERS_RESULT_DISCONNECT;
1413 	}
1414 
1415 	mutex_lock(&vdev->igate);
1416 
1417 	if (vdev->err_trigger)
1418 		eventfd_signal(vdev->err_trigger, 1);
1419 
1420 	mutex_unlock(&vdev->igate);
1421 
1422 	vfio_device_put(device);
1423 
1424 	return PCI_ERS_RESULT_CAN_RECOVER;
1425 }
1426 
1427 static const struct pci_error_handlers vfio_err_handlers = {
1428 	.error_detected = vfio_pci_aer_err_detected,
1429 };
1430 
1431 static struct pci_driver vfio_pci_driver = {
1432 	.name		= "vfio-pci",
1433 	.id_table	= NULL, /* only dynamic ids */
1434 	.probe		= vfio_pci_probe,
1435 	.remove		= vfio_pci_remove,
1436 	.err_handler	= &vfio_err_handlers,
1437 };
1438 
1439 static DEFINE_MUTEX(reflck_lock);
1440 
1441 static struct vfio_pci_reflck *vfio_pci_reflck_alloc(void)
1442 {
1443 	struct vfio_pci_reflck *reflck;
1444 
1445 	reflck = kzalloc(sizeof(*reflck), GFP_KERNEL);
1446 	if (!reflck)
1447 		return ERR_PTR(-ENOMEM);
1448 
1449 	kref_init(&reflck->kref);
1450 	mutex_init(&reflck->lock);
1451 
1452 	return reflck;
1453 }
1454 
1455 static void vfio_pci_reflck_get(struct vfio_pci_reflck *reflck)
1456 {
1457 	kref_get(&reflck->kref);
1458 }
1459 
1460 static int vfio_pci_reflck_find(struct pci_dev *pdev, void *data)
1461 {
1462 	struct vfio_pci_reflck **preflck = data;
1463 	struct vfio_device *device;
1464 	struct vfio_pci_device *vdev;
1465 
1466 	device = vfio_device_get_from_dev(&pdev->dev);
1467 	if (!device)
1468 		return 0;
1469 
1470 	if (pci_dev_driver(pdev) != &vfio_pci_driver) {
1471 		vfio_device_put(device);
1472 		return 0;
1473 	}
1474 
1475 	vdev = vfio_device_data(device);
1476 
1477 	if (vdev->reflck) {
1478 		vfio_pci_reflck_get(vdev->reflck);
1479 		*preflck = vdev->reflck;
1480 		vfio_device_put(device);
1481 		return 1;
1482 	}
1483 
1484 	vfio_device_put(device);
1485 	return 0;
1486 }
1487 
1488 static int vfio_pci_reflck_attach(struct vfio_pci_device *vdev)
1489 {
1490 	bool slot = !pci_probe_reset_slot(vdev->pdev->slot);
1491 
1492 	mutex_lock(&reflck_lock);
1493 
1494 	if (pci_is_root_bus(vdev->pdev->bus) ||
1495 	    vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_reflck_find,
1496 					  &vdev->reflck, slot) <= 0)
1497 		vdev->reflck = vfio_pci_reflck_alloc();
1498 
1499 	mutex_unlock(&reflck_lock);
1500 
1501 	return PTR_ERR_OR_ZERO(vdev->reflck);
1502 }
1503 
1504 static void vfio_pci_reflck_release(struct kref *kref)
1505 {
1506 	struct vfio_pci_reflck *reflck = container_of(kref,
1507 						      struct vfio_pci_reflck,
1508 						      kref);
1509 
1510 	kfree(reflck);
1511 	mutex_unlock(&reflck_lock);
1512 }
1513 
1514 static void vfio_pci_reflck_put(struct vfio_pci_reflck *reflck)
1515 {
1516 	kref_put_mutex(&reflck->kref, vfio_pci_reflck_release, &reflck_lock);
1517 }
1518 
1519 struct vfio_devices {
1520 	struct vfio_device **devices;
1521 	int cur_index;
1522 	int max_index;
1523 };
1524 
1525 static int vfio_pci_get_unused_devs(struct pci_dev *pdev, void *data)
1526 {
1527 	struct vfio_devices *devs = data;
1528 	struct vfio_device *device;
1529 	struct vfio_pci_device *vdev;
1530 
1531 	if (devs->cur_index == devs->max_index)
1532 		return -ENOSPC;
1533 
1534 	device = vfio_device_get_from_dev(&pdev->dev);
1535 	if (!device)
1536 		return -EINVAL;
1537 
1538 	if (pci_dev_driver(pdev) != &vfio_pci_driver) {
1539 		vfio_device_put(device);
1540 		return -EBUSY;
1541 	}
1542 
1543 	vdev = vfio_device_data(device);
1544 
1545 	/* Fault if the device is not unused */
1546 	if (vdev->refcnt) {
1547 		vfio_device_put(device);
1548 		return -EBUSY;
1549 	}
1550 
1551 	devs->devices[devs->cur_index++] = device;
1552 	return 0;
1553 }
1554 
1555 /*
1556  * If a bus or slot reset is available for the provided device and:
1557  *  - All of the devices affected by that bus or slot reset are unused
1558  *    (!refcnt)
1559  *  - At least one of the affected devices is marked dirty via
1560  *    needs_reset (such as by lack of FLR support)
1561  * Then attempt to perform that bus or slot reset.  Callers are required
1562  * to hold vdev->reflck->lock, protecting the bus/slot reset group from
1563  * concurrent opens.  A vfio_device reference is acquired for each device
1564  * to prevent unbinds during the reset operation.
1565  *
1566  * NB: vfio-core considers a group to be viable even if some devices are
1567  * bound to drivers like pci-stub or pcieport.  Here we require all devices
1568  * to be bound to vfio_pci since that's the only way we can be sure they
1569  * stay put.
1570  */
1571 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev)
1572 {
1573 	struct vfio_devices devs = { .cur_index = 0 };
1574 	int i = 0, ret = -EINVAL;
1575 	bool slot = false;
1576 	struct vfio_pci_device *tmp;
1577 
1578 	if (!pci_probe_reset_slot(vdev->pdev->slot))
1579 		slot = true;
1580 	else if (pci_probe_reset_bus(vdev->pdev->bus))
1581 		return;
1582 
1583 	if (vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
1584 					  &i, slot) || !i)
1585 		return;
1586 
1587 	devs.max_index = i;
1588 	devs.devices = kcalloc(i, sizeof(struct vfio_device *), GFP_KERNEL);
1589 	if (!devs.devices)
1590 		return;
1591 
1592 	if (vfio_pci_for_each_slot_or_bus(vdev->pdev,
1593 					  vfio_pci_get_unused_devs,
1594 					  &devs, slot))
1595 		goto put_devs;
1596 
1597 	/* Does at least one need a reset? */
1598 	for (i = 0; i < devs.cur_index; i++) {
1599 		tmp = vfio_device_data(devs.devices[i]);
1600 		if (tmp->needs_reset) {
1601 			ret = pci_reset_bus(vdev->pdev);
1602 			break;
1603 		}
1604 	}
1605 
1606 put_devs:
1607 	for (i = 0; i < devs.cur_index; i++) {
1608 		tmp = vfio_device_data(devs.devices[i]);
1609 
1610 		/*
1611 		 * If reset was successful, affected devices no longer need
1612 		 * a reset and we should return all the collateral devices
1613 		 * to low power.  If not successful, we either didn't reset
1614 		 * the bus or timed out waiting for it, so let's not touch
1615 		 * the power state.
1616 		 */
1617 		if (!ret) {
1618 			tmp->needs_reset = false;
1619 
1620 			if (tmp != vdev && !disable_idle_d3)
1621 				vfio_pci_set_power_state(tmp, PCI_D3hot);
1622 		}
1623 
1624 		vfio_device_put(devs.devices[i]);
1625 	}
1626 
1627 	kfree(devs.devices);
1628 }
1629 
1630 static void __exit vfio_pci_cleanup(void)
1631 {
1632 	pci_unregister_driver(&vfio_pci_driver);
1633 	vfio_pci_uninit_perm_bits();
1634 }
1635 
1636 static void __init vfio_pci_fill_ids(void)
1637 {
1638 	char *p, *id;
1639 	int rc;
1640 
1641 	/* no ids passed actually */
1642 	if (ids[0] == '\0')
1643 		return;
1644 
1645 	/* add ids specified in the module parameter */
1646 	p = ids;
1647 	while ((id = strsep(&p, ","))) {
1648 		unsigned int vendor, device, subvendor = PCI_ANY_ID,
1649 			subdevice = PCI_ANY_ID, class = 0, class_mask = 0;
1650 		int fields;
1651 
1652 		if (!strlen(id))
1653 			continue;
1654 
1655 		fields = sscanf(id, "%x:%x:%x:%x:%x:%x",
1656 				&vendor, &device, &subvendor, &subdevice,
1657 				&class, &class_mask);
1658 
1659 		if (fields < 2) {
1660 			pr_warn("invalid id string \"%s\"\n", id);
1661 			continue;
1662 		}
1663 
1664 		rc = pci_add_dynid(&vfio_pci_driver, vendor, device,
1665 				   subvendor, subdevice, class, class_mask, 0);
1666 		if (rc)
1667 			pr_warn("failed to add dynamic id [%04x:%04x[%04x:%04x]] class %#08x/%08x (%d)\n",
1668 				vendor, device, subvendor, subdevice,
1669 				class, class_mask, rc);
1670 		else
1671 			pr_info("add [%04x:%04x[%04x:%04x]] class %#08x/%08x\n",
1672 				vendor, device, subvendor, subdevice,
1673 				class, class_mask);
1674 	}
1675 }
1676 
1677 static int __init vfio_pci_init(void)
1678 {
1679 	int ret;
1680 
1681 	/* Allocate shared config space permision data used by all devices */
1682 	ret = vfio_pci_init_perm_bits();
1683 	if (ret)
1684 		return ret;
1685 
1686 	/* Register and scan for devices */
1687 	ret = pci_register_driver(&vfio_pci_driver);
1688 	if (ret)
1689 		goto out_driver;
1690 
1691 	vfio_pci_fill_ids();
1692 
1693 	return 0;
1694 
1695 out_driver:
1696 	vfio_pci_uninit_perm_bits();
1697 	return ret;
1698 }
1699 
1700 module_init(vfio_pci_init);
1701 module_exit(vfio_pci_cleanup);
1702 
1703 MODULE_VERSION(DRIVER_VERSION);
1704 MODULE_LICENSE("GPL v2");
1705 MODULE_AUTHOR(DRIVER_AUTHOR);
1706 MODULE_DESCRIPTION(DRIVER_DESC);
1707