xref: /linux/drivers/vfio/pci/vfio_pci_core.c (revision 0074281bb6316108e0cff094bd4db78ab3eee236)
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 
13 #include <linux/aperture.h>
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/vgaarb.h>
28 #include <linux/nospec.h>
29 #include <linux/sched/mm.h>
30 #include <linux/iommufd.h>
31 #if IS_ENABLED(CONFIG_EEH)
32 #include <asm/eeh.h>
33 #endif
34 
35 #include "vfio_pci_priv.h"
36 
37 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
38 #define DRIVER_DESC "core driver for VFIO based PCI devices"
39 
40 static bool nointxmask;
41 static bool disable_vga;
42 static bool disable_idle_d3;
43 
44 /* List of PF's that vfio_pci_core_sriov_configure() has been called on */
45 static DEFINE_MUTEX(vfio_pci_sriov_pfs_mutex);
46 static LIST_HEAD(vfio_pci_sriov_pfs);
47 
48 struct vfio_pci_dummy_resource {
49 	struct resource		resource;
50 	int			index;
51 	struct list_head	res_next;
52 };
53 
54 struct vfio_pci_vf_token {
55 	struct mutex		lock;
56 	uuid_t			uuid;
57 	int			users;
58 };
59 
vfio_vga_disabled(void)60 static inline bool vfio_vga_disabled(void)
61 {
62 #ifdef CONFIG_VFIO_PCI_VGA
63 	return disable_vga;
64 #else
65 	return true;
66 #endif
67 }
68 
69 /*
70  * Our VGA arbiter participation is limited since we don't know anything
71  * about the device itself.  However, if the device is the only VGA device
72  * downstream of a bridge and VFIO VGA support is disabled, then we can
73  * safely return legacy VGA IO and memory as not decoded since the user
74  * has no way to get to it and routing can be disabled externally at the
75  * bridge.
76  */
vfio_pci_set_decode(struct pci_dev * pdev,bool single_vga)77 static unsigned int vfio_pci_set_decode(struct pci_dev *pdev, bool single_vga)
78 {
79 	struct pci_dev *tmp = NULL;
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 
vfio_pci_probe_mmaps(struct vfio_pci_core_device * vdev)107 static void vfio_pci_probe_mmaps(struct vfio_pci_core_device *vdev)
108 {
109 	struct resource *res;
110 	int i;
111 	struct vfio_pci_dummy_resource *dummy_res;
112 
113 	for (i = 0; i < PCI_STD_NUM_BARS; i++) {
114 		int bar = i + PCI_STD_RESOURCES;
115 
116 		res = &vdev->pdev->resource[bar];
117 
118 		if (vdev->pdev->non_mappable_bars)
119 			goto no_mmap;
120 
121 		if (!(res->flags & IORESOURCE_MEM))
122 			goto no_mmap;
123 
124 		/*
125 		 * The PCI core shouldn't set up a resource with a
126 		 * type but zero size. But there may be bugs that
127 		 * cause us to do that.
128 		 */
129 		if (!resource_size(res))
130 			goto no_mmap;
131 
132 		if (resource_size(res) >= PAGE_SIZE) {
133 			vdev->bar_mmap_supported[bar] = true;
134 			continue;
135 		}
136 
137 		if (!(res->start & ~PAGE_MASK)) {
138 			/*
139 			 * Add a dummy resource to reserve the remainder
140 			 * of the exclusive page in case that hot-add
141 			 * device's bar is assigned into it.
142 			 */
143 			dummy_res =
144 				kzalloc(sizeof(*dummy_res), GFP_KERNEL_ACCOUNT);
145 			if (dummy_res == NULL)
146 				goto no_mmap;
147 
148 			dummy_res->resource.name = "vfio sub-page reserved";
149 			dummy_res->resource.start = res->end + 1;
150 			dummy_res->resource.end = res->start + PAGE_SIZE - 1;
151 			dummy_res->resource.flags = res->flags;
152 			if (request_resource(res->parent,
153 						&dummy_res->resource)) {
154 				kfree(dummy_res);
155 				goto no_mmap;
156 			}
157 			dummy_res->index = bar;
158 			list_add(&dummy_res->res_next,
159 					&vdev->dummy_resources_list);
160 			vdev->bar_mmap_supported[bar] = true;
161 			continue;
162 		}
163 		/*
164 		 * Here we don't handle the case when the BAR is not page
165 		 * aligned because we can't expect the BAR will be
166 		 * assigned into the same location in a page in guest
167 		 * when we passthrough the BAR. And it's hard to access
168 		 * this BAR in userspace because we have no way to get
169 		 * the BAR's location in a page.
170 		 */
171 no_mmap:
172 		vdev->bar_mmap_supported[bar] = false;
173 	}
174 }
175 
176 struct vfio_pci_group_info;
177 static void vfio_pci_dev_set_try_reset(struct vfio_device_set *dev_set);
178 static int vfio_pci_dev_set_hot_reset(struct vfio_device_set *dev_set,
179 				      struct vfio_pci_group_info *groups,
180 				      struct iommufd_ctx *iommufd_ctx);
181 
182 /*
183  * INTx masking requires the ability to disable INTx signaling via PCI_COMMAND
184  * _and_ the ability detect when the device is asserting INTx via PCI_STATUS.
185  * If a device implements the former but not the latter we would typically
186  * expect broken_intx_masking be set and require an exclusive interrupt.
187  * However since we do have control of the device's ability to assert INTx,
188  * we can instead pretend that the device does not implement INTx, virtualizing
189  * the pin register to report zero and maintaining DisINTx set on the host.
190  */
vfio_pci_nointx(struct pci_dev * pdev)191 static bool vfio_pci_nointx(struct pci_dev *pdev)
192 {
193 	switch (pdev->vendor) {
194 	case PCI_VENDOR_ID_INTEL:
195 		switch (pdev->device) {
196 		/* All i40e (XL710/X710/XXV710) 10/20/25/40GbE NICs */
197 		case 0x1572:
198 		case 0x1574:
199 		case 0x1580 ... 0x1581:
200 		case 0x1583 ... 0x158b:
201 		case 0x37d0 ... 0x37d2:
202 		/* X550 */
203 		case 0x1563:
204 			return true;
205 		default:
206 			return false;
207 		}
208 	}
209 
210 	return false;
211 }
212 
vfio_pci_probe_power_state(struct vfio_pci_core_device * vdev)213 static void vfio_pci_probe_power_state(struct vfio_pci_core_device *vdev)
214 {
215 	struct pci_dev *pdev = vdev->pdev;
216 	u16 pmcsr;
217 
218 	if (!pdev->pm_cap)
219 		return;
220 
221 	pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmcsr);
222 
223 	vdev->needs_pm_restore = !(pmcsr & PCI_PM_CTRL_NO_SOFT_RESET);
224 }
225 
226 /*
227  * pci_set_power_state() wrapper handling devices which perform a soft reset on
228  * D3->D0 transition.  Save state prior to D0/1/2->D3, stash it on the vdev,
229  * restore when returned to D0.  Saved separately from pci_saved_state for use
230  * by PM capability emulation and separately from pci_dev internal saved state
231  * to avoid it being overwritten and consumed around other resets.
232  */
vfio_pci_set_power_state(struct vfio_pci_core_device * vdev,pci_power_t state)233 int vfio_pci_set_power_state(struct vfio_pci_core_device *vdev, pci_power_t state)
234 {
235 	struct pci_dev *pdev = vdev->pdev;
236 	bool needs_restore = false, needs_save = false;
237 	int ret;
238 
239 	/* Prevent changing power state for PFs with VFs enabled */
240 	if (pci_num_vf(pdev) && state > PCI_D0)
241 		return -EBUSY;
242 
243 	if (vdev->needs_pm_restore) {
244 		if (pdev->current_state < PCI_D3hot && state >= PCI_D3hot) {
245 			pci_save_state(pdev);
246 			needs_save = true;
247 		}
248 
249 		if (pdev->current_state >= PCI_D3hot && state <= PCI_D0)
250 			needs_restore = true;
251 	}
252 
253 	ret = pci_set_power_state(pdev, state);
254 
255 	if (!ret) {
256 		/* D3 might be unsupported via quirk, skip unless in D3 */
257 		if (needs_save && pdev->current_state >= PCI_D3hot) {
258 			/*
259 			 * The current PCI state will be saved locally in
260 			 * 'pm_save' during the D3hot transition. When the
261 			 * device state is changed to D0 again with the current
262 			 * function, then pci_store_saved_state() will restore
263 			 * the state and will free the memory pointed by
264 			 * 'pm_save'. There are few cases where the PCI power
265 			 * state can be changed to D0 without the involvement
266 			 * of the driver. For these cases, free the earlier
267 			 * allocated memory first before overwriting 'pm_save'
268 			 * to prevent the memory leak.
269 			 */
270 			kfree(vdev->pm_save);
271 			vdev->pm_save = pci_store_saved_state(pdev);
272 		} else if (needs_restore) {
273 			pci_load_and_free_saved_state(pdev, &vdev->pm_save);
274 			pci_restore_state(pdev);
275 		}
276 	}
277 
278 	return ret;
279 }
280 
vfio_pci_runtime_pm_entry(struct vfio_pci_core_device * vdev,struct eventfd_ctx * efdctx)281 static int vfio_pci_runtime_pm_entry(struct vfio_pci_core_device *vdev,
282 				     struct eventfd_ctx *efdctx)
283 {
284 	/*
285 	 * The vdev power related flags are protected with 'memory_lock'
286 	 * semaphore.
287 	 */
288 	vfio_pci_zap_and_down_write_memory_lock(vdev);
289 	if (vdev->pm_runtime_engaged) {
290 		up_write(&vdev->memory_lock);
291 		return -EINVAL;
292 	}
293 
294 	vdev->pm_runtime_engaged = true;
295 	vdev->pm_wake_eventfd_ctx = efdctx;
296 	pm_runtime_put_noidle(&vdev->pdev->dev);
297 	up_write(&vdev->memory_lock);
298 
299 	return 0;
300 }
301 
vfio_pci_core_pm_entry(struct vfio_device * device,u32 flags,void __user * arg,size_t argsz)302 static int vfio_pci_core_pm_entry(struct vfio_device *device, u32 flags,
303 				  void __user *arg, size_t argsz)
304 {
305 	struct vfio_pci_core_device *vdev =
306 		container_of(device, struct vfio_pci_core_device, vdev);
307 	int ret;
308 
309 	ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_SET, 0);
310 	if (ret != 1)
311 		return ret;
312 
313 	/*
314 	 * Inside vfio_pci_runtime_pm_entry(), only the runtime PM usage count
315 	 * will be decremented. The pm_runtime_put() will be invoked again
316 	 * while returning from the ioctl and then the device can go into
317 	 * runtime suspended state.
318 	 */
319 	return vfio_pci_runtime_pm_entry(vdev, NULL);
320 }
321 
vfio_pci_core_pm_entry_with_wakeup(struct vfio_device * device,u32 flags,struct vfio_device_low_power_entry_with_wakeup __user * arg,size_t argsz)322 static int vfio_pci_core_pm_entry_with_wakeup(
323 	struct vfio_device *device, u32 flags,
324 	struct vfio_device_low_power_entry_with_wakeup __user *arg,
325 	size_t argsz)
326 {
327 	struct vfio_pci_core_device *vdev =
328 		container_of(device, struct vfio_pci_core_device, vdev);
329 	struct vfio_device_low_power_entry_with_wakeup entry;
330 	struct eventfd_ctx *efdctx;
331 	int ret;
332 
333 	ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_SET,
334 				 sizeof(entry));
335 	if (ret != 1)
336 		return ret;
337 
338 	if (copy_from_user(&entry, arg, sizeof(entry)))
339 		return -EFAULT;
340 
341 	if (entry.wakeup_eventfd < 0)
342 		return -EINVAL;
343 
344 	efdctx = eventfd_ctx_fdget(entry.wakeup_eventfd);
345 	if (IS_ERR(efdctx))
346 		return PTR_ERR(efdctx);
347 
348 	ret = vfio_pci_runtime_pm_entry(vdev, efdctx);
349 	if (ret)
350 		eventfd_ctx_put(efdctx);
351 
352 	return ret;
353 }
354 
__vfio_pci_runtime_pm_exit(struct vfio_pci_core_device * vdev)355 static void __vfio_pci_runtime_pm_exit(struct vfio_pci_core_device *vdev)
356 {
357 	if (vdev->pm_runtime_engaged) {
358 		vdev->pm_runtime_engaged = false;
359 		pm_runtime_get_noresume(&vdev->pdev->dev);
360 
361 		if (vdev->pm_wake_eventfd_ctx) {
362 			eventfd_ctx_put(vdev->pm_wake_eventfd_ctx);
363 			vdev->pm_wake_eventfd_ctx = NULL;
364 		}
365 	}
366 }
367 
vfio_pci_runtime_pm_exit(struct vfio_pci_core_device * vdev)368 static void vfio_pci_runtime_pm_exit(struct vfio_pci_core_device *vdev)
369 {
370 	/*
371 	 * The vdev power related flags are protected with 'memory_lock'
372 	 * semaphore.
373 	 */
374 	down_write(&vdev->memory_lock);
375 	__vfio_pci_runtime_pm_exit(vdev);
376 	up_write(&vdev->memory_lock);
377 }
378 
vfio_pci_core_pm_exit(struct vfio_device * device,u32 flags,void __user * arg,size_t argsz)379 static int vfio_pci_core_pm_exit(struct vfio_device *device, u32 flags,
380 				 void __user *arg, size_t argsz)
381 {
382 	struct vfio_pci_core_device *vdev =
383 		container_of(device, struct vfio_pci_core_device, vdev);
384 	int ret;
385 
386 	ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_SET, 0);
387 	if (ret != 1)
388 		return ret;
389 
390 	/*
391 	 * The device is always in the active state here due to pm wrappers
392 	 * around ioctls. If the device had entered a low power state and
393 	 * pm_wake_eventfd_ctx is valid, vfio_pci_core_runtime_resume() has
394 	 * already signaled the eventfd and exited low power mode itself.
395 	 * pm_runtime_engaged protects the redundant call here.
396 	 */
397 	vfio_pci_runtime_pm_exit(vdev);
398 	return 0;
399 }
400 
401 #ifdef CONFIG_PM
vfio_pci_core_runtime_suspend(struct device * dev)402 static int vfio_pci_core_runtime_suspend(struct device *dev)
403 {
404 	struct vfio_pci_core_device *vdev = dev_get_drvdata(dev);
405 
406 	down_write(&vdev->memory_lock);
407 	/*
408 	 * The user can move the device into D3hot state before invoking
409 	 * power management IOCTL. Move the device into D0 state here and then
410 	 * the pci-driver core runtime PM suspend function will move the device
411 	 * into the low power state. Also, for the devices which have
412 	 * NoSoftRst-, it will help in restoring the original state
413 	 * (saved locally in 'vdev->pm_save').
414 	 */
415 	vfio_pci_set_power_state(vdev, PCI_D0);
416 	up_write(&vdev->memory_lock);
417 
418 	/*
419 	 * If INTx is enabled, then mask INTx before going into the runtime
420 	 * suspended state and unmask the same in the runtime resume.
421 	 * If INTx has already been masked by the user, then
422 	 * vfio_pci_intx_mask() will return false and in that case, INTx
423 	 * should not be unmasked in the runtime resume.
424 	 */
425 	vdev->pm_intx_masked = ((vdev->irq_type == VFIO_PCI_INTX_IRQ_INDEX) &&
426 				vfio_pci_intx_mask(vdev));
427 
428 	return 0;
429 }
430 
vfio_pci_core_runtime_resume(struct device * dev)431 static int vfio_pci_core_runtime_resume(struct device *dev)
432 {
433 	struct vfio_pci_core_device *vdev = dev_get_drvdata(dev);
434 
435 	/*
436 	 * Resume with a pm_wake_eventfd_ctx signals the eventfd and exit
437 	 * low power mode.
438 	 */
439 	down_write(&vdev->memory_lock);
440 	if (vdev->pm_wake_eventfd_ctx) {
441 		eventfd_signal(vdev->pm_wake_eventfd_ctx);
442 		__vfio_pci_runtime_pm_exit(vdev);
443 	}
444 	up_write(&vdev->memory_lock);
445 
446 	if (vdev->pm_intx_masked)
447 		vfio_pci_intx_unmask(vdev);
448 
449 	return 0;
450 }
451 #endif /* CONFIG_PM */
452 
453 /*
454  * The pci-driver core runtime PM routines always save the device state
455  * before going into suspended state. If the device is going into low power
456  * state with only with runtime PM ops, then no explicit handling is needed
457  * for the devices which have NoSoftRst-.
458  */
459 static const struct dev_pm_ops vfio_pci_core_pm_ops = {
460 	SET_RUNTIME_PM_OPS(vfio_pci_core_runtime_suspend,
461 			   vfio_pci_core_runtime_resume,
462 			   NULL)
463 };
464 
vfio_pci_core_enable(struct vfio_pci_core_device * vdev)465 int vfio_pci_core_enable(struct vfio_pci_core_device *vdev)
466 {
467 	struct pci_dev *pdev = vdev->pdev;
468 	int ret;
469 	u16 cmd;
470 	u8 msix_pos;
471 
472 	if (!disable_idle_d3) {
473 		ret = pm_runtime_resume_and_get(&pdev->dev);
474 		if (ret < 0)
475 			return ret;
476 	}
477 
478 	/* Don't allow our initial saved state to include busmaster */
479 	pci_clear_master(pdev);
480 
481 	ret = pci_enable_device(pdev);
482 	if (ret)
483 		goto out_power;
484 
485 	/* If reset fails because of the device lock, fail this path entirely */
486 	ret = pci_try_reset_function(pdev);
487 	if (ret == -EAGAIN)
488 		goto out_disable_device;
489 
490 	vdev->reset_works = !ret;
491 	pci_save_state(pdev);
492 	vdev->pci_saved_state = pci_store_saved_state(pdev);
493 	if (!vdev->pci_saved_state)
494 		pci_dbg(pdev, "%s: Couldn't store saved state\n", __func__);
495 
496 	if (likely(!nointxmask)) {
497 		if (vfio_pci_nointx(pdev)) {
498 			pci_info(pdev, "Masking broken INTx support\n");
499 			vdev->nointx = true;
500 			pci_intx(pdev, 0);
501 		} else
502 			vdev->pci_2_3 = pci_intx_mask_supported(pdev);
503 	}
504 
505 	pci_read_config_word(pdev, PCI_COMMAND, &cmd);
506 	if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
507 		cmd &= ~PCI_COMMAND_INTX_DISABLE;
508 		pci_write_config_word(pdev, PCI_COMMAND, cmd);
509 	}
510 
511 	ret = vfio_pci_zdev_open_device(vdev);
512 	if (ret)
513 		goto out_free_state;
514 
515 	ret = vfio_config_init(vdev);
516 	if (ret)
517 		goto out_free_zdev;
518 
519 	msix_pos = pdev->msix_cap;
520 	if (msix_pos) {
521 		u16 flags;
522 		u32 table;
523 
524 		pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
525 		pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
526 
527 		vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
528 		vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
529 		vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
530 		vdev->has_dyn_msix = pci_msix_can_alloc_dyn(pdev);
531 	} else {
532 		vdev->msix_bar = 0xFF;
533 		vdev->has_dyn_msix = false;
534 	}
535 
536 	if (!vfio_vga_disabled() && vfio_pci_is_vga(pdev))
537 		vdev->has_vga = true;
538 
539 
540 	return 0;
541 
542 out_free_zdev:
543 	vfio_pci_zdev_close_device(vdev);
544 out_free_state:
545 	kfree(vdev->pci_saved_state);
546 	vdev->pci_saved_state = NULL;
547 out_disable_device:
548 	pci_disable_device(pdev);
549 out_power:
550 	if (!disable_idle_d3)
551 		pm_runtime_put(&pdev->dev);
552 	return ret;
553 }
554 EXPORT_SYMBOL_GPL(vfio_pci_core_enable);
555 
vfio_pci_core_disable(struct vfio_pci_core_device * vdev)556 void vfio_pci_core_disable(struct vfio_pci_core_device *vdev)
557 {
558 	struct pci_dev *pdev = vdev->pdev;
559 	struct vfio_pci_dummy_resource *dummy_res, *tmp;
560 	struct vfio_pci_ioeventfd *ioeventfd, *ioeventfd_tmp;
561 	int i, bar;
562 
563 	/* For needs_reset */
564 	lockdep_assert_held(&vdev->vdev.dev_set->lock);
565 
566 	/*
567 	 * This function can be invoked while the power state is non-D0.
568 	 * This non-D0 power state can be with or without runtime PM.
569 	 * vfio_pci_runtime_pm_exit() will internally increment the usage
570 	 * count corresponding to pm_runtime_put() called during low power
571 	 * feature entry and then pm_runtime_resume() will wake up the device,
572 	 * if the device has already gone into the suspended state. Otherwise,
573 	 * the vfio_pci_set_power_state() will change the device power state
574 	 * to D0.
575 	 */
576 	vfio_pci_runtime_pm_exit(vdev);
577 	pm_runtime_resume(&pdev->dev);
578 
579 	/*
580 	 * This function calls __pci_reset_function_locked() which internally
581 	 * can use pci_pm_reset() for the function reset. pci_pm_reset() will
582 	 * fail if the power state is non-D0. Also, for the devices which
583 	 * have NoSoftRst-, the reset function can cause the PCI config space
584 	 * reset without restoring the original state (saved locally in
585 	 * 'vdev->pm_save').
586 	 */
587 	vfio_pci_set_power_state(vdev, PCI_D0);
588 
589 	/* Stop the device from further DMA */
590 	pci_clear_master(pdev);
591 
592 	vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
593 				VFIO_IRQ_SET_ACTION_TRIGGER,
594 				vdev->irq_type, 0, 0, NULL);
595 
596 	/* Device closed, don't need mutex here */
597 	list_for_each_entry_safe(ioeventfd, ioeventfd_tmp,
598 				 &vdev->ioeventfds_list, next) {
599 		vfio_virqfd_disable(&ioeventfd->virqfd);
600 		list_del(&ioeventfd->next);
601 		kfree(ioeventfd);
602 	}
603 	vdev->ioeventfds_nr = 0;
604 
605 	vdev->virq_disabled = false;
606 
607 	for (i = 0; i < vdev->num_regions; i++)
608 		vdev->region[i].ops->release(vdev, &vdev->region[i]);
609 
610 	vdev->num_regions = 0;
611 	kfree(vdev->region);
612 	vdev->region = NULL; /* don't krealloc a freed pointer */
613 
614 	vfio_config_free(vdev);
615 
616 	for (i = 0; i < PCI_STD_NUM_BARS; i++) {
617 		bar = i + PCI_STD_RESOURCES;
618 		if (!vdev->barmap[bar])
619 			continue;
620 		pci_iounmap(pdev, vdev->barmap[bar]);
621 		pci_release_selected_regions(pdev, 1 << bar);
622 		vdev->barmap[bar] = NULL;
623 	}
624 
625 	list_for_each_entry_safe(dummy_res, tmp,
626 				 &vdev->dummy_resources_list, res_next) {
627 		list_del(&dummy_res->res_next);
628 		release_resource(&dummy_res->resource);
629 		kfree(dummy_res);
630 	}
631 
632 	vdev->needs_reset = true;
633 
634 	vfio_pci_zdev_close_device(vdev);
635 
636 	/*
637 	 * If we have saved state, restore it.  If we can reset the device,
638 	 * even better.  Resetting with current state seems better than
639 	 * nothing, but saving and restoring current state without reset
640 	 * is just busy work.
641 	 */
642 	if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
643 		pci_info(pdev, "%s: Couldn't reload saved state\n", __func__);
644 
645 		if (!vdev->reset_works)
646 			goto out;
647 
648 		pci_save_state(pdev);
649 	}
650 
651 	/*
652 	 * Disable INTx and MSI, presumably to avoid spurious interrupts
653 	 * during reset.  Stolen from pci_reset_function()
654 	 */
655 	pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
656 
657 	/*
658 	 * Try to get the locks ourselves to prevent a deadlock. The
659 	 * success of this is dependent on being able to lock the device,
660 	 * which is not always possible.
661 	 * We can not use the "try" reset interface here, which will
662 	 * overwrite the previously restored configuration information.
663 	 */
664 	if (vdev->reset_works && pci_dev_trylock(pdev)) {
665 		if (!__pci_reset_function_locked(pdev))
666 			vdev->needs_reset = false;
667 		pci_dev_unlock(pdev);
668 	}
669 
670 	pci_restore_state(pdev);
671 out:
672 	pci_disable_device(pdev);
673 
674 	vfio_pci_dev_set_try_reset(vdev->vdev.dev_set);
675 
676 	/* Put the pm-runtime usage counter acquired during enable */
677 	if (!disable_idle_d3)
678 		pm_runtime_put(&pdev->dev);
679 }
680 EXPORT_SYMBOL_GPL(vfio_pci_core_disable);
681 
vfio_pci_core_close_device(struct vfio_device * core_vdev)682 void vfio_pci_core_close_device(struct vfio_device *core_vdev)
683 {
684 	struct vfio_pci_core_device *vdev =
685 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
686 
687 	if (vdev->sriov_pf_core_dev) {
688 		mutex_lock(&vdev->sriov_pf_core_dev->vf_token->lock);
689 		WARN_ON(!vdev->sriov_pf_core_dev->vf_token->users);
690 		vdev->sriov_pf_core_dev->vf_token->users--;
691 		mutex_unlock(&vdev->sriov_pf_core_dev->vf_token->lock);
692 	}
693 #if IS_ENABLED(CONFIG_EEH)
694 	eeh_dev_release(vdev->pdev);
695 #endif
696 	vfio_pci_core_disable(vdev);
697 
698 	mutex_lock(&vdev->igate);
699 	if (vdev->err_trigger) {
700 		eventfd_ctx_put(vdev->err_trigger);
701 		vdev->err_trigger = NULL;
702 	}
703 	if (vdev->req_trigger) {
704 		eventfd_ctx_put(vdev->req_trigger);
705 		vdev->req_trigger = NULL;
706 	}
707 	mutex_unlock(&vdev->igate);
708 }
709 EXPORT_SYMBOL_GPL(vfio_pci_core_close_device);
710 
vfio_pci_core_finish_enable(struct vfio_pci_core_device * vdev)711 void vfio_pci_core_finish_enable(struct vfio_pci_core_device *vdev)
712 {
713 	vfio_pci_probe_mmaps(vdev);
714 #if IS_ENABLED(CONFIG_EEH)
715 	eeh_dev_open(vdev->pdev);
716 #endif
717 
718 	if (vdev->sriov_pf_core_dev) {
719 		mutex_lock(&vdev->sriov_pf_core_dev->vf_token->lock);
720 		vdev->sriov_pf_core_dev->vf_token->users++;
721 		mutex_unlock(&vdev->sriov_pf_core_dev->vf_token->lock);
722 	}
723 }
724 EXPORT_SYMBOL_GPL(vfio_pci_core_finish_enable);
725 
vfio_pci_get_irq_count(struct vfio_pci_core_device * vdev,int irq_type)726 static int vfio_pci_get_irq_count(struct vfio_pci_core_device *vdev, int irq_type)
727 {
728 	if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
729 		return vdev->vconfig[PCI_INTERRUPT_PIN] ? 1 : 0;
730 	} else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
731 		u8 pos;
732 		u16 flags;
733 
734 		pos = vdev->pdev->msi_cap;
735 		if (pos) {
736 			pci_read_config_word(vdev->pdev,
737 					     pos + PCI_MSI_FLAGS, &flags);
738 			return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
739 		}
740 	} else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
741 		u8 pos;
742 		u16 flags;
743 
744 		pos = vdev->pdev->msix_cap;
745 		if (pos) {
746 			pci_read_config_word(vdev->pdev,
747 					     pos + PCI_MSIX_FLAGS, &flags);
748 
749 			return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
750 		}
751 	} else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX) {
752 		if (pci_is_pcie(vdev->pdev))
753 			return 1;
754 	} else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
755 		return 1;
756 	}
757 
758 	return 0;
759 }
760 
vfio_pci_count_devs(struct pci_dev * pdev,void * data)761 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
762 {
763 	(*(int *)data)++;
764 	return 0;
765 }
766 
767 struct vfio_pci_fill_info {
768 	struct vfio_device *vdev;
769 	struct vfio_pci_dependent_device *devices;
770 	int nr_devices;
771 	u32 count;
772 	u32 flags;
773 };
774 
vfio_pci_fill_devs(struct pci_dev * pdev,void * data)775 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
776 {
777 	struct vfio_pci_dependent_device *info;
778 	struct vfio_pci_fill_info *fill = data;
779 
780 	/* The topology changed since we counted devices */
781 	if (fill->count >= fill->nr_devices)
782 		return -EAGAIN;
783 
784 	info = &fill->devices[fill->count++];
785 	info->segment = pci_domain_nr(pdev->bus);
786 	info->bus = pdev->bus->number;
787 	info->devfn = pdev->devfn;
788 
789 	if (fill->flags & VFIO_PCI_HOT_RESET_FLAG_DEV_ID) {
790 		struct iommufd_ctx *iommufd = vfio_iommufd_device_ictx(fill->vdev);
791 		struct vfio_device_set *dev_set = fill->vdev->dev_set;
792 		struct vfio_device *vdev;
793 
794 		/*
795 		 * hot-reset requires all affected devices be represented in
796 		 * the dev_set.
797 		 */
798 		vdev = vfio_find_device_in_devset(dev_set, &pdev->dev);
799 		if (!vdev) {
800 			info->devid = VFIO_PCI_DEVID_NOT_OWNED;
801 		} else {
802 			int id = vfio_iommufd_get_dev_id(vdev, iommufd);
803 
804 			if (id > 0)
805 				info->devid = id;
806 			else if (id == -ENOENT)
807 				info->devid = VFIO_PCI_DEVID_OWNED;
808 			else
809 				info->devid = VFIO_PCI_DEVID_NOT_OWNED;
810 		}
811 		/* If devid is VFIO_PCI_DEVID_NOT_OWNED, clear owned flag. */
812 		if (info->devid == VFIO_PCI_DEVID_NOT_OWNED)
813 			fill->flags &= ~VFIO_PCI_HOT_RESET_FLAG_DEV_ID_OWNED;
814 	} else {
815 		struct iommu_group *iommu_group;
816 
817 		iommu_group = iommu_group_get(&pdev->dev);
818 		if (!iommu_group)
819 			return -EPERM; /* Cannot reset non-isolated devices */
820 
821 		info->group_id = iommu_group_id(iommu_group);
822 		iommu_group_put(iommu_group);
823 	}
824 
825 	return 0;
826 }
827 
828 struct vfio_pci_group_info {
829 	int count;
830 	struct file **files;
831 };
832 
vfio_pci_dev_below_slot(struct pci_dev * pdev,struct pci_slot * slot)833 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
834 {
835 	for (; pdev; pdev = pdev->bus->self)
836 		if (pdev->bus == slot->bus)
837 			return (pdev->slot == slot);
838 	return false;
839 }
840 
841 struct vfio_pci_walk_info {
842 	int (*fn)(struct pci_dev *pdev, void *data);
843 	void *data;
844 	struct pci_dev *pdev;
845 	bool slot;
846 	int ret;
847 };
848 
vfio_pci_walk_wrapper(struct pci_dev * pdev,void * data)849 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
850 {
851 	struct vfio_pci_walk_info *walk = data;
852 
853 	if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
854 		walk->ret = walk->fn(pdev, walk->data);
855 
856 	return walk->ret;
857 }
858 
vfio_pci_for_each_slot_or_bus(struct pci_dev * pdev,int (* fn)(struct pci_dev *,void * data),void * data,bool slot)859 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
860 					 int (*fn)(struct pci_dev *,
861 						   void *data), void *data,
862 					 bool slot)
863 {
864 	struct vfio_pci_walk_info walk = {
865 		.fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
866 	};
867 
868 	pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
869 
870 	return walk.ret;
871 }
872 
msix_mmappable_cap(struct vfio_pci_core_device * vdev,struct vfio_info_cap * caps)873 static int msix_mmappable_cap(struct vfio_pci_core_device *vdev,
874 			      struct vfio_info_cap *caps)
875 {
876 	struct vfio_info_cap_header header = {
877 		.id = VFIO_REGION_INFO_CAP_MSIX_MAPPABLE,
878 		.version = 1
879 	};
880 
881 	return vfio_info_add_capability(caps, &header, sizeof(header));
882 }
883 
vfio_pci_core_register_dev_region(struct vfio_pci_core_device * vdev,unsigned int type,unsigned int subtype,const struct vfio_pci_regops * ops,size_t size,u32 flags,void * data)884 int vfio_pci_core_register_dev_region(struct vfio_pci_core_device *vdev,
885 				      unsigned int type, unsigned int subtype,
886 				      const struct vfio_pci_regops *ops,
887 				      size_t size, u32 flags, void *data)
888 {
889 	struct vfio_pci_region *region;
890 
891 	region = krealloc(vdev->region,
892 			  (vdev->num_regions + 1) * sizeof(*region),
893 			  GFP_KERNEL_ACCOUNT);
894 	if (!region)
895 		return -ENOMEM;
896 
897 	vdev->region = region;
898 	vdev->region[vdev->num_regions].type = type;
899 	vdev->region[vdev->num_regions].subtype = subtype;
900 	vdev->region[vdev->num_regions].ops = ops;
901 	vdev->region[vdev->num_regions].size = size;
902 	vdev->region[vdev->num_regions].flags = flags;
903 	vdev->region[vdev->num_regions].data = data;
904 
905 	vdev->num_regions++;
906 
907 	return 0;
908 }
909 EXPORT_SYMBOL_GPL(vfio_pci_core_register_dev_region);
910 
vfio_pci_info_atomic_cap(struct vfio_pci_core_device * vdev,struct vfio_info_cap * caps)911 static int vfio_pci_info_atomic_cap(struct vfio_pci_core_device *vdev,
912 				    struct vfio_info_cap *caps)
913 {
914 	struct vfio_device_info_cap_pci_atomic_comp cap = {
915 		.header.id = VFIO_DEVICE_INFO_CAP_PCI_ATOMIC_COMP,
916 		.header.version = 1
917 	};
918 	struct pci_dev *pdev = pci_physfn(vdev->pdev);
919 	u32 devcap2;
920 
921 	pcie_capability_read_dword(pdev, PCI_EXP_DEVCAP2, &devcap2);
922 
923 	if ((devcap2 & PCI_EXP_DEVCAP2_ATOMIC_COMP32) &&
924 	    !pci_enable_atomic_ops_to_root(pdev, PCI_EXP_DEVCAP2_ATOMIC_COMP32))
925 		cap.flags |= VFIO_PCI_ATOMIC_COMP32;
926 
927 	if ((devcap2 & PCI_EXP_DEVCAP2_ATOMIC_COMP64) &&
928 	    !pci_enable_atomic_ops_to_root(pdev, PCI_EXP_DEVCAP2_ATOMIC_COMP64))
929 		cap.flags |= VFIO_PCI_ATOMIC_COMP64;
930 
931 	if ((devcap2 & PCI_EXP_DEVCAP2_ATOMIC_COMP128) &&
932 	    !pci_enable_atomic_ops_to_root(pdev,
933 					   PCI_EXP_DEVCAP2_ATOMIC_COMP128))
934 		cap.flags |= VFIO_PCI_ATOMIC_COMP128;
935 
936 	if (!cap.flags)
937 		return -ENODEV;
938 
939 	return vfio_info_add_capability(caps, &cap.header, sizeof(cap));
940 }
941 
vfio_pci_ioctl_get_info(struct vfio_pci_core_device * vdev,struct vfio_device_info __user * arg)942 static int vfio_pci_ioctl_get_info(struct vfio_pci_core_device *vdev,
943 				   struct vfio_device_info __user *arg)
944 {
945 	unsigned long minsz = offsetofend(struct vfio_device_info, num_irqs);
946 	struct vfio_device_info info = {};
947 	struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
948 	int ret;
949 
950 	if (copy_from_user(&info, arg, minsz))
951 		return -EFAULT;
952 
953 	if (info.argsz < minsz)
954 		return -EINVAL;
955 
956 	minsz = min_t(size_t, info.argsz, sizeof(info));
957 
958 	info.flags = VFIO_DEVICE_FLAGS_PCI;
959 
960 	if (vdev->reset_works)
961 		info.flags |= VFIO_DEVICE_FLAGS_RESET;
962 
963 	info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions;
964 	info.num_irqs = VFIO_PCI_NUM_IRQS;
965 
966 	ret = vfio_pci_info_zdev_add_caps(vdev, &caps);
967 	if (ret && ret != -ENODEV) {
968 		pci_warn(vdev->pdev,
969 			 "Failed to setup zPCI info capabilities\n");
970 		return ret;
971 	}
972 
973 	ret = vfio_pci_info_atomic_cap(vdev, &caps);
974 	if (ret && ret != -ENODEV) {
975 		pci_warn(vdev->pdev,
976 			 "Failed to setup AtomicOps info capability\n");
977 		return ret;
978 	}
979 
980 	if (caps.size) {
981 		info.flags |= VFIO_DEVICE_FLAGS_CAPS;
982 		if (info.argsz < sizeof(info) + caps.size) {
983 			info.argsz = sizeof(info) + caps.size;
984 		} else {
985 			vfio_info_cap_shift(&caps, sizeof(info));
986 			if (copy_to_user(arg + 1, caps.buf, caps.size)) {
987 				kfree(caps.buf);
988 				return -EFAULT;
989 			}
990 			info.cap_offset = sizeof(*arg);
991 		}
992 
993 		kfree(caps.buf);
994 	}
995 
996 	return copy_to_user(arg, &info, minsz) ? -EFAULT : 0;
997 }
998 
vfio_pci_ioctl_get_region_info(struct vfio_pci_core_device * vdev,struct vfio_region_info __user * arg)999 static int vfio_pci_ioctl_get_region_info(struct vfio_pci_core_device *vdev,
1000 					  struct vfio_region_info __user *arg)
1001 {
1002 	unsigned long minsz = offsetofend(struct vfio_region_info, offset);
1003 	struct pci_dev *pdev = vdev->pdev;
1004 	struct vfio_region_info info;
1005 	struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
1006 	int i, ret;
1007 
1008 	if (copy_from_user(&info, arg, minsz))
1009 		return -EFAULT;
1010 
1011 	if (info.argsz < minsz)
1012 		return -EINVAL;
1013 
1014 	switch (info.index) {
1015 	case VFIO_PCI_CONFIG_REGION_INDEX:
1016 		info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
1017 		info.size = pdev->cfg_size;
1018 		info.flags = VFIO_REGION_INFO_FLAG_READ |
1019 			     VFIO_REGION_INFO_FLAG_WRITE;
1020 		break;
1021 	case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
1022 		info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
1023 		info.size = pci_resource_len(pdev, info.index);
1024 		if (!info.size) {
1025 			info.flags = 0;
1026 			break;
1027 		}
1028 
1029 		info.flags = VFIO_REGION_INFO_FLAG_READ |
1030 			     VFIO_REGION_INFO_FLAG_WRITE;
1031 		if (vdev->bar_mmap_supported[info.index]) {
1032 			info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
1033 			if (info.index == vdev->msix_bar) {
1034 				ret = msix_mmappable_cap(vdev, &caps);
1035 				if (ret)
1036 					return ret;
1037 			}
1038 		}
1039 
1040 		break;
1041 	case VFIO_PCI_ROM_REGION_INDEX: {
1042 		void __iomem *io;
1043 		size_t size;
1044 		u16 cmd;
1045 
1046 		info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
1047 		info.flags = 0;
1048 		info.size = 0;
1049 
1050 		if (pci_resource_start(pdev, PCI_ROM_RESOURCE)) {
1051 			/*
1052 			 * Check ROM content is valid. Need to enable memory
1053 			 * decode for ROM access in pci_map_rom().
1054 			 */
1055 			cmd = vfio_pci_memory_lock_and_enable(vdev);
1056 			io = pci_map_rom(pdev, &size);
1057 			if (io) {
1058 				info.flags = VFIO_REGION_INFO_FLAG_READ;
1059 				/* Report the BAR size, not the ROM size. */
1060 				info.size = pci_resource_len(pdev, PCI_ROM_RESOURCE);
1061 				pci_unmap_rom(pdev, io);
1062 			}
1063 			vfio_pci_memory_unlock_and_restore(vdev, cmd);
1064 		} else if (pdev->rom && pdev->romlen) {
1065 			info.flags = VFIO_REGION_INFO_FLAG_READ;
1066 			/* Report BAR size as power of two. */
1067 			info.size = roundup_pow_of_two(pdev->romlen);
1068 		}
1069 
1070 		break;
1071 	}
1072 	case VFIO_PCI_VGA_REGION_INDEX:
1073 		if (!vdev->has_vga)
1074 			return -EINVAL;
1075 
1076 		info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
1077 		info.size = 0xc0000;
1078 		info.flags = VFIO_REGION_INFO_FLAG_READ |
1079 			     VFIO_REGION_INFO_FLAG_WRITE;
1080 
1081 		break;
1082 	default: {
1083 		struct vfio_region_info_cap_type cap_type = {
1084 			.header.id = VFIO_REGION_INFO_CAP_TYPE,
1085 			.header.version = 1
1086 		};
1087 
1088 		if (info.index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1089 			return -EINVAL;
1090 		info.index = array_index_nospec(
1091 			info.index, VFIO_PCI_NUM_REGIONS + vdev->num_regions);
1092 
1093 		i = info.index - VFIO_PCI_NUM_REGIONS;
1094 
1095 		info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
1096 		info.size = vdev->region[i].size;
1097 		info.flags = vdev->region[i].flags;
1098 
1099 		cap_type.type = vdev->region[i].type;
1100 		cap_type.subtype = vdev->region[i].subtype;
1101 
1102 		ret = vfio_info_add_capability(&caps, &cap_type.header,
1103 					       sizeof(cap_type));
1104 		if (ret)
1105 			return ret;
1106 
1107 		if (vdev->region[i].ops->add_capability) {
1108 			ret = vdev->region[i].ops->add_capability(
1109 				vdev, &vdev->region[i], &caps);
1110 			if (ret)
1111 				return ret;
1112 		}
1113 	}
1114 	}
1115 
1116 	if (caps.size) {
1117 		info.flags |= VFIO_REGION_INFO_FLAG_CAPS;
1118 		if (info.argsz < sizeof(info) + caps.size) {
1119 			info.argsz = sizeof(info) + caps.size;
1120 			info.cap_offset = 0;
1121 		} else {
1122 			vfio_info_cap_shift(&caps, sizeof(info));
1123 			if (copy_to_user(arg + 1, caps.buf, caps.size)) {
1124 				kfree(caps.buf);
1125 				return -EFAULT;
1126 			}
1127 			info.cap_offset = sizeof(*arg);
1128 		}
1129 
1130 		kfree(caps.buf);
1131 	}
1132 
1133 	return copy_to_user(arg, &info, minsz) ? -EFAULT : 0;
1134 }
1135 
vfio_pci_ioctl_get_irq_info(struct vfio_pci_core_device * vdev,struct vfio_irq_info __user * arg)1136 static int vfio_pci_ioctl_get_irq_info(struct vfio_pci_core_device *vdev,
1137 				       struct vfio_irq_info __user *arg)
1138 {
1139 	unsigned long minsz = offsetofend(struct vfio_irq_info, count);
1140 	struct vfio_irq_info info;
1141 
1142 	if (copy_from_user(&info, arg, minsz))
1143 		return -EFAULT;
1144 
1145 	if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
1146 		return -EINVAL;
1147 
1148 	switch (info.index) {
1149 	case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
1150 	case VFIO_PCI_REQ_IRQ_INDEX:
1151 		break;
1152 	case VFIO_PCI_ERR_IRQ_INDEX:
1153 		if (pci_is_pcie(vdev->pdev))
1154 			break;
1155 		fallthrough;
1156 	default:
1157 		return -EINVAL;
1158 	}
1159 
1160 	info.flags = VFIO_IRQ_INFO_EVENTFD;
1161 
1162 	info.count = vfio_pci_get_irq_count(vdev, info.index);
1163 
1164 	if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
1165 		info.flags |=
1166 			(VFIO_IRQ_INFO_MASKABLE | VFIO_IRQ_INFO_AUTOMASKED);
1167 	else if (info.index != VFIO_PCI_MSIX_IRQ_INDEX || !vdev->has_dyn_msix)
1168 		info.flags |= VFIO_IRQ_INFO_NORESIZE;
1169 
1170 	return copy_to_user(arg, &info, minsz) ? -EFAULT : 0;
1171 }
1172 
vfio_pci_ioctl_set_irqs(struct vfio_pci_core_device * vdev,struct vfio_irq_set __user * arg)1173 static int vfio_pci_ioctl_set_irqs(struct vfio_pci_core_device *vdev,
1174 				   struct vfio_irq_set __user *arg)
1175 {
1176 	unsigned long minsz = offsetofend(struct vfio_irq_set, count);
1177 	struct vfio_irq_set hdr;
1178 	u8 *data = NULL;
1179 	int max, ret = 0;
1180 	size_t data_size = 0;
1181 
1182 	if (copy_from_user(&hdr, arg, minsz))
1183 		return -EFAULT;
1184 
1185 	max = vfio_pci_get_irq_count(vdev, hdr.index);
1186 
1187 	ret = vfio_set_irqs_validate_and_prepare(&hdr, max, VFIO_PCI_NUM_IRQS,
1188 						 &data_size);
1189 	if (ret)
1190 		return ret;
1191 
1192 	if (data_size) {
1193 		data = memdup_user(&arg->data, data_size);
1194 		if (IS_ERR(data))
1195 			return PTR_ERR(data);
1196 	}
1197 
1198 	mutex_lock(&vdev->igate);
1199 
1200 	ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index, hdr.start,
1201 				      hdr.count, data);
1202 
1203 	mutex_unlock(&vdev->igate);
1204 	kfree(data);
1205 
1206 	return ret;
1207 }
1208 
vfio_pci_ioctl_reset(struct vfio_pci_core_device * vdev,void __user * arg)1209 static int vfio_pci_ioctl_reset(struct vfio_pci_core_device *vdev,
1210 				void __user *arg)
1211 {
1212 	int ret;
1213 
1214 	if (!vdev->reset_works)
1215 		return -EINVAL;
1216 
1217 	vfio_pci_zap_and_down_write_memory_lock(vdev);
1218 
1219 	/*
1220 	 * This function can be invoked while the power state is non-D0. If
1221 	 * pci_try_reset_function() has been called while the power state is
1222 	 * non-D0, then pci_try_reset_function() will internally set the power
1223 	 * state to D0 without vfio driver involvement. For the devices which
1224 	 * have NoSoftRst-, the reset function can cause the PCI config space
1225 	 * reset without restoring the original state (saved locally in
1226 	 * 'vdev->pm_save').
1227 	 */
1228 	vfio_pci_set_power_state(vdev, PCI_D0);
1229 
1230 	ret = pci_try_reset_function(vdev->pdev);
1231 	up_write(&vdev->memory_lock);
1232 
1233 	return ret;
1234 }
1235 
vfio_pci_ioctl_get_pci_hot_reset_info(struct vfio_pci_core_device * vdev,struct vfio_pci_hot_reset_info __user * arg)1236 static int vfio_pci_ioctl_get_pci_hot_reset_info(
1237 	struct vfio_pci_core_device *vdev,
1238 	struct vfio_pci_hot_reset_info __user *arg)
1239 {
1240 	unsigned long minsz =
1241 		offsetofend(struct vfio_pci_hot_reset_info, count);
1242 	struct vfio_pci_dependent_device *devices = NULL;
1243 	struct vfio_pci_hot_reset_info hdr;
1244 	struct vfio_pci_fill_info fill = {};
1245 	bool slot = false;
1246 	int ret, count = 0;
1247 
1248 	if (copy_from_user(&hdr, arg, minsz))
1249 		return -EFAULT;
1250 
1251 	if (hdr.argsz < minsz)
1252 		return -EINVAL;
1253 
1254 	hdr.flags = 0;
1255 
1256 	/* Can we do a slot or bus reset or neither? */
1257 	if (!pci_probe_reset_slot(vdev->pdev->slot))
1258 		slot = true;
1259 	else if (pci_probe_reset_bus(vdev->pdev->bus))
1260 		return -ENODEV;
1261 
1262 	ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
1263 					    &count, slot);
1264 	if (ret)
1265 		return ret;
1266 
1267 	if (WARN_ON(!count)) /* Should always be at least one */
1268 		return -ERANGE;
1269 
1270 	if (count > (hdr.argsz - sizeof(hdr)) / sizeof(*devices)) {
1271 		hdr.count = count;
1272 		ret = -ENOSPC;
1273 		goto header;
1274 	}
1275 
1276 	devices = kcalloc(count, sizeof(*devices), GFP_KERNEL);
1277 	if (!devices)
1278 		return -ENOMEM;
1279 
1280 	fill.devices = devices;
1281 	fill.nr_devices = count;
1282 	fill.vdev = &vdev->vdev;
1283 
1284 	if (vfio_device_cdev_opened(&vdev->vdev))
1285 		fill.flags |= VFIO_PCI_HOT_RESET_FLAG_DEV_ID |
1286 			     VFIO_PCI_HOT_RESET_FLAG_DEV_ID_OWNED;
1287 
1288 	mutex_lock(&vdev->vdev.dev_set->lock);
1289 	ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_fill_devs,
1290 					    &fill, slot);
1291 	mutex_unlock(&vdev->vdev.dev_set->lock);
1292 	if (ret)
1293 		goto out;
1294 
1295 	if (copy_to_user(arg->devices, devices,
1296 			 sizeof(*devices) * fill.count)) {
1297 		ret = -EFAULT;
1298 		goto out;
1299 	}
1300 
1301 	hdr.count = fill.count;
1302 	hdr.flags = fill.flags;
1303 
1304 header:
1305 	if (copy_to_user(arg, &hdr, minsz))
1306 		ret = -EFAULT;
1307 out:
1308 	kfree(devices);
1309 	return ret;
1310 }
1311 
1312 static int
vfio_pci_ioctl_pci_hot_reset_groups(struct vfio_pci_core_device * vdev,u32 array_count,bool slot,struct vfio_pci_hot_reset __user * arg)1313 vfio_pci_ioctl_pci_hot_reset_groups(struct vfio_pci_core_device *vdev,
1314 				    u32 array_count, bool slot,
1315 				    struct vfio_pci_hot_reset __user *arg)
1316 {
1317 	int32_t *group_fds;
1318 	struct file **files;
1319 	struct vfio_pci_group_info info;
1320 	int file_idx, count = 0, ret = 0;
1321 
1322 	/*
1323 	 * We can't let userspace give us an arbitrarily large buffer to copy,
1324 	 * so verify how many we think there could be.  Note groups can have
1325 	 * multiple devices so one group per device is the max.
1326 	 */
1327 	ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
1328 					    &count, slot);
1329 	if (ret)
1330 		return ret;
1331 
1332 	if (array_count > count)
1333 		return -EINVAL;
1334 
1335 	group_fds = kcalloc(array_count, sizeof(*group_fds), GFP_KERNEL);
1336 	files = kcalloc(array_count, sizeof(*files), GFP_KERNEL);
1337 	if (!group_fds || !files) {
1338 		kfree(group_fds);
1339 		kfree(files);
1340 		return -ENOMEM;
1341 	}
1342 
1343 	if (copy_from_user(group_fds, arg->group_fds,
1344 			   array_count * sizeof(*group_fds))) {
1345 		kfree(group_fds);
1346 		kfree(files);
1347 		return -EFAULT;
1348 	}
1349 
1350 	/*
1351 	 * Get the group file for each fd to ensure the group is held across
1352 	 * the reset
1353 	 */
1354 	for (file_idx = 0; file_idx < array_count; file_idx++) {
1355 		struct file *file = fget(group_fds[file_idx]);
1356 
1357 		if (!file) {
1358 			ret = -EBADF;
1359 			break;
1360 		}
1361 
1362 		/* Ensure the FD is a vfio group FD.*/
1363 		if (!vfio_file_is_group(file)) {
1364 			fput(file);
1365 			ret = -EINVAL;
1366 			break;
1367 		}
1368 
1369 		files[file_idx] = file;
1370 	}
1371 
1372 	kfree(group_fds);
1373 
1374 	/* release reference to groups on error */
1375 	if (ret)
1376 		goto hot_reset_release;
1377 
1378 	info.count = array_count;
1379 	info.files = files;
1380 
1381 	ret = vfio_pci_dev_set_hot_reset(vdev->vdev.dev_set, &info, NULL);
1382 
1383 hot_reset_release:
1384 	for (file_idx--; file_idx >= 0; file_idx--)
1385 		fput(files[file_idx]);
1386 
1387 	kfree(files);
1388 	return ret;
1389 }
1390 
vfio_pci_ioctl_pci_hot_reset(struct vfio_pci_core_device * vdev,struct vfio_pci_hot_reset __user * arg)1391 static int vfio_pci_ioctl_pci_hot_reset(struct vfio_pci_core_device *vdev,
1392 					struct vfio_pci_hot_reset __user *arg)
1393 {
1394 	unsigned long minsz = offsetofend(struct vfio_pci_hot_reset, count);
1395 	struct vfio_pci_hot_reset hdr;
1396 	bool slot = false;
1397 
1398 	if (copy_from_user(&hdr, arg, minsz))
1399 		return -EFAULT;
1400 
1401 	if (hdr.argsz < minsz || hdr.flags)
1402 		return -EINVAL;
1403 
1404 	/* zero-length array is only for cdev opened devices */
1405 	if (!!hdr.count == vfio_device_cdev_opened(&vdev->vdev))
1406 		return -EINVAL;
1407 
1408 	/* Can we do a slot or bus reset or neither? */
1409 	if (!pci_probe_reset_slot(vdev->pdev->slot))
1410 		slot = true;
1411 	else if (pci_probe_reset_bus(vdev->pdev->bus))
1412 		return -ENODEV;
1413 
1414 	if (hdr.count)
1415 		return vfio_pci_ioctl_pci_hot_reset_groups(vdev, hdr.count, slot, arg);
1416 
1417 	return vfio_pci_dev_set_hot_reset(vdev->vdev.dev_set, NULL,
1418 					  vfio_iommufd_device_ictx(&vdev->vdev));
1419 }
1420 
vfio_pci_ioctl_ioeventfd(struct vfio_pci_core_device * vdev,struct vfio_device_ioeventfd __user * arg)1421 static int vfio_pci_ioctl_ioeventfd(struct vfio_pci_core_device *vdev,
1422 				    struct vfio_device_ioeventfd __user *arg)
1423 {
1424 	unsigned long minsz = offsetofend(struct vfio_device_ioeventfd, fd);
1425 	struct vfio_device_ioeventfd ioeventfd;
1426 	int count;
1427 
1428 	if (copy_from_user(&ioeventfd, arg, minsz))
1429 		return -EFAULT;
1430 
1431 	if (ioeventfd.argsz < minsz)
1432 		return -EINVAL;
1433 
1434 	if (ioeventfd.flags & ~VFIO_DEVICE_IOEVENTFD_SIZE_MASK)
1435 		return -EINVAL;
1436 
1437 	count = ioeventfd.flags & VFIO_DEVICE_IOEVENTFD_SIZE_MASK;
1438 
1439 	if (hweight8(count) != 1 || ioeventfd.fd < -1)
1440 		return -EINVAL;
1441 
1442 	return vfio_pci_ioeventfd(vdev, ioeventfd.offset, ioeventfd.data, count,
1443 				  ioeventfd.fd);
1444 }
1445 
vfio_pci_core_ioctl(struct vfio_device * core_vdev,unsigned int cmd,unsigned long arg)1446 long vfio_pci_core_ioctl(struct vfio_device *core_vdev, unsigned int cmd,
1447 			 unsigned long arg)
1448 {
1449 	struct vfio_pci_core_device *vdev =
1450 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1451 	void __user *uarg = (void __user *)arg;
1452 
1453 	switch (cmd) {
1454 	case VFIO_DEVICE_GET_INFO:
1455 		return vfio_pci_ioctl_get_info(vdev, uarg);
1456 	case VFIO_DEVICE_GET_IRQ_INFO:
1457 		return vfio_pci_ioctl_get_irq_info(vdev, uarg);
1458 	case VFIO_DEVICE_GET_PCI_HOT_RESET_INFO:
1459 		return vfio_pci_ioctl_get_pci_hot_reset_info(vdev, uarg);
1460 	case VFIO_DEVICE_GET_REGION_INFO:
1461 		return vfio_pci_ioctl_get_region_info(vdev, uarg);
1462 	case VFIO_DEVICE_IOEVENTFD:
1463 		return vfio_pci_ioctl_ioeventfd(vdev, uarg);
1464 	case VFIO_DEVICE_PCI_HOT_RESET:
1465 		return vfio_pci_ioctl_pci_hot_reset(vdev, uarg);
1466 	case VFIO_DEVICE_RESET:
1467 		return vfio_pci_ioctl_reset(vdev, uarg);
1468 	case VFIO_DEVICE_SET_IRQS:
1469 		return vfio_pci_ioctl_set_irqs(vdev, uarg);
1470 	default:
1471 		return -ENOTTY;
1472 	}
1473 }
1474 EXPORT_SYMBOL_GPL(vfio_pci_core_ioctl);
1475 
vfio_pci_core_feature_token(struct vfio_device * device,u32 flags,uuid_t __user * arg,size_t argsz)1476 static int vfio_pci_core_feature_token(struct vfio_device *device, u32 flags,
1477 				       uuid_t __user *arg, size_t argsz)
1478 {
1479 	struct vfio_pci_core_device *vdev =
1480 		container_of(device, struct vfio_pci_core_device, vdev);
1481 	uuid_t uuid;
1482 	int ret;
1483 
1484 	if (!vdev->vf_token)
1485 		return -ENOTTY;
1486 	/*
1487 	 * We do not support GET of the VF Token UUID as this could
1488 	 * expose the token of the previous device user.
1489 	 */
1490 	ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_SET,
1491 				 sizeof(uuid));
1492 	if (ret != 1)
1493 		return ret;
1494 
1495 	if (copy_from_user(&uuid, arg, sizeof(uuid)))
1496 		return -EFAULT;
1497 
1498 	mutex_lock(&vdev->vf_token->lock);
1499 	uuid_copy(&vdev->vf_token->uuid, &uuid);
1500 	mutex_unlock(&vdev->vf_token->lock);
1501 	return 0;
1502 }
1503 
vfio_pci_core_ioctl_feature(struct vfio_device * device,u32 flags,void __user * arg,size_t argsz)1504 int vfio_pci_core_ioctl_feature(struct vfio_device *device, u32 flags,
1505 				void __user *arg, size_t argsz)
1506 {
1507 	switch (flags & VFIO_DEVICE_FEATURE_MASK) {
1508 	case VFIO_DEVICE_FEATURE_LOW_POWER_ENTRY:
1509 		return vfio_pci_core_pm_entry(device, flags, arg, argsz);
1510 	case VFIO_DEVICE_FEATURE_LOW_POWER_ENTRY_WITH_WAKEUP:
1511 		return vfio_pci_core_pm_entry_with_wakeup(device, flags,
1512 							  arg, argsz);
1513 	case VFIO_DEVICE_FEATURE_LOW_POWER_EXIT:
1514 		return vfio_pci_core_pm_exit(device, flags, arg, argsz);
1515 	case VFIO_DEVICE_FEATURE_PCI_VF_TOKEN:
1516 		return vfio_pci_core_feature_token(device, flags, arg, argsz);
1517 	default:
1518 		return -ENOTTY;
1519 	}
1520 }
1521 EXPORT_SYMBOL_GPL(vfio_pci_core_ioctl_feature);
1522 
vfio_pci_rw(struct vfio_pci_core_device * vdev,char __user * buf,size_t count,loff_t * ppos,bool iswrite)1523 static ssize_t vfio_pci_rw(struct vfio_pci_core_device *vdev, char __user *buf,
1524 			   size_t count, loff_t *ppos, bool iswrite)
1525 {
1526 	unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
1527 	int ret;
1528 
1529 	if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1530 		return -EINVAL;
1531 
1532 	ret = pm_runtime_resume_and_get(&vdev->pdev->dev);
1533 	if (ret) {
1534 		pci_info_ratelimited(vdev->pdev, "runtime resume failed %d\n",
1535 				     ret);
1536 		return -EIO;
1537 	}
1538 
1539 	switch (index) {
1540 	case VFIO_PCI_CONFIG_REGION_INDEX:
1541 		ret = vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
1542 		break;
1543 
1544 	case VFIO_PCI_ROM_REGION_INDEX:
1545 		if (iswrite)
1546 			ret = -EINVAL;
1547 		else
1548 			ret = vfio_pci_bar_rw(vdev, buf, count, ppos, false);
1549 		break;
1550 
1551 	case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
1552 		ret = vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
1553 		break;
1554 
1555 	case VFIO_PCI_VGA_REGION_INDEX:
1556 		ret = vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
1557 		break;
1558 
1559 	default:
1560 		index -= VFIO_PCI_NUM_REGIONS;
1561 		ret = vdev->region[index].ops->rw(vdev, buf,
1562 						   count, ppos, iswrite);
1563 		break;
1564 	}
1565 
1566 	pm_runtime_put(&vdev->pdev->dev);
1567 	return ret;
1568 }
1569 
vfio_pci_core_read(struct vfio_device * core_vdev,char __user * buf,size_t count,loff_t * ppos)1570 ssize_t vfio_pci_core_read(struct vfio_device *core_vdev, char __user *buf,
1571 		size_t count, loff_t *ppos)
1572 {
1573 	struct vfio_pci_core_device *vdev =
1574 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1575 
1576 	if (!count)
1577 		return 0;
1578 
1579 	return vfio_pci_rw(vdev, buf, count, ppos, false);
1580 }
1581 EXPORT_SYMBOL_GPL(vfio_pci_core_read);
1582 
vfio_pci_core_write(struct vfio_device * core_vdev,const char __user * buf,size_t count,loff_t * ppos)1583 ssize_t vfio_pci_core_write(struct vfio_device *core_vdev, const char __user *buf,
1584 		size_t count, loff_t *ppos)
1585 {
1586 	struct vfio_pci_core_device *vdev =
1587 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1588 
1589 	if (!count)
1590 		return 0;
1591 
1592 	return vfio_pci_rw(vdev, (char __user *)buf, count, ppos, true);
1593 }
1594 EXPORT_SYMBOL_GPL(vfio_pci_core_write);
1595 
vfio_pci_zap_bars(struct vfio_pci_core_device * vdev)1596 static void vfio_pci_zap_bars(struct vfio_pci_core_device *vdev)
1597 {
1598 	struct vfio_device *core_vdev = &vdev->vdev;
1599 	loff_t start = VFIO_PCI_INDEX_TO_OFFSET(VFIO_PCI_BAR0_REGION_INDEX);
1600 	loff_t end = VFIO_PCI_INDEX_TO_OFFSET(VFIO_PCI_ROM_REGION_INDEX);
1601 	loff_t len = end - start;
1602 
1603 	unmap_mapping_range(core_vdev->inode->i_mapping, start, len, true);
1604 }
1605 
vfio_pci_zap_and_down_write_memory_lock(struct vfio_pci_core_device * vdev)1606 void vfio_pci_zap_and_down_write_memory_lock(struct vfio_pci_core_device *vdev)
1607 {
1608 	down_write(&vdev->memory_lock);
1609 	vfio_pci_zap_bars(vdev);
1610 }
1611 
vfio_pci_memory_lock_and_enable(struct vfio_pci_core_device * vdev)1612 u16 vfio_pci_memory_lock_and_enable(struct vfio_pci_core_device *vdev)
1613 {
1614 	u16 cmd;
1615 
1616 	down_write(&vdev->memory_lock);
1617 	pci_read_config_word(vdev->pdev, PCI_COMMAND, &cmd);
1618 	if (!(cmd & PCI_COMMAND_MEMORY))
1619 		pci_write_config_word(vdev->pdev, PCI_COMMAND,
1620 				      cmd | PCI_COMMAND_MEMORY);
1621 
1622 	return cmd;
1623 }
1624 
vfio_pci_memory_unlock_and_restore(struct vfio_pci_core_device * vdev,u16 cmd)1625 void vfio_pci_memory_unlock_and_restore(struct vfio_pci_core_device *vdev, u16 cmd)
1626 {
1627 	pci_write_config_word(vdev->pdev, PCI_COMMAND, cmd);
1628 	up_write(&vdev->memory_lock);
1629 }
1630 
vma_to_pfn(struct vm_area_struct * vma)1631 static unsigned long vma_to_pfn(struct vm_area_struct *vma)
1632 {
1633 	struct vfio_pci_core_device *vdev = vma->vm_private_data;
1634 	int index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1635 	u64 pgoff;
1636 
1637 	pgoff = vma->vm_pgoff &
1638 		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1639 
1640 	return (pci_resource_start(vdev->pdev, index) >> PAGE_SHIFT) + pgoff;
1641 }
1642 
vfio_pci_mmap_huge_fault(struct vm_fault * vmf,unsigned int order)1643 static vm_fault_t vfio_pci_mmap_huge_fault(struct vm_fault *vmf,
1644 					   unsigned int order)
1645 {
1646 	struct vm_area_struct *vma = vmf->vma;
1647 	struct vfio_pci_core_device *vdev = vma->vm_private_data;
1648 	unsigned long addr = vmf->address & ~((PAGE_SIZE << order) - 1);
1649 	unsigned long pgoff = (addr - vma->vm_start) >> PAGE_SHIFT;
1650 	unsigned long pfn = vma_to_pfn(vma) + pgoff;
1651 	vm_fault_t ret = VM_FAULT_SIGBUS;
1652 
1653 	if (order && (addr < vma->vm_start ||
1654 		      addr + (PAGE_SIZE << order) > vma->vm_end ||
1655 		      pfn & ((1 << order) - 1))) {
1656 		ret = VM_FAULT_FALLBACK;
1657 		goto out;
1658 	}
1659 
1660 	down_read(&vdev->memory_lock);
1661 
1662 	if (vdev->pm_runtime_engaged || !__vfio_pci_memory_enabled(vdev))
1663 		goto out_unlock;
1664 
1665 	switch (order) {
1666 	case 0:
1667 		ret = vmf_insert_pfn(vma, vmf->address, pfn);
1668 		break;
1669 #ifdef CONFIG_ARCH_SUPPORTS_PMD_PFNMAP
1670 	case PMD_ORDER:
1671 		ret = vmf_insert_pfn_pmd(vmf, pfn, false);
1672 		break;
1673 #endif
1674 #ifdef CONFIG_ARCH_SUPPORTS_PUD_PFNMAP
1675 	case PUD_ORDER:
1676 		ret = vmf_insert_pfn_pud(vmf, pfn, false);
1677 		break;
1678 #endif
1679 	default:
1680 		ret = VM_FAULT_FALLBACK;
1681 	}
1682 
1683 out_unlock:
1684 	up_read(&vdev->memory_lock);
1685 out:
1686 	dev_dbg_ratelimited(&vdev->pdev->dev,
1687 			   "%s(,order = %d) BAR %ld page offset 0x%lx: 0x%x\n",
1688 			    __func__, order,
1689 			    vma->vm_pgoff >>
1690 				(VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT),
1691 			    pgoff, (unsigned int)ret);
1692 
1693 	return ret;
1694 }
1695 
vfio_pci_mmap_page_fault(struct vm_fault * vmf)1696 static vm_fault_t vfio_pci_mmap_page_fault(struct vm_fault *vmf)
1697 {
1698 	return vfio_pci_mmap_huge_fault(vmf, 0);
1699 }
1700 
1701 static const struct vm_operations_struct vfio_pci_mmap_ops = {
1702 	.fault = vfio_pci_mmap_page_fault,
1703 #ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
1704 	.huge_fault = vfio_pci_mmap_huge_fault,
1705 #endif
1706 };
1707 
vfio_pci_core_mmap(struct vfio_device * core_vdev,struct vm_area_struct * vma)1708 int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma)
1709 {
1710 	struct vfio_pci_core_device *vdev =
1711 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1712 	struct pci_dev *pdev = vdev->pdev;
1713 	unsigned int index;
1714 	u64 phys_len, req_len, pgoff, req_start;
1715 	int ret;
1716 
1717 	index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1718 
1719 	if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1720 		return -EINVAL;
1721 	if (vma->vm_end < vma->vm_start)
1722 		return -EINVAL;
1723 	if ((vma->vm_flags & VM_SHARED) == 0)
1724 		return -EINVAL;
1725 	if (index >= VFIO_PCI_NUM_REGIONS) {
1726 		int regnum = index - VFIO_PCI_NUM_REGIONS;
1727 		struct vfio_pci_region *region = vdev->region + regnum;
1728 
1729 		if (region->ops && region->ops->mmap &&
1730 		    (region->flags & VFIO_REGION_INFO_FLAG_MMAP))
1731 			return region->ops->mmap(vdev, region, vma);
1732 		return -EINVAL;
1733 	}
1734 	if (index >= VFIO_PCI_ROM_REGION_INDEX)
1735 		return -EINVAL;
1736 	if (!vdev->bar_mmap_supported[index])
1737 		return -EINVAL;
1738 
1739 	phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1740 	req_len = vma->vm_end - vma->vm_start;
1741 	pgoff = vma->vm_pgoff &
1742 		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1743 	req_start = pgoff << PAGE_SHIFT;
1744 
1745 	if (req_start + req_len > phys_len)
1746 		return -EINVAL;
1747 
1748 	/*
1749 	 * Even though we don't make use of the barmap for the mmap,
1750 	 * we need to request the region and the barmap tracks that.
1751 	 */
1752 	if (!vdev->barmap[index]) {
1753 		ret = pci_request_selected_regions(pdev,
1754 						   1 << index, "vfio-pci");
1755 		if (ret)
1756 			return ret;
1757 
1758 		vdev->barmap[index] = pci_iomap(pdev, index, 0);
1759 		if (!vdev->barmap[index]) {
1760 			pci_release_selected_regions(pdev, 1 << index);
1761 			return -ENOMEM;
1762 		}
1763 	}
1764 
1765 	vma->vm_private_data = vdev;
1766 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1767 	vma->vm_page_prot = pgprot_decrypted(vma->vm_page_prot);
1768 
1769 	/*
1770 	 * Set vm_flags now, they should not be changed in the fault handler.
1771 	 * We want the same flags and page protection (decrypted above) as
1772 	 * io_remap_pfn_range() would set.
1773 	 *
1774 	 * VM_ALLOW_ANY_UNCACHED: The VMA flag is implemented for ARM64,
1775 	 * allowing KVM stage 2 device mapping attributes to use Normal-NC
1776 	 * rather than DEVICE_nGnRE, which allows guest mappings
1777 	 * supporting write-combining attributes (WC). ARM does not
1778 	 * architecturally guarantee this is safe, and indeed some MMIO
1779 	 * regions like the GICv2 VCPU interface can trigger uncontained
1780 	 * faults if Normal-NC is used.
1781 	 *
1782 	 * To safely use VFIO in KVM the platform must guarantee full
1783 	 * safety in the guest where no action taken against a MMIO
1784 	 * mapping can trigger an uncontained failure. The assumption is
1785 	 * that most VFIO PCI platforms support this for both mapping types,
1786 	 * at least in common flows, based on some expectations of how
1787 	 * PCI IP is integrated. Hence VM_ALLOW_ANY_UNCACHED is set in
1788 	 * the VMA flags.
1789 	 */
1790 	vm_flags_set(vma, VM_ALLOW_ANY_UNCACHED | VM_IO | VM_PFNMAP |
1791 			VM_DONTEXPAND | VM_DONTDUMP);
1792 	vma->vm_ops = &vfio_pci_mmap_ops;
1793 
1794 	return 0;
1795 }
1796 EXPORT_SYMBOL_GPL(vfio_pci_core_mmap);
1797 
vfio_pci_core_request(struct vfio_device * core_vdev,unsigned int count)1798 void vfio_pci_core_request(struct vfio_device *core_vdev, unsigned int count)
1799 {
1800 	struct vfio_pci_core_device *vdev =
1801 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1802 	struct pci_dev *pdev = vdev->pdev;
1803 
1804 	mutex_lock(&vdev->igate);
1805 
1806 	if (vdev->req_trigger) {
1807 		if (!(count % 10))
1808 			pci_notice_ratelimited(pdev,
1809 				"Relaying device request to user (#%u)\n",
1810 				count);
1811 		eventfd_signal(vdev->req_trigger);
1812 	} else if (count == 0) {
1813 		pci_warn(pdev,
1814 			"No device request channel registered, blocked until released by user\n");
1815 	}
1816 
1817 	mutex_unlock(&vdev->igate);
1818 }
1819 EXPORT_SYMBOL_GPL(vfio_pci_core_request);
1820 
vfio_pci_core_match_token_uuid(struct vfio_device * core_vdev,const uuid_t * uuid)1821 int vfio_pci_core_match_token_uuid(struct vfio_device *core_vdev,
1822 				   const uuid_t *uuid)
1823 
1824 {
1825 	struct vfio_pci_core_device *vdev =
1826 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1827 
1828 	/*
1829 	 * There's always some degree of trust or collaboration between SR-IOV
1830 	 * PF and VFs, even if just that the PF hosts the SR-IOV capability and
1831 	 * can disrupt VFs with a reset, but often the PF has more explicit
1832 	 * access to deny service to the VF or access data passed through the
1833 	 * VF.  We therefore require an opt-in via a shared VF token (UUID) to
1834 	 * represent this trust.  This both prevents that a VF driver might
1835 	 * assume the PF driver is a trusted, in-kernel driver, and also that
1836 	 * a PF driver might be replaced with a rogue driver, unknown to in-use
1837 	 * VF drivers.
1838 	 *
1839 	 * Therefore when presented with a VF, if the PF is a vfio device and
1840 	 * it is bound to the vfio-pci driver, the user needs to provide a VF
1841 	 * token to access the device, in the form of appending a vf_token to
1842 	 * the device name, for example:
1843 	 *
1844 	 * "0000:04:10.0 vf_token=bd8d9d2b-5a5f-4f5a-a211-f591514ba1f3"
1845 	 *
1846 	 * When presented with a PF which has VFs in use, the user must also
1847 	 * provide the current VF token to prove collaboration with existing
1848 	 * VF users.  If VFs are not in use, the VF token provided for the PF
1849 	 * device will act to set the VF token.
1850 	 *
1851 	 * If the VF token is provided but unused, an error is generated.
1852 	 */
1853 	if (vdev->pdev->is_virtfn) {
1854 		struct vfio_pci_core_device *pf_vdev = vdev->sriov_pf_core_dev;
1855 		bool match;
1856 
1857 		if (!pf_vdev) {
1858 			if (!uuid)
1859 				return 0; /* PF is not vfio-pci, no VF token */
1860 
1861 			pci_info_ratelimited(vdev->pdev,
1862 				"VF token incorrectly provided, PF not bound to vfio-pci\n");
1863 			return -EINVAL;
1864 		}
1865 
1866 		if (!uuid) {
1867 			pci_info_ratelimited(vdev->pdev,
1868 				"VF token required to access device\n");
1869 			return -EACCES;
1870 		}
1871 
1872 		mutex_lock(&pf_vdev->vf_token->lock);
1873 		match = uuid_equal(uuid, &pf_vdev->vf_token->uuid);
1874 		mutex_unlock(&pf_vdev->vf_token->lock);
1875 
1876 		if (!match) {
1877 			pci_info_ratelimited(vdev->pdev,
1878 				"Incorrect VF token provided for device\n");
1879 			return -EACCES;
1880 		}
1881 	} else if (vdev->vf_token) {
1882 		mutex_lock(&vdev->vf_token->lock);
1883 		if (vdev->vf_token->users) {
1884 			if (!uuid) {
1885 				mutex_unlock(&vdev->vf_token->lock);
1886 				pci_info_ratelimited(vdev->pdev,
1887 					"VF token required to access device\n");
1888 				return -EACCES;
1889 			}
1890 
1891 			if (!uuid_equal(uuid, &vdev->vf_token->uuid)) {
1892 				mutex_unlock(&vdev->vf_token->lock);
1893 				pci_info_ratelimited(vdev->pdev,
1894 					"Incorrect VF token provided for device\n");
1895 				return -EACCES;
1896 			}
1897 		} else if (uuid) {
1898 			uuid_copy(&vdev->vf_token->uuid, uuid);
1899 		}
1900 
1901 		mutex_unlock(&vdev->vf_token->lock);
1902 	} else if (uuid) {
1903 		pci_info_ratelimited(vdev->pdev,
1904 			"VF token incorrectly provided, not a PF or VF\n");
1905 		return -EINVAL;
1906 	}
1907 
1908 	return 0;
1909 }
1910 EXPORT_SYMBOL_GPL(vfio_pci_core_match_token_uuid);
1911 
1912 #define VF_TOKEN_ARG "vf_token="
1913 
vfio_pci_core_match(struct vfio_device * core_vdev,char * buf)1914 int vfio_pci_core_match(struct vfio_device *core_vdev, char *buf)
1915 {
1916 	struct vfio_pci_core_device *vdev =
1917 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1918 	bool vf_token = false;
1919 	uuid_t uuid;
1920 	int ret;
1921 
1922 	if (strncmp(pci_name(vdev->pdev), buf, strlen(pci_name(vdev->pdev))))
1923 		return 0; /* No match */
1924 
1925 	if (strlen(buf) > strlen(pci_name(vdev->pdev))) {
1926 		buf += strlen(pci_name(vdev->pdev));
1927 
1928 		if (*buf != ' ')
1929 			return 0; /* No match: non-whitespace after name */
1930 
1931 		while (*buf) {
1932 			if (*buf == ' ') {
1933 				buf++;
1934 				continue;
1935 			}
1936 
1937 			if (!vf_token && !strncmp(buf, VF_TOKEN_ARG,
1938 						  strlen(VF_TOKEN_ARG))) {
1939 				buf += strlen(VF_TOKEN_ARG);
1940 
1941 				if (strlen(buf) < UUID_STRING_LEN)
1942 					return -EINVAL;
1943 
1944 				ret = uuid_parse(buf, &uuid);
1945 				if (ret)
1946 					return ret;
1947 
1948 				vf_token = true;
1949 				buf += UUID_STRING_LEN;
1950 			} else {
1951 				/* Unknown/duplicate option */
1952 				return -EINVAL;
1953 			}
1954 		}
1955 	}
1956 
1957 	ret = core_vdev->ops->match_token_uuid(core_vdev,
1958 					       vf_token ? &uuid : NULL);
1959 	if (ret)
1960 		return ret;
1961 
1962 	return 1; /* Match */
1963 }
1964 EXPORT_SYMBOL_GPL(vfio_pci_core_match);
1965 
vfio_pci_bus_notifier(struct notifier_block * nb,unsigned long action,void * data)1966 static int vfio_pci_bus_notifier(struct notifier_block *nb,
1967 				 unsigned long action, void *data)
1968 {
1969 	struct vfio_pci_core_device *vdev = container_of(nb,
1970 						    struct vfio_pci_core_device, nb);
1971 	struct device *dev = data;
1972 	struct pci_dev *pdev = to_pci_dev(dev);
1973 	struct pci_dev *physfn = pci_physfn(pdev);
1974 
1975 	if (action == BUS_NOTIFY_ADD_DEVICE &&
1976 	    pdev->is_virtfn && physfn == vdev->pdev) {
1977 		pci_info(vdev->pdev, "Captured SR-IOV VF %s driver_override\n",
1978 			 pci_name(pdev));
1979 		pdev->driver_override = kasprintf(GFP_KERNEL, "%s",
1980 						  vdev->vdev.ops->name);
1981 		WARN_ON(!pdev->driver_override);
1982 	} else if (action == BUS_NOTIFY_BOUND_DRIVER &&
1983 		   pdev->is_virtfn && physfn == vdev->pdev) {
1984 		struct pci_driver *drv = pci_dev_driver(pdev);
1985 
1986 		if (drv && drv != pci_dev_driver(vdev->pdev))
1987 			pci_warn(vdev->pdev,
1988 				 "VF %s bound to driver %s while PF bound to driver %s\n",
1989 				 pci_name(pdev), drv->name,
1990 				 pci_dev_driver(vdev->pdev)->name);
1991 	}
1992 
1993 	return 0;
1994 }
1995 
vfio_pci_vf_init(struct vfio_pci_core_device * vdev)1996 static int vfio_pci_vf_init(struct vfio_pci_core_device *vdev)
1997 {
1998 	struct pci_dev *pdev = vdev->pdev;
1999 	struct vfio_pci_core_device *cur;
2000 	struct pci_dev *physfn;
2001 	int ret;
2002 
2003 	if (pdev->is_virtfn) {
2004 		/*
2005 		 * If this VF was created by our vfio_pci_core_sriov_configure()
2006 		 * then we can find the PF vfio_pci_core_device now, and due to
2007 		 * the locking in pci_disable_sriov() it cannot change until
2008 		 * this VF device driver is removed.
2009 		 */
2010 		physfn = pci_physfn(vdev->pdev);
2011 		mutex_lock(&vfio_pci_sriov_pfs_mutex);
2012 		list_for_each_entry(cur, &vfio_pci_sriov_pfs, sriov_pfs_item) {
2013 			if (cur->pdev == physfn) {
2014 				vdev->sriov_pf_core_dev = cur;
2015 				break;
2016 			}
2017 		}
2018 		mutex_unlock(&vfio_pci_sriov_pfs_mutex);
2019 		return 0;
2020 	}
2021 
2022 	/* Not a SRIOV PF */
2023 	if (!pdev->is_physfn)
2024 		return 0;
2025 
2026 	vdev->vf_token = kzalloc(sizeof(*vdev->vf_token), GFP_KERNEL);
2027 	if (!vdev->vf_token)
2028 		return -ENOMEM;
2029 
2030 	mutex_init(&vdev->vf_token->lock);
2031 	uuid_gen(&vdev->vf_token->uuid);
2032 
2033 	vdev->nb.notifier_call = vfio_pci_bus_notifier;
2034 	ret = bus_register_notifier(&pci_bus_type, &vdev->nb);
2035 	if (ret) {
2036 		kfree(vdev->vf_token);
2037 		return ret;
2038 	}
2039 	return 0;
2040 }
2041 
vfio_pci_vf_uninit(struct vfio_pci_core_device * vdev)2042 static void vfio_pci_vf_uninit(struct vfio_pci_core_device *vdev)
2043 {
2044 	if (!vdev->vf_token)
2045 		return;
2046 
2047 	bus_unregister_notifier(&pci_bus_type, &vdev->nb);
2048 	WARN_ON(vdev->vf_token->users);
2049 	mutex_destroy(&vdev->vf_token->lock);
2050 	kfree(vdev->vf_token);
2051 }
2052 
vfio_pci_vga_init(struct vfio_pci_core_device * vdev)2053 static int vfio_pci_vga_init(struct vfio_pci_core_device *vdev)
2054 {
2055 	struct pci_dev *pdev = vdev->pdev;
2056 	int ret;
2057 
2058 	if (!vfio_pci_is_vga(pdev))
2059 		return 0;
2060 
2061 	ret = aperture_remove_conflicting_pci_devices(pdev, vdev->vdev.ops->name);
2062 	if (ret)
2063 		return ret;
2064 
2065 	ret = vga_client_register(pdev, vfio_pci_set_decode);
2066 	if (ret)
2067 		return ret;
2068 	vga_set_legacy_decoding(pdev, vfio_pci_set_decode(pdev, false));
2069 	return 0;
2070 }
2071 
vfio_pci_vga_uninit(struct vfio_pci_core_device * vdev)2072 static void vfio_pci_vga_uninit(struct vfio_pci_core_device *vdev)
2073 {
2074 	struct pci_dev *pdev = vdev->pdev;
2075 
2076 	if (!vfio_pci_is_vga(pdev))
2077 		return;
2078 	vga_client_unregister(pdev);
2079 	vga_set_legacy_decoding(pdev, VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
2080 					      VGA_RSRC_LEGACY_IO |
2081 					      VGA_RSRC_LEGACY_MEM);
2082 }
2083 
vfio_pci_core_init_dev(struct vfio_device * core_vdev)2084 int vfio_pci_core_init_dev(struct vfio_device *core_vdev)
2085 {
2086 	struct vfio_pci_core_device *vdev =
2087 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
2088 
2089 	vdev->pdev = to_pci_dev(core_vdev->dev);
2090 	vdev->irq_type = VFIO_PCI_NUM_IRQS;
2091 	mutex_init(&vdev->igate);
2092 	spin_lock_init(&vdev->irqlock);
2093 	mutex_init(&vdev->ioeventfds_lock);
2094 	INIT_LIST_HEAD(&vdev->dummy_resources_list);
2095 	INIT_LIST_HEAD(&vdev->ioeventfds_list);
2096 	INIT_LIST_HEAD(&vdev->sriov_pfs_item);
2097 	init_rwsem(&vdev->memory_lock);
2098 	xa_init(&vdev->ctx);
2099 
2100 	return 0;
2101 }
2102 EXPORT_SYMBOL_GPL(vfio_pci_core_init_dev);
2103 
vfio_pci_core_release_dev(struct vfio_device * core_vdev)2104 void vfio_pci_core_release_dev(struct vfio_device *core_vdev)
2105 {
2106 	struct vfio_pci_core_device *vdev =
2107 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
2108 
2109 	mutex_destroy(&vdev->igate);
2110 	mutex_destroy(&vdev->ioeventfds_lock);
2111 	kfree(vdev->region);
2112 	kfree(vdev->pm_save);
2113 }
2114 EXPORT_SYMBOL_GPL(vfio_pci_core_release_dev);
2115 
vfio_pci_core_register_device(struct vfio_pci_core_device * vdev)2116 int vfio_pci_core_register_device(struct vfio_pci_core_device *vdev)
2117 {
2118 	struct pci_dev *pdev = vdev->pdev;
2119 	struct device *dev = &pdev->dev;
2120 	int ret;
2121 
2122 	/* Drivers must set the vfio_pci_core_device to their drvdata */
2123 	if (WARN_ON(vdev != dev_get_drvdata(dev)))
2124 		return -EINVAL;
2125 
2126 	if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
2127 		return -EINVAL;
2128 
2129 	if (vdev->vdev.mig_ops) {
2130 		if (!(vdev->vdev.mig_ops->migration_get_state &&
2131 		      vdev->vdev.mig_ops->migration_set_state &&
2132 		      vdev->vdev.mig_ops->migration_get_data_size) ||
2133 		    !(vdev->vdev.migration_flags & VFIO_MIGRATION_STOP_COPY))
2134 			return -EINVAL;
2135 	}
2136 
2137 	if (vdev->vdev.log_ops && !(vdev->vdev.log_ops->log_start &&
2138 	    vdev->vdev.log_ops->log_stop &&
2139 	    vdev->vdev.log_ops->log_read_and_clear))
2140 		return -EINVAL;
2141 
2142 	/*
2143 	 * Prevent binding to PFs with VFs enabled, the VFs might be in use
2144 	 * by the host or other users.  We cannot capture the VFs if they
2145 	 * already exist, nor can we track VF users.  Disabling SR-IOV here
2146 	 * would initiate removing the VFs, which would unbind the driver,
2147 	 * which is prone to blocking if that VF is also in use by vfio-pci.
2148 	 * Just reject these PFs and let the user sort it out.
2149 	 */
2150 	if (pci_num_vf(pdev)) {
2151 		pci_warn(pdev, "Cannot bind to PF with SR-IOV enabled\n");
2152 		return -EBUSY;
2153 	}
2154 
2155 	if (pci_is_root_bus(pdev->bus) || pdev->is_virtfn) {
2156 		ret = vfio_assign_device_set(&vdev->vdev, vdev);
2157 	} else if (!pci_probe_reset_slot(pdev->slot)) {
2158 		ret = vfio_assign_device_set(&vdev->vdev, pdev->slot);
2159 	} else {
2160 		/*
2161 		 * If there is no slot reset support for this device, the whole
2162 		 * bus needs to be grouped together to support bus-wide resets.
2163 		 */
2164 		ret = vfio_assign_device_set(&vdev->vdev, pdev->bus);
2165 	}
2166 
2167 	if (ret)
2168 		return ret;
2169 	ret = vfio_pci_vf_init(vdev);
2170 	if (ret)
2171 		return ret;
2172 	ret = vfio_pci_vga_init(vdev);
2173 	if (ret)
2174 		goto out_vf;
2175 
2176 	vfio_pci_probe_power_state(vdev);
2177 
2178 	/*
2179 	 * pci-core sets the device power state to an unknown value at
2180 	 * bootup and after being removed from a driver.  The only
2181 	 * transition it allows from this unknown state is to D0, which
2182 	 * typically happens when a driver calls pci_enable_device().
2183 	 * We're not ready to enable the device yet, but we do want to
2184 	 * be able to get to D3.  Therefore first do a D0 transition
2185 	 * before enabling runtime PM.
2186 	 */
2187 	vfio_pci_set_power_state(vdev, PCI_D0);
2188 
2189 	dev->driver->pm = &vfio_pci_core_pm_ops;
2190 	pm_runtime_allow(dev);
2191 	if (!disable_idle_d3)
2192 		pm_runtime_put(dev);
2193 
2194 	ret = vfio_register_group_dev(&vdev->vdev);
2195 	if (ret)
2196 		goto out_power;
2197 	return 0;
2198 
2199 out_power:
2200 	if (!disable_idle_d3)
2201 		pm_runtime_get_noresume(dev);
2202 
2203 	pm_runtime_forbid(dev);
2204 out_vf:
2205 	vfio_pci_vf_uninit(vdev);
2206 	return ret;
2207 }
2208 EXPORT_SYMBOL_GPL(vfio_pci_core_register_device);
2209 
vfio_pci_core_unregister_device(struct vfio_pci_core_device * vdev)2210 void vfio_pci_core_unregister_device(struct vfio_pci_core_device *vdev)
2211 {
2212 	vfio_pci_core_sriov_configure(vdev, 0);
2213 
2214 	vfio_unregister_group_dev(&vdev->vdev);
2215 
2216 	vfio_pci_vf_uninit(vdev);
2217 	vfio_pci_vga_uninit(vdev);
2218 
2219 	if (!disable_idle_d3)
2220 		pm_runtime_get_noresume(&vdev->pdev->dev);
2221 
2222 	pm_runtime_forbid(&vdev->pdev->dev);
2223 }
2224 EXPORT_SYMBOL_GPL(vfio_pci_core_unregister_device);
2225 
vfio_pci_core_aer_err_detected(struct pci_dev * pdev,pci_channel_state_t state)2226 pci_ers_result_t vfio_pci_core_aer_err_detected(struct pci_dev *pdev,
2227 						pci_channel_state_t state)
2228 {
2229 	struct vfio_pci_core_device *vdev = dev_get_drvdata(&pdev->dev);
2230 
2231 	mutex_lock(&vdev->igate);
2232 
2233 	if (vdev->err_trigger)
2234 		eventfd_signal(vdev->err_trigger);
2235 
2236 	mutex_unlock(&vdev->igate);
2237 
2238 	return PCI_ERS_RESULT_CAN_RECOVER;
2239 }
2240 EXPORT_SYMBOL_GPL(vfio_pci_core_aer_err_detected);
2241 
vfio_pci_core_sriov_configure(struct vfio_pci_core_device * vdev,int nr_virtfn)2242 int vfio_pci_core_sriov_configure(struct vfio_pci_core_device *vdev,
2243 				  int nr_virtfn)
2244 {
2245 	struct pci_dev *pdev = vdev->pdev;
2246 	int ret = 0;
2247 
2248 	device_lock_assert(&pdev->dev);
2249 
2250 	if (nr_virtfn) {
2251 		mutex_lock(&vfio_pci_sriov_pfs_mutex);
2252 		/*
2253 		 * The thread that adds the vdev to the list is the only thread
2254 		 * that gets to call pci_enable_sriov() and we will only allow
2255 		 * it to be called once without going through
2256 		 * pci_disable_sriov()
2257 		 */
2258 		if (!list_empty(&vdev->sriov_pfs_item)) {
2259 			ret = -EINVAL;
2260 			goto out_unlock;
2261 		}
2262 		list_add_tail(&vdev->sriov_pfs_item, &vfio_pci_sriov_pfs);
2263 		mutex_unlock(&vfio_pci_sriov_pfs_mutex);
2264 
2265 		/*
2266 		 * The PF power state should always be higher than the VF power
2267 		 * state. The PF can be in low power state either with runtime
2268 		 * power management (when there is no user) or PCI_PM_CTRL
2269 		 * register write by the user. If PF is in the low power state,
2270 		 * then change the power state to D0 first before enabling
2271 		 * SR-IOV. Also, this function can be called at any time, and
2272 		 * userspace PCI_PM_CTRL write can race against this code path,
2273 		 * so protect the same with 'memory_lock'.
2274 		 */
2275 		ret = pm_runtime_resume_and_get(&pdev->dev);
2276 		if (ret)
2277 			goto out_del;
2278 
2279 		down_write(&vdev->memory_lock);
2280 		vfio_pci_set_power_state(vdev, PCI_D0);
2281 		ret = pci_enable_sriov(pdev, nr_virtfn);
2282 		up_write(&vdev->memory_lock);
2283 		if (ret) {
2284 			pm_runtime_put(&pdev->dev);
2285 			goto out_del;
2286 		}
2287 		return nr_virtfn;
2288 	}
2289 
2290 	if (pci_num_vf(pdev)) {
2291 		pci_disable_sriov(pdev);
2292 		pm_runtime_put(&pdev->dev);
2293 	}
2294 
2295 out_del:
2296 	mutex_lock(&vfio_pci_sriov_pfs_mutex);
2297 	list_del_init(&vdev->sriov_pfs_item);
2298 out_unlock:
2299 	mutex_unlock(&vfio_pci_sriov_pfs_mutex);
2300 	return ret;
2301 }
2302 EXPORT_SYMBOL_GPL(vfio_pci_core_sriov_configure);
2303 
2304 const struct pci_error_handlers vfio_pci_core_err_handlers = {
2305 	.error_detected = vfio_pci_core_aer_err_detected,
2306 };
2307 EXPORT_SYMBOL_GPL(vfio_pci_core_err_handlers);
2308 
vfio_dev_in_groups(struct vfio_device * vdev,struct vfio_pci_group_info * groups)2309 static bool vfio_dev_in_groups(struct vfio_device *vdev,
2310 			       struct vfio_pci_group_info *groups)
2311 {
2312 	unsigned int i;
2313 
2314 	if (!groups)
2315 		return false;
2316 
2317 	for (i = 0; i < groups->count; i++)
2318 		if (vfio_file_has_dev(groups->files[i], vdev))
2319 			return true;
2320 	return false;
2321 }
2322 
vfio_pci_is_device_in_set(struct pci_dev * pdev,void * data)2323 static int vfio_pci_is_device_in_set(struct pci_dev *pdev, void *data)
2324 {
2325 	struct vfio_device_set *dev_set = data;
2326 
2327 	return vfio_find_device_in_devset(dev_set, &pdev->dev) ? 0 : -ENODEV;
2328 }
2329 
2330 /*
2331  * vfio-core considers a group to be viable and will create a vfio_device even
2332  * if some devices are bound to drivers like pci-stub or pcieport. Here we
2333  * require all PCI devices to be inside our dev_set since that ensures they stay
2334  * put and that every driver controlling the device can co-ordinate with the
2335  * device reset.
2336  *
2337  * Returns the pci_dev to pass to pci_reset_bus() if every PCI device to be
2338  * reset is inside the dev_set, and pci_reset_bus() can succeed. NULL otherwise.
2339  */
2340 static struct pci_dev *
vfio_pci_dev_set_resettable(struct vfio_device_set * dev_set)2341 vfio_pci_dev_set_resettable(struct vfio_device_set *dev_set)
2342 {
2343 	struct pci_dev *pdev;
2344 
2345 	lockdep_assert_held(&dev_set->lock);
2346 
2347 	/*
2348 	 * By definition all PCI devices in the dev_set share the same PCI
2349 	 * reset, so any pci_dev will have the same outcomes for
2350 	 * pci_probe_reset_*() and pci_reset_bus().
2351 	 */
2352 	pdev = list_first_entry(&dev_set->device_list,
2353 				struct vfio_pci_core_device,
2354 				vdev.dev_set_list)->pdev;
2355 
2356 	/* pci_reset_bus() is supported */
2357 	if (pci_probe_reset_slot(pdev->slot) && pci_probe_reset_bus(pdev->bus))
2358 		return NULL;
2359 
2360 	if (vfio_pci_for_each_slot_or_bus(pdev, vfio_pci_is_device_in_set,
2361 					  dev_set,
2362 					  !pci_probe_reset_slot(pdev->slot)))
2363 		return NULL;
2364 	return pdev;
2365 }
2366 
vfio_pci_dev_set_pm_runtime_get(struct vfio_device_set * dev_set)2367 static int vfio_pci_dev_set_pm_runtime_get(struct vfio_device_set *dev_set)
2368 {
2369 	struct vfio_pci_core_device *cur;
2370 	int ret;
2371 
2372 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2373 		ret = pm_runtime_resume_and_get(&cur->pdev->dev);
2374 		if (ret)
2375 			goto unwind;
2376 	}
2377 
2378 	return 0;
2379 
2380 unwind:
2381 	list_for_each_entry_continue_reverse(cur, &dev_set->device_list,
2382 					     vdev.dev_set_list)
2383 		pm_runtime_put(&cur->pdev->dev);
2384 
2385 	return ret;
2386 }
2387 
vfio_pci_dev_set_hot_reset(struct vfio_device_set * dev_set,struct vfio_pci_group_info * groups,struct iommufd_ctx * iommufd_ctx)2388 static int vfio_pci_dev_set_hot_reset(struct vfio_device_set *dev_set,
2389 				      struct vfio_pci_group_info *groups,
2390 				      struct iommufd_ctx *iommufd_ctx)
2391 {
2392 	struct vfio_pci_core_device *vdev;
2393 	struct pci_dev *pdev;
2394 	int ret;
2395 
2396 	mutex_lock(&dev_set->lock);
2397 
2398 	pdev = vfio_pci_dev_set_resettable(dev_set);
2399 	if (!pdev) {
2400 		ret = -EINVAL;
2401 		goto err_unlock;
2402 	}
2403 
2404 	/*
2405 	 * Some of the devices in the dev_set can be in the runtime suspended
2406 	 * state. Increment the usage count for all the devices in the dev_set
2407 	 * before reset and decrement the same after reset.
2408 	 */
2409 	ret = vfio_pci_dev_set_pm_runtime_get(dev_set);
2410 	if (ret)
2411 		goto err_unlock;
2412 
2413 	list_for_each_entry(vdev, &dev_set->device_list, vdev.dev_set_list) {
2414 		bool owned;
2415 
2416 		/*
2417 		 * Test whether all the affected devices can be reset by the
2418 		 * user.
2419 		 *
2420 		 * If called from a group opened device and the user provides
2421 		 * a set of groups, all the devices in the dev_set should be
2422 		 * contained by the set of groups provided by the user.
2423 		 *
2424 		 * If called from a cdev opened device and the user provides
2425 		 * a zero-length array, all the devices in the dev_set must
2426 		 * be bound to the same iommufd_ctx as the input iommufd_ctx.
2427 		 * If there is any device that has not been bound to any
2428 		 * iommufd_ctx yet, check if its iommu_group has any device
2429 		 * bound to the input iommufd_ctx.  Such devices can be
2430 		 * considered owned by the input iommufd_ctx as the device
2431 		 * cannot be owned by another iommufd_ctx when its iommu_group
2432 		 * is owned.
2433 		 *
2434 		 * Otherwise, reset is not allowed.
2435 		 */
2436 		if (iommufd_ctx) {
2437 			int devid = vfio_iommufd_get_dev_id(&vdev->vdev,
2438 							    iommufd_ctx);
2439 
2440 			owned = (devid > 0 || devid == -ENOENT);
2441 		} else {
2442 			owned = vfio_dev_in_groups(&vdev->vdev, groups);
2443 		}
2444 
2445 		if (!owned) {
2446 			ret = -EINVAL;
2447 			break;
2448 		}
2449 
2450 		/*
2451 		 * Take the memory write lock for each device and zap BAR
2452 		 * mappings to prevent the user accessing the device while in
2453 		 * reset.  Locking multiple devices is prone to deadlock,
2454 		 * runaway and unwind if we hit contention.
2455 		 */
2456 		if (!down_write_trylock(&vdev->memory_lock)) {
2457 			ret = -EBUSY;
2458 			break;
2459 		}
2460 
2461 		vfio_pci_zap_bars(vdev);
2462 	}
2463 
2464 	if (!list_entry_is_head(vdev,
2465 				&dev_set->device_list, vdev.dev_set_list)) {
2466 		vdev = list_prev_entry(vdev, vdev.dev_set_list);
2467 		goto err_undo;
2468 	}
2469 
2470 	/*
2471 	 * The pci_reset_bus() will reset all the devices in the bus.
2472 	 * The power state can be non-D0 for some of the devices in the bus.
2473 	 * For these devices, the pci_reset_bus() will internally set
2474 	 * the power state to D0 without vfio driver involvement.
2475 	 * For the devices which have NoSoftRst-, the reset function can
2476 	 * cause the PCI config space reset without restoring the original
2477 	 * state (saved locally in 'vdev->pm_save').
2478 	 */
2479 	list_for_each_entry(vdev, &dev_set->device_list, vdev.dev_set_list)
2480 		vfio_pci_set_power_state(vdev, PCI_D0);
2481 
2482 	ret = pci_reset_bus(pdev);
2483 
2484 	vdev = list_last_entry(&dev_set->device_list,
2485 			       struct vfio_pci_core_device, vdev.dev_set_list);
2486 
2487 err_undo:
2488 	list_for_each_entry_from_reverse(vdev, &dev_set->device_list,
2489 					 vdev.dev_set_list)
2490 		up_write(&vdev->memory_lock);
2491 
2492 	list_for_each_entry(vdev, &dev_set->device_list, vdev.dev_set_list)
2493 		pm_runtime_put(&vdev->pdev->dev);
2494 
2495 err_unlock:
2496 	mutex_unlock(&dev_set->lock);
2497 	return ret;
2498 }
2499 
vfio_pci_dev_set_needs_reset(struct vfio_device_set * dev_set)2500 static bool vfio_pci_dev_set_needs_reset(struct vfio_device_set *dev_set)
2501 {
2502 	struct vfio_pci_core_device *cur;
2503 	bool needs_reset = false;
2504 
2505 	/* No other VFIO device in the set can be open. */
2506 	if (vfio_device_set_open_count(dev_set) > 1)
2507 		return false;
2508 
2509 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list)
2510 		needs_reset |= cur->needs_reset;
2511 	return needs_reset;
2512 }
2513 
2514 /*
2515  * If a bus or slot reset is available for the provided dev_set and:
2516  *  - All of the devices affected by that bus or slot reset are unused
2517  *  - At least one of the affected devices is marked dirty via
2518  *    needs_reset (such as by lack of FLR support)
2519  * Then attempt to perform that bus or slot reset.
2520  */
vfio_pci_dev_set_try_reset(struct vfio_device_set * dev_set)2521 static void vfio_pci_dev_set_try_reset(struct vfio_device_set *dev_set)
2522 {
2523 	struct vfio_pci_core_device *cur;
2524 	struct pci_dev *pdev;
2525 	bool reset_done = false;
2526 
2527 	if (!vfio_pci_dev_set_needs_reset(dev_set))
2528 		return;
2529 
2530 	pdev = vfio_pci_dev_set_resettable(dev_set);
2531 	if (!pdev)
2532 		return;
2533 
2534 	/*
2535 	 * Some of the devices in the bus can be in the runtime suspended
2536 	 * state. Increment the usage count for all the devices in the dev_set
2537 	 * before reset and decrement the same after reset.
2538 	 */
2539 	if (!disable_idle_d3 && vfio_pci_dev_set_pm_runtime_get(dev_set))
2540 		return;
2541 
2542 	if (!pci_reset_bus(pdev))
2543 		reset_done = true;
2544 
2545 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2546 		if (reset_done)
2547 			cur->needs_reset = false;
2548 
2549 		if (!disable_idle_d3)
2550 			pm_runtime_put(&cur->pdev->dev);
2551 	}
2552 }
2553 
vfio_pci_core_set_params(bool is_nointxmask,bool is_disable_vga,bool is_disable_idle_d3)2554 void vfio_pci_core_set_params(bool is_nointxmask, bool is_disable_vga,
2555 			      bool is_disable_idle_d3)
2556 {
2557 	nointxmask = is_nointxmask;
2558 	disable_vga = is_disable_vga;
2559 	disable_idle_d3 = is_disable_idle_d3;
2560 }
2561 EXPORT_SYMBOL_GPL(vfio_pci_core_set_params);
2562 
vfio_pci_core_cleanup(void)2563 static void vfio_pci_core_cleanup(void)
2564 {
2565 	vfio_pci_uninit_perm_bits();
2566 }
2567 
vfio_pci_core_init(void)2568 static int __init vfio_pci_core_init(void)
2569 {
2570 	/* Allocate shared config space permission data used by all devices */
2571 	return vfio_pci_init_perm_bits();
2572 }
2573 
2574 module_init(vfio_pci_core_init);
2575 module_exit(vfio_pci_core_cleanup);
2576 
2577 MODULE_LICENSE("GPL v2");
2578 MODULE_AUTHOR(DRIVER_AUTHOR);
2579 MODULE_DESCRIPTION(DRIVER_DESC);
2580