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