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