xref: /linux/drivers/vfio/pci/vfio_pci_core.c (revision bf4afc53b77aeaa48b5409da5c8da6bb4eff7f43)
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 	switch (order) {
1674 	case 0:
1675 		return vmf_insert_pfn(vmf->vma, vmf->address, pfn);
1676 #ifdef CONFIG_ARCH_SUPPORTS_PMD_PFNMAP
1677 	case PMD_ORDER:
1678 		return vmf_insert_pfn_pmd(vmf, pfn, false);
1679 #endif
1680 #ifdef CONFIG_ARCH_SUPPORTS_PUD_PFNMAP
1681 	case PUD_ORDER:
1682 		return vmf_insert_pfn_pud(vmf, pfn, false);
1683 		break;
1684 #endif
1685 	default:
1686 		return VM_FAULT_FALLBACK;
1687 	}
1688 }
1689 EXPORT_SYMBOL_GPL(vfio_pci_vmf_insert_pfn);
1690 
vfio_pci_mmap_huge_fault(struct vm_fault * vmf,unsigned int order)1691 static vm_fault_t vfio_pci_mmap_huge_fault(struct vm_fault *vmf,
1692 					   unsigned int order)
1693 {
1694 	struct vm_area_struct *vma = vmf->vma;
1695 	struct vfio_pci_core_device *vdev = vma->vm_private_data;
1696 	unsigned long addr = vmf->address & ~((PAGE_SIZE << order) - 1);
1697 	unsigned long pgoff = (addr - vma->vm_start) >> PAGE_SHIFT;
1698 	unsigned long pfn = vma_to_pfn(vma) + pgoff;
1699 	vm_fault_t ret = VM_FAULT_FALLBACK;
1700 
1701 	if (is_aligned_for_order(vma, addr, pfn, order)) {
1702 		scoped_guard(rwsem_read, &vdev->memory_lock)
1703 			ret = vfio_pci_vmf_insert_pfn(vdev, vmf, pfn, order);
1704 	}
1705 
1706 	dev_dbg_ratelimited(&vdev->pdev->dev,
1707 			   "%s(,order = %d) BAR %ld page offset 0x%lx: 0x%x\n",
1708 			    __func__, order,
1709 			    vma->vm_pgoff >>
1710 				(VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT),
1711 			    pgoff, (unsigned int)ret);
1712 
1713 	return ret;
1714 }
1715 
vfio_pci_mmap_page_fault(struct vm_fault * vmf)1716 static vm_fault_t vfio_pci_mmap_page_fault(struct vm_fault *vmf)
1717 {
1718 	return vfio_pci_mmap_huge_fault(vmf, 0);
1719 }
1720 
1721 static const struct vm_operations_struct vfio_pci_mmap_ops = {
1722 	.fault = vfio_pci_mmap_page_fault,
1723 #ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
1724 	.huge_fault = vfio_pci_mmap_huge_fault,
1725 #endif
1726 };
1727 
vfio_pci_core_mmap(struct vfio_device * core_vdev,struct vm_area_struct * vma)1728 int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma)
1729 {
1730 	struct vfio_pci_core_device *vdev =
1731 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1732 	struct pci_dev *pdev = vdev->pdev;
1733 	unsigned int index;
1734 	u64 phys_len, req_len, pgoff, req_start;
1735 	int ret;
1736 
1737 	index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1738 
1739 	if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1740 		return -EINVAL;
1741 	if (vma->vm_end < vma->vm_start)
1742 		return -EINVAL;
1743 	if ((vma->vm_flags & VM_SHARED) == 0)
1744 		return -EINVAL;
1745 	if (index >= VFIO_PCI_NUM_REGIONS) {
1746 		int regnum = index - VFIO_PCI_NUM_REGIONS;
1747 		struct vfio_pci_region *region = vdev->region + regnum;
1748 
1749 		if (region->ops && region->ops->mmap &&
1750 		    (region->flags & VFIO_REGION_INFO_FLAG_MMAP))
1751 			return region->ops->mmap(vdev, region, vma);
1752 		return -EINVAL;
1753 	}
1754 	if (index >= VFIO_PCI_ROM_REGION_INDEX)
1755 		return -EINVAL;
1756 	if (!vdev->bar_mmap_supported[index])
1757 		return -EINVAL;
1758 
1759 	phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1760 	req_len = vma->vm_end - vma->vm_start;
1761 	pgoff = vma->vm_pgoff &
1762 		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1763 	req_start = pgoff << PAGE_SHIFT;
1764 
1765 	if (req_start + req_len > phys_len)
1766 		return -EINVAL;
1767 
1768 	/*
1769 	 * Even though we don't make use of the barmap for the mmap,
1770 	 * we need to request the region and the barmap tracks that.
1771 	 */
1772 	ret = vfio_pci_core_setup_barmap(vdev, index);
1773 	if (ret)
1774 		return ret;
1775 
1776 	vma->vm_private_data = vdev;
1777 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1778 	vma->vm_page_prot = pgprot_decrypted(vma->vm_page_prot);
1779 
1780 	/*
1781 	 * Set vm_flags now, they should not be changed in the fault handler.
1782 	 * We want the same flags and page protection (decrypted above) as
1783 	 * io_remap_pfn_range() would set.
1784 	 *
1785 	 * VM_ALLOW_ANY_UNCACHED: The VMA flag is implemented for ARM64,
1786 	 * allowing KVM stage 2 device mapping attributes to use Normal-NC
1787 	 * rather than DEVICE_nGnRE, which allows guest mappings
1788 	 * supporting write-combining attributes (WC). ARM does not
1789 	 * architecturally guarantee this is safe, and indeed some MMIO
1790 	 * regions like the GICv2 VCPU interface can trigger uncontained
1791 	 * faults if Normal-NC is used.
1792 	 *
1793 	 * To safely use VFIO in KVM the platform must guarantee full
1794 	 * safety in the guest where no action taken against a MMIO
1795 	 * mapping can trigger an uncontained failure. The assumption is
1796 	 * that most VFIO PCI platforms support this for both mapping types,
1797 	 * at least in common flows, based on some expectations of how
1798 	 * PCI IP is integrated. Hence VM_ALLOW_ANY_UNCACHED is set in
1799 	 * the VMA flags.
1800 	 */
1801 	vm_flags_set(vma, VM_ALLOW_ANY_UNCACHED | VM_IO | VM_PFNMAP |
1802 			VM_DONTEXPAND | VM_DONTDUMP);
1803 	vma->vm_ops = &vfio_pci_mmap_ops;
1804 
1805 	return 0;
1806 }
1807 EXPORT_SYMBOL_GPL(vfio_pci_core_mmap);
1808 
vfio_pci_core_request(struct vfio_device * core_vdev,unsigned int count)1809 void vfio_pci_core_request(struct vfio_device *core_vdev, unsigned int count)
1810 {
1811 	struct vfio_pci_core_device *vdev =
1812 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1813 	struct pci_dev *pdev = vdev->pdev;
1814 	struct vfio_pci_eventfd *eventfd;
1815 
1816 	rcu_read_lock();
1817 	eventfd = rcu_dereference(vdev->req_trigger);
1818 	if (eventfd) {
1819 		if (!(count % 10))
1820 			pci_notice_ratelimited(pdev,
1821 				"Relaying device request to user (#%u)\n",
1822 				count);
1823 		eventfd_signal(eventfd->ctx);
1824 	} else if (count == 0) {
1825 		pci_warn(pdev,
1826 			"No device request channel registered, blocked until released by user\n");
1827 	}
1828 	rcu_read_unlock();
1829 }
1830 EXPORT_SYMBOL_GPL(vfio_pci_core_request);
1831 
vfio_pci_core_match_token_uuid(struct vfio_device * core_vdev,const uuid_t * uuid)1832 int vfio_pci_core_match_token_uuid(struct vfio_device *core_vdev,
1833 				   const uuid_t *uuid)
1834 
1835 {
1836 	struct vfio_pci_core_device *vdev =
1837 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1838 
1839 	/*
1840 	 * There's always some degree of trust or collaboration between SR-IOV
1841 	 * PF and VFs, even if just that the PF hosts the SR-IOV capability and
1842 	 * can disrupt VFs with a reset, but often the PF has more explicit
1843 	 * access to deny service to the VF or access data passed through the
1844 	 * VF.  We therefore require an opt-in via a shared VF token (UUID) to
1845 	 * represent this trust.  This both prevents that a VF driver might
1846 	 * assume the PF driver is a trusted, in-kernel driver, and also that
1847 	 * a PF driver might be replaced with a rogue driver, unknown to in-use
1848 	 * VF drivers.
1849 	 *
1850 	 * Therefore when presented with a VF, if the PF is a vfio device and
1851 	 * it is bound to the vfio-pci driver, the user needs to provide a VF
1852 	 * token to access the device, in the form of appending a vf_token to
1853 	 * the device name, for example:
1854 	 *
1855 	 * "0000:04:10.0 vf_token=bd8d9d2b-5a5f-4f5a-a211-f591514ba1f3"
1856 	 *
1857 	 * When presented with a PF which has VFs in use, the user must also
1858 	 * provide the current VF token to prove collaboration with existing
1859 	 * VF users.  If VFs are not in use, the VF token provided for the PF
1860 	 * device will act to set the VF token.
1861 	 *
1862 	 * If the VF token is provided but unused, an error is generated.
1863 	 */
1864 	if (vdev->pdev->is_virtfn) {
1865 		struct vfio_pci_core_device *pf_vdev = vdev->sriov_pf_core_dev;
1866 		bool match;
1867 
1868 		if (!pf_vdev) {
1869 			if (!uuid)
1870 				return 0; /* PF is not vfio-pci, no VF token */
1871 
1872 			pci_info_ratelimited(vdev->pdev,
1873 				"VF token incorrectly provided, PF not bound to vfio-pci\n");
1874 			return -EINVAL;
1875 		}
1876 
1877 		if (!uuid) {
1878 			pci_info_ratelimited(vdev->pdev,
1879 				"VF token required to access device\n");
1880 			return -EACCES;
1881 		}
1882 
1883 		mutex_lock(&pf_vdev->vf_token->lock);
1884 		match = uuid_equal(uuid, &pf_vdev->vf_token->uuid);
1885 		mutex_unlock(&pf_vdev->vf_token->lock);
1886 
1887 		if (!match) {
1888 			pci_info_ratelimited(vdev->pdev,
1889 				"Incorrect VF token provided for device\n");
1890 			return -EACCES;
1891 		}
1892 	} else if (vdev->vf_token) {
1893 		mutex_lock(&vdev->vf_token->lock);
1894 		if (vdev->vf_token->users) {
1895 			if (!uuid) {
1896 				mutex_unlock(&vdev->vf_token->lock);
1897 				pci_info_ratelimited(vdev->pdev,
1898 					"VF token required to access device\n");
1899 				return -EACCES;
1900 			}
1901 
1902 			if (!uuid_equal(uuid, &vdev->vf_token->uuid)) {
1903 				mutex_unlock(&vdev->vf_token->lock);
1904 				pci_info_ratelimited(vdev->pdev,
1905 					"Incorrect VF token provided for device\n");
1906 				return -EACCES;
1907 			}
1908 		} else if (uuid) {
1909 			uuid_copy(&vdev->vf_token->uuid, uuid);
1910 		}
1911 
1912 		mutex_unlock(&vdev->vf_token->lock);
1913 	} else if (uuid) {
1914 		pci_info_ratelimited(vdev->pdev,
1915 			"VF token incorrectly provided, not a PF or VF\n");
1916 		return -EINVAL;
1917 	}
1918 
1919 	return 0;
1920 }
1921 EXPORT_SYMBOL_GPL(vfio_pci_core_match_token_uuid);
1922 
1923 #define VF_TOKEN_ARG "vf_token="
1924 
vfio_pci_core_match(struct vfio_device * core_vdev,char * buf)1925 int vfio_pci_core_match(struct vfio_device *core_vdev, char *buf)
1926 {
1927 	struct vfio_pci_core_device *vdev =
1928 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1929 	bool vf_token = false;
1930 	uuid_t uuid;
1931 	int ret;
1932 
1933 	if (strncmp(pci_name(vdev->pdev), buf, strlen(pci_name(vdev->pdev))))
1934 		return 0; /* No match */
1935 
1936 	if (strlen(buf) > strlen(pci_name(vdev->pdev))) {
1937 		buf += strlen(pci_name(vdev->pdev));
1938 
1939 		if (*buf != ' ')
1940 			return 0; /* No match: non-whitespace after name */
1941 
1942 		while (*buf) {
1943 			if (*buf == ' ') {
1944 				buf++;
1945 				continue;
1946 			}
1947 
1948 			if (!vf_token && !strncmp(buf, VF_TOKEN_ARG,
1949 						  strlen(VF_TOKEN_ARG))) {
1950 				buf += strlen(VF_TOKEN_ARG);
1951 
1952 				if (strlen(buf) < UUID_STRING_LEN)
1953 					return -EINVAL;
1954 
1955 				ret = uuid_parse(buf, &uuid);
1956 				if (ret)
1957 					return ret;
1958 
1959 				vf_token = true;
1960 				buf += UUID_STRING_LEN;
1961 			} else {
1962 				/* Unknown/duplicate option */
1963 				return -EINVAL;
1964 			}
1965 		}
1966 	}
1967 
1968 	ret = core_vdev->ops->match_token_uuid(core_vdev,
1969 					       vf_token ? &uuid : NULL);
1970 	if (ret)
1971 		return ret;
1972 
1973 	return 1; /* Match */
1974 }
1975 EXPORT_SYMBOL_GPL(vfio_pci_core_match);
1976 
vfio_pci_bus_notifier(struct notifier_block * nb,unsigned long action,void * data)1977 static int vfio_pci_bus_notifier(struct notifier_block *nb,
1978 				 unsigned long action, void *data)
1979 {
1980 	struct vfio_pci_core_device *vdev = container_of(nb,
1981 						    struct vfio_pci_core_device, nb);
1982 	struct device *dev = data;
1983 	struct pci_dev *pdev = to_pci_dev(dev);
1984 	struct pci_dev *physfn = pci_physfn(pdev);
1985 
1986 	if (action == BUS_NOTIFY_ADD_DEVICE &&
1987 	    pdev->is_virtfn && physfn == vdev->pdev) {
1988 		pci_info(vdev->pdev, "Captured SR-IOV VF %s driver_override\n",
1989 			 pci_name(pdev));
1990 		pdev->driver_override = kasprintf(GFP_KERNEL, "%s",
1991 						  vdev->vdev.ops->name);
1992 		WARN_ON(!pdev->driver_override);
1993 	} else if (action == BUS_NOTIFY_BOUND_DRIVER &&
1994 		   pdev->is_virtfn && physfn == vdev->pdev) {
1995 		struct pci_driver *drv = pci_dev_driver(pdev);
1996 
1997 		if (drv && drv != pci_dev_driver(vdev->pdev))
1998 			pci_warn(vdev->pdev,
1999 				 "VF %s bound to driver %s while PF bound to driver %s\n",
2000 				 pci_name(pdev), drv->name,
2001 				 pci_dev_driver(vdev->pdev)->name);
2002 	}
2003 
2004 	return 0;
2005 }
2006 
vfio_pci_vf_init(struct vfio_pci_core_device * vdev)2007 static int vfio_pci_vf_init(struct vfio_pci_core_device *vdev)
2008 {
2009 	struct pci_dev *pdev = vdev->pdev;
2010 	struct vfio_pci_core_device *cur;
2011 	struct pci_dev *physfn;
2012 	int ret;
2013 
2014 	if (pdev->is_virtfn) {
2015 		/*
2016 		 * If this VF was created by our vfio_pci_core_sriov_configure()
2017 		 * then we can find the PF vfio_pci_core_device now, and due to
2018 		 * the locking in pci_disable_sriov() it cannot change until
2019 		 * this VF device driver is removed.
2020 		 */
2021 		physfn = pci_physfn(vdev->pdev);
2022 		mutex_lock(&vfio_pci_sriov_pfs_mutex);
2023 		list_for_each_entry(cur, &vfio_pci_sriov_pfs, sriov_pfs_item) {
2024 			if (cur->pdev == physfn) {
2025 				vdev->sriov_pf_core_dev = cur;
2026 				break;
2027 			}
2028 		}
2029 		mutex_unlock(&vfio_pci_sriov_pfs_mutex);
2030 		return 0;
2031 	}
2032 
2033 	/* Not a SRIOV PF */
2034 	if (!pdev->is_physfn)
2035 		return 0;
2036 
2037 	vdev->vf_token = kzalloc_obj(*vdev->vf_token);
2038 	if (!vdev->vf_token)
2039 		return -ENOMEM;
2040 
2041 	mutex_init(&vdev->vf_token->lock);
2042 	uuid_gen(&vdev->vf_token->uuid);
2043 
2044 	vdev->nb.notifier_call = vfio_pci_bus_notifier;
2045 	ret = bus_register_notifier(&pci_bus_type, &vdev->nb);
2046 	if (ret) {
2047 		kfree(vdev->vf_token);
2048 		return ret;
2049 	}
2050 	return 0;
2051 }
2052 
vfio_pci_vf_uninit(struct vfio_pci_core_device * vdev)2053 static void vfio_pci_vf_uninit(struct vfio_pci_core_device *vdev)
2054 {
2055 	if (!vdev->vf_token)
2056 		return;
2057 
2058 	bus_unregister_notifier(&pci_bus_type, &vdev->nb);
2059 	WARN_ON(vdev->vf_token->users);
2060 	mutex_destroy(&vdev->vf_token->lock);
2061 	kfree(vdev->vf_token);
2062 }
2063 
vfio_pci_vga_init(struct vfio_pci_core_device * vdev)2064 static int vfio_pci_vga_init(struct vfio_pci_core_device *vdev)
2065 {
2066 	struct pci_dev *pdev = vdev->pdev;
2067 	int ret;
2068 
2069 	if (!vfio_pci_is_vga(pdev))
2070 		return 0;
2071 
2072 	ret = aperture_remove_conflicting_pci_devices(pdev, vdev->vdev.ops->name);
2073 	if (ret)
2074 		return ret;
2075 
2076 	ret = vga_client_register(pdev, vfio_pci_set_decode);
2077 	if (ret)
2078 		return ret;
2079 	vga_set_legacy_decoding(pdev, vfio_pci_set_decode(pdev, false));
2080 	return 0;
2081 }
2082 
vfio_pci_vga_uninit(struct vfio_pci_core_device * vdev)2083 static void vfio_pci_vga_uninit(struct vfio_pci_core_device *vdev)
2084 {
2085 	struct pci_dev *pdev = vdev->pdev;
2086 
2087 	if (!vfio_pci_is_vga(pdev))
2088 		return;
2089 	vga_client_unregister(pdev);
2090 	vga_set_legacy_decoding(pdev, VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
2091 					      VGA_RSRC_LEGACY_IO |
2092 					      VGA_RSRC_LEGACY_MEM);
2093 }
2094 
vfio_pci_core_init_dev(struct vfio_device * core_vdev)2095 int vfio_pci_core_init_dev(struct vfio_device *core_vdev)
2096 {
2097 	struct vfio_pci_core_device *vdev =
2098 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
2099 	int ret;
2100 
2101 	vdev->pdev = to_pci_dev(core_vdev->dev);
2102 	vdev->irq_type = VFIO_PCI_NUM_IRQS;
2103 	mutex_init(&vdev->igate);
2104 	spin_lock_init(&vdev->irqlock);
2105 	mutex_init(&vdev->ioeventfds_lock);
2106 	INIT_LIST_HEAD(&vdev->dummy_resources_list);
2107 	INIT_LIST_HEAD(&vdev->ioeventfds_list);
2108 	INIT_LIST_HEAD(&vdev->sriov_pfs_item);
2109 	ret = pcim_p2pdma_init(vdev->pdev);
2110 	if (ret && ret != -EOPNOTSUPP)
2111 		return ret;
2112 	INIT_LIST_HEAD(&vdev->dmabufs);
2113 	init_rwsem(&vdev->memory_lock);
2114 	xa_init(&vdev->ctx);
2115 
2116 	return 0;
2117 }
2118 EXPORT_SYMBOL_GPL(vfio_pci_core_init_dev);
2119 
vfio_pci_core_release_dev(struct vfio_device * core_vdev)2120 void vfio_pci_core_release_dev(struct vfio_device *core_vdev)
2121 {
2122 	struct vfio_pci_core_device *vdev =
2123 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
2124 
2125 	mutex_destroy(&vdev->igate);
2126 	mutex_destroy(&vdev->ioeventfds_lock);
2127 	kfree(vdev->region);
2128 	kfree(vdev->pm_save);
2129 }
2130 EXPORT_SYMBOL_GPL(vfio_pci_core_release_dev);
2131 
vfio_pci_core_register_device(struct vfio_pci_core_device * vdev)2132 int vfio_pci_core_register_device(struct vfio_pci_core_device *vdev)
2133 {
2134 	struct pci_dev *pdev = vdev->pdev;
2135 	struct device *dev = &pdev->dev;
2136 	int ret;
2137 
2138 	/* Drivers must set the vfio_pci_core_device to their drvdata */
2139 	if (WARN_ON(vdev != dev_get_drvdata(dev)))
2140 		return -EINVAL;
2141 
2142 	if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
2143 		return -EINVAL;
2144 
2145 	if (vdev->vdev.mig_ops) {
2146 		if (!(vdev->vdev.mig_ops->migration_get_state &&
2147 		      vdev->vdev.mig_ops->migration_set_state &&
2148 		      vdev->vdev.mig_ops->migration_get_data_size) ||
2149 		    !(vdev->vdev.migration_flags & VFIO_MIGRATION_STOP_COPY))
2150 			return -EINVAL;
2151 	}
2152 
2153 	if (vdev->vdev.log_ops && !(vdev->vdev.log_ops->log_start &&
2154 	    vdev->vdev.log_ops->log_stop &&
2155 	    vdev->vdev.log_ops->log_read_and_clear))
2156 		return -EINVAL;
2157 
2158 	/*
2159 	 * Prevent binding to PFs with VFs enabled, the VFs might be in use
2160 	 * by the host or other users.  We cannot capture the VFs if they
2161 	 * already exist, nor can we track VF users.  Disabling SR-IOV here
2162 	 * would initiate removing the VFs, which would unbind the driver,
2163 	 * which is prone to blocking if that VF is also in use by vfio-pci.
2164 	 * Just reject these PFs and let the user sort it out.
2165 	 */
2166 	if (pci_num_vf(pdev)) {
2167 		pci_warn(pdev, "Cannot bind to PF with SR-IOV enabled\n");
2168 		return -EBUSY;
2169 	}
2170 
2171 	if (pci_is_root_bus(pdev->bus) || pdev->is_virtfn) {
2172 		ret = vfio_assign_device_set(&vdev->vdev, vdev);
2173 	} else if (!pci_probe_reset_slot(pdev->slot)) {
2174 		ret = vfio_assign_device_set(&vdev->vdev, pdev->slot);
2175 	} else {
2176 		/*
2177 		 * If there is no slot reset support for this device, the whole
2178 		 * bus needs to be grouped together to support bus-wide resets.
2179 		 */
2180 		ret = vfio_assign_device_set(&vdev->vdev, pdev->bus);
2181 	}
2182 
2183 	if (ret)
2184 		return ret;
2185 	ret = vfio_pci_vf_init(vdev);
2186 	if (ret)
2187 		return ret;
2188 	ret = vfio_pci_vga_init(vdev);
2189 	if (ret)
2190 		goto out_vf;
2191 
2192 	vfio_pci_probe_power_state(vdev);
2193 
2194 	/*
2195 	 * pci-core sets the device power state to an unknown value at
2196 	 * bootup and after being removed from a driver.  The only
2197 	 * transition it allows from this unknown state is to D0, which
2198 	 * typically happens when a driver calls pci_enable_device().
2199 	 * We're not ready to enable the device yet, but we do want to
2200 	 * be able to get to D3.  Therefore first do a D0 transition
2201 	 * before enabling runtime PM.
2202 	 */
2203 	vfio_pci_set_power_state(vdev, PCI_D0);
2204 
2205 	dev->driver->pm = &vfio_pci_core_pm_ops;
2206 	pm_runtime_allow(dev);
2207 	if (!disable_idle_d3)
2208 		pm_runtime_put(dev);
2209 
2210 	ret = vfio_register_group_dev(&vdev->vdev);
2211 	if (ret)
2212 		goto out_power;
2213 	return 0;
2214 
2215 out_power:
2216 	if (!disable_idle_d3)
2217 		pm_runtime_get_noresume(dev);
2218 
2219 	pm_runtime_forbid(dev);
2220 out_vf:
2221 	vfio_pci_vf_uninit(vdev);
2222 	return ret;
2223 }
2224 EXPORT_SYMBOL_GPL(vfio_pci_core_register_device);
2225 
vfio_pci_core_unregister_device(struct vfio_pci_core_device * vdev)2226 void vfio_pci_core_unregister_device(struct vfio_pci_core_device *vdev)
2227 {
2228 	vfio_pci_core_sriov_configure(vdev, 0);
2229 
2230 	vfio_unregister_group_dev(&vdev->vdev);
2231 
2232 	vfio_pci_vf_uninit(vdev);
2233 	vfio_pci_vga_uninit(vdev);
2234 
2235 	if (!disable_idle_d3)
2236 		pm_runtime_get_noresume(&vdev->pdev->dev);
2237 
2238 	pm_runtime_forbid(&vdev->pdev->dev);
2239 }
2240 EXPORT_SYMBOL_GPL(vfio_pci_core_unregister_device);
2241 
vfio_pci_core_aer_err_detected(struct pci_dev * pdev,pci_channel_state_t state)2242 pci_ers_result_t vfio_pci_core_aer_err_detected(struct pci_dev *pdev,
2243 						pci_channel_state_t state)
2244 {
2245 	struct vfio_pci_core_device *vdev = dev_get_drvdata(&pdev->dev);
2246 	struct vfio_pci_eventfd *eventfd;
2247 
2248 	rcu_read_lock();
2249 	eventfd = rcu_dereference(vdev->err_trigger);
2250 	if (eventfd)
2251 		eventfd_signal(eventfd->ctx);
2252 	rcu_read_unlock();
2253 
2254 	return PCI_ERS_RESULT_CAN_RECOVER;
2255 }
2256 EXPORT_SYMBOL_GPL(vfio_pci_core_aer_err_detected);
2257 
vfio_pci_core_sriov_configure(struct vfio_pci_core_device * vdev,int nr_virtfn)2258 int vfio_pci_core_sriov_configure(struct vfio_pci_core_device *vdev,
2259 				  int nr_virtfn)
2260 {
2261 	struct pci_dev *pdev = vdev->pdev;
2262 	int ret = 0;
2263 
2264 	device_lock_assert(&pdev->dev);
2265 
2266 	if (nr_virtfn) {
2267 		mutex_lock(&vfio_pci_sriov_pfs_mutex);
2268 		/*
2269 		 * The thread that adds the vdev to the list is the only thread
2270 		 * that gets to call pci_enable_sriov() and we will only allow
2271 		 * it to be called once without going through
2272 		 * pci_disable_sriov()
2273 		 */
2274 		if (!list_empty(&vdev->sriov_pfs_item)) {
2275 			ret = -EINVAL;
2276 			goto out_unlock;
2277 		}
2278 		list_add_tail(&vdev->sriov_pfs_item, &vfio_pci_sriov_pfs);
2279 		mutex_unlock(&vfio_pci_sriov_pfs_mutex);
2280 
2281 		/*
2282 		 * The PF power state should always be higher than the VF power
2283 		 * state. The PF can be in low power state either with runtime
2284 		 * power management (when there is no user) or PCI_PM_CTRL
2285 		 * register write by the user. If PF is in the low power state,
2286 		 * then change the power state to D0 first before enabling
2287 		 * SR-IOV. Also, this function can be called at any time, and
2288 		 * userspace PCI_PM_CTRL write can race against this code path,
2289 		 * so protect the same with 'memory_lock'.
2290 		 */
2291 		ret = pm_runtime_resume_and_get(&pdev->dev);
2292 		if (ret)
2293 			goto out_del;
2294 
2295 		down_write(&vdev->memory_lock);
2296 		vfio_pci_set_power_state(vdev, PCI_D0);
2297 		ret = pci_enable_sriov(pdev, nr_virtfn);
2298 		up_write(&vdev->memory_lock);
2299 		if (ret) {
2300 			pm_runtime_put(&pdev->dev);
2301 			goto out_del;
2302 		}
2303 		return nr_virtfn;
2304 	}
2305 
2306 	if (pci_num_vf(pdev)) {
2307 		pci_disable_sriov(pdev);
2308 		pm_runtime_put(&pdev->dev);
2309 	}
2310 
2311 out_del:
2312 	mutex_lock(&vfio_pci_sriov_pfs_mutex);
2313 	list_del_init(&vdev->sriov_pfs_item);
2314 out_unlock:
2315 	mutex_unlock(&vfio_pci_sriov_pfs_mutex);
2316 	return ret;
2317 }
2318 EXPORT_SYMBOL_GPL(vfio_pci_core_sriov_configure);
2319 
2320 const struct pci_error_handlers vfio_pci_core_err_handlers = {
2321 	.error_detected = vfio_pci_core_aer_err_detected,
2322 };
2323 EXPORT_SYMBOL_GPL(vfio_pci_core_err_handlers);
2324 
vfio_dev_in_groups(struct vfio_device * vdev,struct vfio_pci_group_info * groups)2325 static bool vfio_dev_in_groups(struct vfio_device *vdev,
2326 			       struct vfio_pci_group_info *groups)
2327 {
2328 	unsigned int i;
2329 
2330 	if (!groups)
2331 		return false;
2332 
2333 	for (i = 0; i < groups->count; i++)
2334 		if (vfio_file_has_dev(groups->files[i], vdev))
2335 			return true;
2336 	return false;
2337 }
2338 
vfio_pci_is_device_in_set(struct pci_dev * pdev,void * data)2339 static int vfio_pci_is_device_in_set(struct pci_dev *pdev, void *data)
2340 {
2341 	struct vfio_device_set *dev_set = data;
2342 
2343 	return vfio_find_device_in_devset(dev_set, &pdev->dev) ? 0 : -ENODEV;
2344 }
2345 
2346 /*
2347  * vfio-core considers a group to be viable and will create a vfio_device even
2348  * if some devices are bound to drivers like pci-stub or pcieport. Here we
2349  * require all PCI devices to be inside our dev_set since that ensures they stay
2350  * put and that every driver controlling the device can co-ordinate with the
2351  * device reset.
2352  *
2353  * Returns the pci_dev to pass to pci_reset_bus() if every PCI device to be
2354  * reset is inside the dev_set, and pci_reset_bus() can succeed. NULL otherwise.
2355  */
2356 static struct pci_dev *
vfio_pci_dev_set_resettable(struct vfio_device_set * dev_set)2357 vfio_pci_dev_set_resettable(struct vfio_device_set *dev_set)
2358 {
2359 	struct pci_dev *pdev;
2360 
2361 	lockdep_assert_held(&dev_set->lock);
2362 
2363 	/*
2364 	 * By definition all PCI devices in the dev_set share the same PCI
2365 	 * reset, so any pci_dev will have the same outcomes for
2366 	 * pci_probe_reset_*() and pci_reset_bus().
2367 	 */
2368 	pdev = list_first_entry(&dev_set->device_list,
2369 				struct vfio_pci_core_device,
2370 				vdev.dev_set_list)->pdev;
2371 
2372 	/* pci_reset_bus() is supported */
2373 	if (pci_probe_reset_slot(pdev->slot) && pci_probe_reset_bus(pdev->bus))
2374 		return NULL;
2375 
2376 	if (vfio_pci_for_each_slot_or_bus(pdev, vfio_pci_is_device_in_set,
2377 					  dev_set,
2378 					  !pci_probe_reset_slot(pdev->slot)))
2379 		return NULL;
2380 	return pdev;
2381 }
2382 
vfio_pci_dev_set_pm_runtime_get(struct vfio_device_set * dev_set)2383 static int vfio_pci_dev_set_pm_runtime_get(struct vfio_device_set *dev_set)
2384 {
2385 	struct vfio_pci_core_device *cur;
2386 	int ret;
2387 
2388 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2389 		ret = pm_runtime_resume_and_get(&cur->pdev->dev);
2390 		if (ret)
2391 			goto unwind;
2392 	}
2393 
2394 	return 0;
2395 
2396 unwind:
2397 	list_for_each_entry_continue_reverse(cur, &dev_set->device_list,
2398 					     vdev.dev_set_list)
2399 		pm_runtime_put(&cur->pdev->dev);
2400 
2401 	return ret;
2402 }
2403 
vfio_pci_dev_set_hot_reset(struct vfio_device_set * dev_set,struct vfio_pci_group_info * groups,struct iommufd_ctx * iommufd_ctx)2404 static int vfio_pci_dev_set_hot_reset(struct vfio_device_set *dev_set,
2405 				      struct vfio_pci_group_info *groups,
2406 				      struct iommufd_ctx *iommufd_ctx)
2407 {
2408 	struct vfio_pci_core_device *vdev;
2409 	struct pci_dev *pdev;
2410 	int ret;
2411 
2412 	mutex_lock(&dev_set->lock);
2413 
2414 	pdev = vfio_pci_dev_set_resettable(dev_set);
2415 	if (!pdev) {
2416 		ret = -EINVAL;
2417 		goto err_unlock;
2418 	}
2419 
2420 	/*
2421 	 * Some of the devices in the dev_set can be in the runtime suspended
2422 	 * state. Increment the usage count for all the devices in the dev_set
2423 	 * before reset and decrement the same after reset.
2424 	 */
2425 	ret = vfio_pci_dev_set_pm_runtime_get(dev_set);
2426 	if (ret)
2427 		goto err_unlock;
2428 
2429 	list_for_each_entry(vdev, &dev_set->device_list, vdev.dev_set_list) {
2430 		bool owned;
2431 
2432 		/*
2433 		 * Test whether all the affected devices can be reset by the
2434 		 * user.
2435 		 *
2436 		 * If called from a group opened device and the user provides
2437 		 * a set of groups, all the devices in the dev_set should be
2438 		 * contained by the set of groups provided by the user.
2439 		 *
2440 		 * If called from a cdev opened device and the user provides
2441 		 * a zero-length array, all the devices in the dev_set must
2442 		 * be bound to the same iommufd_ctx as the input iommufd_ctx.
2443 		 * If there is any device that has not been bound to any
2444 		 * iommufd_ctx yet, check if its iommu_group has any device
2445 		 * bound to the input iommufd_ctx.  Such devices can be
2446 		 * considered owned by the input iommufd_ctx as the device
2447 		 * cannot be owned by another iommufd_ctx when its iommu_group
2448 		 * is owned.
2449 		 *
2450 		 * Otherwise, reset is not allowed.
2451 		 */
2452 		if (iommufd_ctx) {
2453 			int devid = vfio_iommufd_get_dev_id(&vdev->vdev,
2454 							    iommufd_ctx);
2455 
2456 			owned = (devid > 0 || devid == -ENOENT);
2457 		} else {
2458 			owned = vfio_dev_in_groups(&vdev->vdev, groups);
2459 		}
2460 
2461 		if (!owned) {
2462 			ret = -EINVAL;
2463 			break;
2464 		}
2465 
2466 		/*
2467 		 * Take the memory write lock for each device and zap BAR
2468 		 * mappings to prevent the user accessing the device while in
2469 		 * reset.  Locking multiple devices is prone to deadlock,
2470 		 * runaway and unwind if we hit contention.
2471 		 */
2472 		if (!down_write_trylock(&vdev->memory_lock)) {
2473 			ret = -EBUSY;
2474 			break;
2475 		}
2476 
2477 		vfio_pci_dma_buf_move(vdev, true);
2478 		vfio_pci_zap_bars(vdev);
2479 	}
2480 
2481 	if (!list_entry_is_head(vdev,
2482 				&dev_set->device_list, vdev.dev_set_list)) {
2483 		vdev = list_prev_entry(vdev, vdev.dev_set_list);
2484 		goto err_undo;
2485 	}
2486 
2487 	/*
2488 	 * The pci_reset_bus() will reset all the devices in the bus.
2489 	 * The power state can be non-D0 for some of the devices in the bus.
2490 	 * For these devices, the pci_reset_bus() will internally set
2491 	 * the power state to D0 without vfio driver involvement.
2492 	 * For the devices which have NoSoftRst-, the reset function can
2493 	 * cause the PCI config space reset without restoring the original
2494 	 * state (saved locally in 'vdev->pm_save').
2495 	 */
2496 	list_for_each_entry(vdev, &dev_set->device_list, vdev.dev_set_list)
2497 		vfio_pci_set_power_state(vdev, PCI_D0);
2498 
2499 	ret = pci_reset_bus(pdev);
2500 
2501 	vdev = list_last_entry(&dev_set->device_list,
2502 			       struct vfio_pci_core_device, vdev.dev_set_list);
2503 
2504 err_undo:
2505 	list_for_each_entry_from_reverse(vdev, &dev_set->device_list,
2506 					 vdev.dev_set_list) {
2507 		if (vdev->vdev.open_count && __vfio_pci_memory_enabled(vdev))
2508 			vfio_pci_dma_buf_move(vdev, false);
2509 		up_write(&vdev->memory_lock);
2510 	}
2511 
2512 	list_for_each_entry(vdev, &dev_set->device_list, vdev.dev_set_list)
2513 		pm_runtime_put(&vdev->pdev->dev);
2514 
2515 err_unlock:
2516 	mutex_unlock(&dev_set->lock);
2517 	return ret;
2518 }
2519 
vfio_pci_dev_set_needs_reset(struct vfio_device_set * dev_set)2520 static bool vfio_pci_dev_set_needs_reset(struct vfio_device_set *dev_set)
2521 {
2522 	struct vfio_pci_core_device *cur;
2523 	bool needs_reset = false;
2524 
2525 	/* No other VFIO device in the set can be open. */
2526 	if (vfio_device_set_open_count(dev_set) > 1)
2527 		return false;
2528 
2529 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list)
2530 		needs_reset |= cur->needs_reset;
2531 	return needs_reset;
2532 }
2533 
2534 /*
2535  * If a bus or slot reset is available for the provided dev_set and:
2536  *  - All of the devices affected by that bus or slot reset are unused
2537  *  - At least one of the affected devices is marked dirty via
2538  *    needs_reset (such as by lack of FLR support)
2539  * Then attempt to perform that bus or slot reset.
2540  */
vfio_pci_dev_set_try_reset(struct vfio_device_set * dev_set)2541 static void vfio_pci_dev_set_try_reset(struct vfio_device_set *dev_set)
2542 {
2543 	struct vfio_pci_core_device *cur;
2544 	struct pci_dev *pdev;
2545 	bool reset_done = false;
2546 
2547 	if (!vfio_pci_dev_set_needs_reset(dev_set))
2548 		return;
2549 
2550 	pdev = vfio_pci_dev_set_resettable(dev_set);
2551 	if (!pdev)
2552 		return;
2553 
2554 	/*
2555 	 * Some of the devices in the bus can be in the runtime suspended
2556 	 * state. Increment the usage count for all the devices in the dev_set
2557 	 * before reset and decrement the same after reset.
2558 	 */
2559 	if (!disable_idle_d3 && vfio_pci_dev_set_pm_runtime_get(dev_set))
2560 		return;
2561 
2562 	if (!pci_reset_bus(pdev))
2563 		reset_done = true;
2564 
2565 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2566 		if (reset_done)
2567 			cur->needs_reset = false;
2568 
2569 		if (!disable_idle_d3)
2570 			pm_runtime_put(&cur->pdev->dev);
2571 	}
2572 }
2573 
vfio_pci_core_set_params(bool is_nointxmask,bool is_disable_vga,bool is_disable_idle_d3)2574 void vfio_pci_core_set_params(bool is_nointxmask, bool is_disable_vga,
2575 			      bool is_disable_idle_d3)
2576 {
2577 	nointxmask = is_nointxmask;
2578 	disable_vga = is_disable_vga;
2579 	disable_idle_d3 = is_disable_idle_d3;
2580 }
2581 EXPORT_SYMBOL_GPL(vfio_pci_core_set_params);
2582 
vfio_pci_core_cleanup(void)2583 static void vfio_pci_core_cleanup(void)
2584 {
2585 	vfio_pci_uninit_perm_bits();
2586 }
2587 
vfio_pci_core_init(void)2588 static int __init vfio_pci_core_init(void)
2589 {
2590 	/* Allocate shared config space permission data used by all devices */
2591 	return vfio_pci_init_perm_bits();
2592 }
2593 
2594 module_init(vfio_pci_core_init);
2595 module_exit(vfio_pci_core_cleanup);
2596 
2597 MODULE_LICENSE("GPL v2");
2598 MODULE_AUTHOR(DRIVER_AUTHOR);
2599 MODULE_DESCRIPTION(DRIVER_DESC);
2600