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