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