xref: /openbmc/linux/drivers/vfio/pci/vfio_pci_core.c (revision 8dd3cdea)
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/device.h>
14 #include <linux/eventfd.h>
15 #include <linux/file.h>
16 #include <linux/interrupt.h>
17 #include <linux/iommu.h>
18 #include <linux/module.h>
19 #include <linux/mutex.h>
20 #include <linux/notifier.h>
21 #include <linux/pci.h>
22 #include <linux/pm_runtime.h>
23 #include <linux/slab.h>
24 #include <linux/types.h>
25 #include <linux/uaccess.h>
26 #include <linux/vgaarb.h>
27 #include <linux/nospec.h>
28 #include <linux/sched/mm.h>
29 
30 #include <linux/vfio_pci_core.h>
31 
32 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
33 #define DRIVER_DESC "core driver for VFIO based PCI devices"
34 
35 static bool nointxmask;
36 static bool disable_vga;
37 static bool disable_idle_d3;
38 
39 static inline bool vfio_vga_disabled(void)
40 {
41 #ifdef CONFIG_VFIO_PCI_VGA
42 	return disable_vga;
43 #else
44 	return true;
45 #endif
46 }
47 
48 /*
49  * Our VGA arbiter participation is limited since we don't know anything
50  * about the device itself.  However, if the device is the only VGA device
51  * downstream of a bridge and VFIO VGA support is disabled, then we can
52  * safely return legacy VGA IO and memory as not decoded since the user
53  * has no way to get to it and routing can be disabled externally at the
54  * bridge.
55  */
56 static unsigned int vfio_pci_set_decode(struct pci_dev *pdev, bool single_vga)
57 {
58 	struct pci_dev *tmp = NULL;
59 	unsigned char max_busnr;
60 	unsigned int decodes;
61 
62 	if (single_vga || !vfio_vga_disabled() || pci_is_root_bus(pdev->bus))
63 		return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
64 		       VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
65 
66 	max_busnr = pci_bus_max_busnr(pdev->bus);
67 	decodes = VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
68 
69 	while ((tmp = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, tmp)) != NULL) {
70 		if (tmp == pdev ||
71 		    pci_domain_nr(tmp->bus) != pci_domain_nr(pdev->bus) ||
72 		    pci_is_root_bus(tmp->bus))
73 			continue;
74 
75 		if (tmp->bus->number >= pdev->bus->number &&
76 		    tmp->bus->number <= max_busnr) {
77 			pci_dev_put(tmp);
78 			decodes |= VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
79 			break;
80 		}
81 	}
82 
83 	return decodes;
84 }
85 
86 static void vfio_pci_probe_mmaps(struct vfio_pci_core_device *vdev)
87 {
88 	struct resource *res;
89 	int i;
90 	struct vfio_pci_dummy_resource *dummy_res;
91 
92 	for (i = 0; i < PCI_STD_NUM_BARS; i++) {
93 		int bar = i + PCI_STD_RESOURCES;
94 
95 		res = &vdev->pdev->resource[bar];
96 
97 		if (!IS_ENABLED(CONFIG_VFIO_PCI_MMAP))
98 			goto no_mmap;
99 
100 		if (!(res->flags & IORESOURCE_MEM))
101 			goto no_mmap;
102 
103 		/*
104 		 * The PCI core shouldn't set up a resource with a
105 		 * type but zero size. But there may be bugs that
106 		 * cause us to do that.
107 		 */
108 		if (!resource_size(res))
109 			goto no_mmap;
110 
111 		if (resource_size(res) >= PAGE_SIZE) {
112 			vdev->bar_mmap_supported[bar] = true;
113 			continue;
114 		}
115 
116 		if (!(res->start & ~PAGE_MASK)) {
117 			/*
118 			 * Add a dummy resource to reserve the remainder
119 			 * of the exclusive page in case that hot-add
120 			 * device's bar is assigned into it.
121 			 */
122 			dummy_res = kzalloc(sizeof(*dummy_res), GFP_KERNEL);
123 			if (dummy_res == NULL)
124 				goto no_mmap;
125 
126 			dummy_res->resource.name = "vfio sub-page reserved";
127 			dummy_res->resource.start = res->end + 1;
128 			dummy_res->resource.end = res->start + PAGE_SIZE - 1;
129 			dummy_res->resource.flags = res->flags;
130 			if (request_resource(res->parent,
131 						&dummy_res->resource)) {
132 				kfree(dummy_res);
133 				goto no_mmap;
134 			}
135 			dummy_res->index = bar;
136 			list_add(&dummy_res->res_next,
137 					&vdev->dummy_resources_list);
138 			vdev->bar_mmap_supported[bar] = true;
139 			continue;
140 		}
141 		/*
142 		 * Here we don't handle the case when the BAR is not page
143 		 * aligned because we can't expect the BAR will be
144 		 * assigned into the same location in a page in guest
145 		 * when we passthrough the BAR. And it's hard to access
146 		 * this BAR in userspace because we have no way to get
147 		 * the BAR's location in a page.
148 		 */
149 no_mmap:
150 		vdev->bar_mmap_supported[bar] = false;
151 	}
152 }
153 
154 struct vfio_pci_group_info;
155 static bool vfio_pci_dev_set_try_reset(struct vfio_device_set *dev_set);
156 static int vfio_pci_dev_set_hot_reset(struct vfio_device_set *dev_set,
157 				      struct vfio_pci_group_info *groups);
158 
159 /*
160  * INTx masking requires the ability to disable INTx signaling via PCI_COMMAND
161  * _and_ the ability detect when the device is asserting INTx via PCI_STATUS.
162  * If a device implements the former but not the latter we would typically
163  * expect broken_intx_masking be set and require an exclusive interrupt.
164  * However since we do have control of the device's ability to assert INTx,
165  * we can instead pretend that the device does not implement INTx, virtualizing
166  * the pin register to report zero and maintaining DisINTx set on the host.
167  */
168 static bool vfio_pci_nointx(struct pci_dev *pdev)
169 {
170 	switch (pdev->vendor) {
171 	case PCI_VENDOR_ID_INTEL:
172 		switch (pdev->device) {
173 		/* All i40e (XL710/X710/XXV710) 10/20/25/40GbE NICs */
174 		case 0x1572:
175 		case 0x1574:
176 		case 0x1580 ... 0x1581:
177 		case 0x1583 ... 0x158b:
178 		case 0x37d0 ... 0x37d2:
179 		/* X550 */
180 		case 0x1563:
181 			return true;
182 		default:
183 			return false;
184 		}
185 	}
186 
187 	return false;
188 }
189 
190 static void vfio_pci_probe_power_state(struct vfio_pci_core_device *vdev)
191 {
192 	struct pci_dev *pdev = vdev->pdev;
193 	u16 pmcsr;
194 
195 	if (!pdev->pm_cap)
196 		return;
197 
198 	pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmcsr);
199 
200 	vdev->needs_pm_restore = !(pmcsr & PCI_PM_CTRL_NO_SOFT_RESET);
201 }
202 
203 /*
204  * pci_set_power_state() wrapper handling devices which perform a soft reset on
205  * D3->D0 transition.  Save state prior to D0/1/2->D3, stash it on the vdev,
206  * restore when returned to D0.  Saved separately from pci_saved_state for use
207  * by PM capability emulation and separately from pci_dev internal saved state
208  * to avoid it being overwritten and consumed around other resets.
209  */
210 int vfio_pci_set_power_state(struct vfio_pci_core_device *vdev, pci_power_t state)
211 {
212 	struct pci_dev *pdev = vdev->pdev;
213 	bool needs_restore = false, needs_save = false;
214 	int ret;
215 
216 	if (vdev->needs_pm_restore) {
217 		if (pdev->current_state < PCI_D3hot && state >= PCI_D3hot) {
218 			pci_save_state(pdev);
219 			needs_save = true;
220 		}
221 
222 		if (pdev->current_state >= PCI_D3hot && state <= PCI_D0)
223 			needs_restore = true;
224 	}
225 
226 	ret = pci_set_power_state(pdev, state);
227 
228 	if (!ret) {
229 		/* D3 might be unsupported via quirk, skip unless in D3 */
230 		if (needs_save && pdev->current_state >= PCI_D3hot) {
231 			/*
232 			 * The current PCI state will be saved locally in
233 			 * 'pm_save' during the D3hot transition. When the
234 			 * device state is changed to D0 again with the current
235 			 * function, then pci_store_saved_state() will restore
236 			 * the state and will free the memory pointed by
237 			 * 'pm_save'. There are few cases where the PCI power
238 			 * state can be changed to D0 without the involvement
239 			 * of the driver. For these cases, free the earlier
240 			 * allocated memory first before overwriting 'pm_save'
241 			 * to prevent the memory leak.
242 			 */
243 			kfree(vdev->pm_save);
244 			vdev->pm_save = pci_store_saved_state(pdev);
245 		} else if (needs_restore) {
246 			pci_load_and_free_saved_state(pdev, &vdev->pm_save);
247 			pci_restore_state(pdev);
248 		}
249 	}
250 
251 	return ret;
252 }
253 
254 int vfio_pci_core_enable(struct vfio_pci_core_device *vdev)
255 {
256 	struct pci_dev *pdev = vdev->pdev;
257 	int ret;
258 	u16 cmd;
259 	u8 msix_pos;
260 
261 	vfio_pci_set_power_state(vdev, PCI_D0);
262 
263 	/* Don't allow our initial saved state to include busmaster */
264 	pci_clear_master(pdev);
265 
266 	ret = pci_enable_device(pdev);
267 	if (ret)
268 		return ret;
269 
270 	/* If reset fails because of the device lock, fail this path entirely */
271 	ret = pci_try_reset_function(pdev);
272 	if (ret == -EAGAIN) {
273 		pci_disable_device(pdev);
274 		return ret;
275 	}
276 
277 	vdev->reset_works = !ret;
278 	pci_save_state(pdev);
279 	vdev->pci_saved_state = pci_store_saved_state(pdev);
280 	if (!vdev->pci_saved_state)
281 		pci_dbg(pdev, "%s: Couldn't store saved state\n", __func__);
282 
283 	if (likely(!nointxmask)) {
284 		if (vfio_pci_nointx(pdev)) {
285 			pci_info(pdev, "Masking broken INTx support\n");
286 			vdev->nointx = true;
287 			pci_intx(pdev, 0);
288 		} else
289 			vdev->pci_2_3 = pci_intx_mask_supported(pdev);
290 	}
291 
292 	pci_read_config_word(pdev, PCI_COMMAND, &cmd);
293 	if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
294 		cmd &= ~PCI_COMMAND_INTX_DISABLE;
295 		pci_write_config_word(pdev, PCI_COMMAND, cmd);
296 	}
297 
298 	ret = vfio_config_init(vdev);
299 	if (ret) {
300 		kfree(vdev->pci_saved_state);
301 		vdev->pci_saved_state = NULL;
302 		pci_disable_device(pdev);
303 		return ret;
304 	}
305 
306 	msix_pos = pdev->msix_cap;
307 	if (msix_pos) {
308 		u16 flags;
309 		u32 table;
310 
311 		pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
312 		pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
313 
314 		vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
315 		vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
316 		vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
317 	} else
318 		vdev->msix_bar = 0xFF;
319 
320 	if (!vfio_vga_disabled() && vfio_pci_is_vga(pdev))
321 		vdev->has_vga = true;
322 
323 
324 	return 0;
325 }
326 EXPORT_SYMBOL_GPL(vfio_pci_core_enable);
327 
328 void vfio_pci_core_disable(struct vfio_pci_core_device *vdev)
329 {
330 	struct pci_dev *pdev = vdev->pdev;
331 	struct vfio_pci_dummy_resource *dummy_res, *tmp;
332 	struct vfio_pci_ioeventfd *ioeventfd, *ioeventfd_tmp;
333 	int i, bar;
334 
335 	/* For needs_reset */
336 	lockdep_assert_held(&vdev->vdev.dev_set->lock);
337 
338 	/*
339 	 * This function can be invoked while the power state is non-D0.
340 	 * This function calls __pci_reset_function_locked() which internally
341 	 * can use pci_pm_reset() for the function reset. pci_pm_reset() will
342 	 * fail if the power state is non-D0. Also, for the devices which
343 	 * have NoSoftRst-, the reset function can cause the PCI config space
344 	 * reset without restoring the original state (saved locally in
345 	 * 'vdev->pm_save').
346 	 */
347 	vfio_pci_set_power_state(vdev, PCI_D0);
348 
349 	/* Stop the device from further DMA */
350 	pci_clear_master(pdev);
351 
352 	vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
353 				VFIO_IRQ_SET_ACTION_TRIGGER,
354 				vdev->irq_type, 0, 0, NULL);
355 
356 	/* Device closed, don't need mutex here */
357 	list_for_each_entry_safe(ioeventfd, ioeventfd_tmp,
358 				 &vdev->ioeventfds_list, next) {
359 		vfio_virqfd_disable(&ioeventfd->virqfd);
360 		list_del(&ioeventfd->next);
361 		kfree(ioeventfd);
362 	}
363 	vdev->ioeventfds_nr = 0;
364 
365 	vdev->virq_disabled = false;
366 
367 	for (i = 0; i < vdev->num_regions; i++)
368 		vdev->region[i].ops->release(vdev, &vdev->region[i]);
369 
370 	vdev->num_regions = 0;
371 	kfree(vdev->region);
372 	vdev->region = NULL; /* don't krealloc a freed pointer */
373 
374 	vfio_config_free(vdev);
375 
376 	for (i = 0; i < PCI_STD_NUM_BARS; i++) {
377 		bar = i + PCI_STD_RESOURCES;
378 		if (!vdev->barmap[bar])
379 			continue;
380 		pci_iounmap(pdev, vdev->barmap[bar]);
381 		pci_release_selected_regions(pdev, 1 << bar);
382 		vdev->barmap[bar] = NULL;
383 	}
384 
385 	list_for_each_entry_safe(dummy_res, tmp,
386 				 &vdev->dummy_resources_list, res_next) {
387 		list_del(&dummy_res->res_next);
388 		release_resource(&dummy_res->resource);
389 		kfree(dummy_res);
390 	}
391 
392 	vdev->needs_reset = true;
393 
394 	/*
395 	 * If we have saved state, restore it.  If we can reset the device,
396 	 * even better.  Resetting with current state seems better than
397 	 * nothing, but saving and restoring current state without reset
398 	 * is just busy work.
399 	 */
400 	if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
401 		pci_info(pdev, "%s: Couldn't reload saved state\n", __func__);
402 
403 		if (!vdev->reset_works)
404 			goto out;
405 
406 		pci_save_state(pdev);
407 	}
408 
409 	/*
410 	 * Disable INTx and MSI, presumably to avoid spurious interrupts
411 	 * during reset.  Stolen from pci_reset_function()
412 	 */
413 	pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
414 
415 	/*
416 	 * Try to get the locks ourselves to prevent a deadlock. The
417 	 * success of this is dependent on being able to lock the device,
418 	 * which is not always possible.
419 	 * We can not use the "try" reset interface here, which will
420 	 * overwrite the previously restored configuration information.
421 	 */
422 	if (vdev->reset_works && pci_dev_trylock(pdev)) {
423 		if (!__pci_reset_function_locked(pdev))
424 			vdev->needs_reset = false;
425 		pci_dev_unlock(pdev);
426 	}
427 
428 	pci_restore_state(pdev);
429 out:
430 	pci_disable_device(pdev);
431 
432 	if (!vfio_pci_dev_set_try_reset(vdev->vdev.dev_set) && !disable_idle_d3)
433 		vfio_pci_set_power_state(vdev, PCI_D3hot);
434 }
435 EXPORT_SYMBOL_GPL(vfio_pci_core_disable);
436 
437 static struct vfio_pci_core_device *get_pf_vdev(struct vfio_pci_core_device *vdev)
438 {
439 	struct pci_dev *physfn = pci_physfn(vdev->pdev);
440 	struct vfio_device *pf_dev;
441 
442 	if (!vdev->pdev->is_virtfn)
443 		return NULL;
444 
445 	pf_dev = vfio_device_get_from_dev(&physfn->dev);
446 	if (!pf_dev)
447 		return NULL;
448 
449 	if (pci_dev_driver(physfn) != pci_dev_driver(vdev->pdev)) {
450 		vfio_device_put(pf_dev);
451 		return NULL;
452 	}
453 
454 	return container_of(pf_dev, struct vfio_pci_core_device, vdev);
455 }
456 
457 static void vfio_pci_vf_token_user_add(struct vfio_pci_core_device *vdev, int val)
458 {
459 	struct vfio_pci_core_device *pf_vdev = get_pf_vdev(vdev);
460 
461 	if (!pf_vdev)
462 		return;
463 
464 	mutex_lock(&pf_vdev->vf_token->lock);
465 	pf_vdev->vf_token->users += val;
466 	WARN_ON(pf_vdev->vf_token->users < 0);
467 	mutex_unlock(&pf_vdev->vf_token->lock);
468 
469 	vfio_device_put(&pf_vdev->vdev);
470 }
471 
472 void vfio_pci_core_close_device(struct vfio_device *core_vdev)
473 {
474 	struct vfio_pci_core_device *vdev =
475 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
476 
477 	vfio_pci_vf_token_user_add(vdev, -1);
478 	vfio_spapr_pci_eeh_release(vdev->pdev);
479 	vfio_pci_core_disable(vdev);
480 
481 	mutex_lock(&vdev->igate);
482 	if (vdev->err_trigger) {
483 		eventfd_ctx_put(vdev->err_trigger);
484 		vdev->err_trigger = NULL;
485 	}
486 	if (vdev->req_trigger) {
487 		eventfd_ctx_put(vdev->req_trigger);
488 		vdev->req_trigger = NULL;
489 	}
490 	mutex_unlock(&vdev->igate);
491 }
492 EXPORT_SYMBOL_GPL(vfio_pci_core_close_device);
493 
494 void vfio_pci_core_finish_enable(struct vfio_pci_core_device *vdev)
495 {
496 	vfio_pci_probe_mmaps(vdev);
497 	vfio_spapr_pci_eeh_open(vdev->pdev);
498 	vfio_pci_vf_token_user_add(vdev, 1);
499 }
500 EXPORT_SYMBOL_GPL(vfio_pci_core_finish_enable);
501 
502 static int vfio_pci_get_irq_count(struct vfio_pci_core_device *vdev, int irq_type)
503 {
504 	if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
505 		u8 pin;
506 
507 		if (!IS_ENABLED(CONFIG_VFIO_PCI_INTX) ||
508 		    vdev->nointx || vdev->pdev->is_virtfn)
509 			return 0;
510 
511 		pci_read_config_byte(vdev->pdev, PCI_INTERRUPT_PIN, &pin);
512 
513 		return pin ? 1 : 0;
514 	} else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
515 		u8 pos;
516 		u16 flags;
517 
518 		pos = vdev->pdev->msi_cap;
519 		if (pos) {
520 			pci_read_config_word(vdev->pdev,
521 					     pos + PCI_MSI_FLAGS, &flags);
522 			return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
523 		}
524 	} else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
525 		u8 pos;
526 		u16 flags;
527 
528 		pos = vdev->pdev->msix_cap;
529 		if (pos) {
530 			pci_read_config_word(vdev->pdev,
531 					     pos + PCI_MSIX_FLAGS, &flags);
532 
533 			return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
534 		}
535 	} else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX) {
536 		if (pci_is_pcie(vdev->pdev))
537 			return 1;
538 	} else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
539 		return 1;
540 	}
541 
542 	return 0;
543 }
544 
545 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
546 {
547 	(*(int *)data)++;
548 	return 0;
549 }
550 
551 struct vfio_pci_fill_info {
552 	int max;
553 	int cur;
554 	struct vfio_pci_dependent_device *devices;
555 };
556 
557 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
558 {
559 	struct vfio_pci_fill_info *fill = data;
560 	struct iommu_group *iommu_group;
561 
562 	if (fill->cur == fill->max)
563 		return -EAGAIN; /* Something changed, try again */
564 
565 	iommu_group = iommu_group_get(&pdev->dev);
566 	if (!iommu_group)
567 		return -EPERM; /* Cannot reset non-isolated devices */
568 
569 	fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
570 	fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
571 	fill->devices[fill->cur].bus = pdev->bus->number;
572 	fill->devices[fill->cur].devfn = pdev->devfn;
573 	fill->cur++;
574 	iommu_group_put(iommu_group);
575 	return 0;
576 }
577 
578 struct vfio_pci_group_info {
579 	int count;
580 	struct vfio_group **groups;
581 };
582 
583 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
584 {
585 	for (; pdev; pdev = pdev->bus->self)
586 		if (pdev->bus == slot->bus)
587 			return (pdev->slot == slot);
588 	return false;
589 }
590 
591 struct vfio_pci_walk_info {
592 	int (*fn)(struct pci_dev *pdev, void *data);
593 	void *data;
594 	struct pci_dev *pdev;
595 	bool slot;
596 	int ret;
597 };
598 
599 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
600 {
601 	struct vfio_pci_walk_info *walk = data;
602 
603 	if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
604 		walk->ret = walk->fn(pdev, walk->data);
605 
606 	return walk->ret;
607 }
608 
609 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
610 					 int (*fn)(struct pci_dev *,
611 						   void *data), void *data,
612 					 bool slot)
613 {
614 	struct vfio_pci_walk_info walk = {
615 		.fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
616 	};
617 
618 	pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
619 
620 	return walk.ret;
621 }
622 
623 static int msix_mmappable_cap(struct vfio_pci_core_device *vdev,
624 			      struct vfio_info_cap *caps)
625 {
626 	struct vfio_info_cap_header header = {
627 		.id = VFIO_REGION_INFO_CAP_MSIX_MAPPABLE,
628 		.version = 1
629 	};
630 
631 	return vfio_info_add_capability(caps, &header, sizeof(header));
632 }
633 
634 int vfio_pci_register_dev_region(struct vfio_pci_core_device *vdev,
635 				 unsigned int type, unsigned int subtype,
636 				 const struct vfio_pci_regops *ops,
637 				 size_t size, u32 flags, void *data)
638 {
639 	struct vfio_pci_region *region;
640 
641 	region = krealloc(vdev->region,
642 			  (vdev->num_regions + 1) * sizeof(*region),
643 			  GFP_KERNEL);
644 	if (!region)
645 		return -ENOMEM;
646 
647 	vdev->region = region;
648 	vdev->region[vdev->num_regions].type = type;
649 	vdev->region[vdev->num_regions].subtype = subtype;
650 	vdev->region[vdev->num_regions].ops = ops;
651 	vdev->region[vdev->num_regions].size = size;
652 	vdev->region[vdev->num_regions].flags = flags;
653 	vdev->region[vdev->num_regions].data = data;
654 
655 	vdev->num_regions++;
656 
657 	return 0;
658 }
659 EXPORT_SYMBOL_GPL(vfio_pci_register_dev_region);
660 
661 long vfio_pci_core_ioctl(struct vfio_device *core_vdev, unsigned int cmd,
662 		unsigned long arg)
663 {
664 	struct vfio_pci_core_device *vdev =
665 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
666 	unsigned long minsz;
667 
668 	if (cmd == VFIO_DEVICE_GET_INFO) {
669 		struct vfio_device_info info;
670 		struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
671 		unsigned long capsz;
672 		int ret;
673 
674 		minsz = offsetofend(struct vfio_device_info, num_irqs);
675 
676 		/* For backward compatibility, cannot require this */
677 		capsz = offsetofend(struct vfio_iommu_type1_info, cap_offset);
678 
679 		if (copy_from_user(&info, (void __user *)arg, minsz))
680 			return -EFAULT;
681 
682 		if (info.argsz < minsz)
683 			return -EINVAL;
684 
685 		if (info.argsz >= capsz) {
686 			minsz = capsz;
687 			info.cap_offset = 0;
688 		}
689 
690 		info.flags = VFIO_DEVICE_FLAGS_PCI;
691 
692 		if (vdev->reset_works)
693 			info.flags |= VFIO_DEVICE_FLAGS_RESET;
694 
695 		info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions;
696 		info.num_irqs = VFIO_PCI_NUM_IRQS;
697 
698 		ret = vfio_pci_info_zdev_add_caps(vdev, &caps);
699 		if (ret && ret != -ENODEV) {
700 			pci_warn(vdev->pdev, "Failed to setup zPCI info capabilities\n");
701 			return ret;
702 		}
703 
704 		if (caps.size) {
705 			info.flags |= VFIO_DEVICE_FLAGS_CAPS;
706 			if (info.argsz < sizeof(info) + caps.size) {
707 				info.argsz = sizeof(info) + caps.size;
708 			} else {
709 				vfio_info_cap_shift(&caps, sizeof(info));
710 				if (copy_to_user((void __user *)arg +
711 						  sizeof(info), caps.buf,
712 						  caps.size)) {
713 					kfree(caps.buf);
714 					return -EFAULT;
715 				}
716 				info.cap_offset = sizeof(info);
717 			}
718 
719 			kfree(caps.buf);
720 		}
721 
722 		return copy_to_user((void __user *)arg, &info, minsz) ?
723 			-EFAULT : 0;
724 
725 	} else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
726 		struct pci_dev *pdev = vdev->pdev;
727 		struct vfio_region_info info;
728 		struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
729 		int i, ret;
730 
731 		minsz = offsetofend(struct vfio_region_info, offset);
732 
733 		if (copy_from_user(&info, (void __user *)arg, minsz))
734 			return -EFAULT;
735 
736 		if (info.argsz < minsz)
737 			return -EINVAL;
738 
739 		switch (info.index) {
740 		case VFIO_PCI_CONFIG_REGION_INDEX:
741 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
742 			info.size = pdev->cfg_size;
743 			info.flags = VFIO_REGION_INFO_FLAG_READ |
744 				     VFIO_REGION_INFO_FLAG_WRITE;
745 			break;
746 		case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
747 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
748 			info.size = pci_resource_len(pdev, info.index);
749 			if (!info.size) {
750 				info.flags = 0;
751 				break;
752 			}
753 
754 			info.flags = VFIO_REGION_INFO_FLAG_READ |
755 				     VFIO_REGION_INFO_FLAG_WRITE;
756 			if (vdev->bar_mmap_supported[info.index]) {
757 				info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
758 				if (info.index == vdev->msix_bar) {
759 					ret = msix_mmappable_cap(vdev, &caps);
760 					if (ret)
761 						return ret;
762 				}
763 			}
764 
765 			break;
766 		case VFIO_PCI_ROM_REGION_INDEX:
767 		{
768 			void __iomem *io;
769 			size_t size;
770 			u16 cmd;
771 
772 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
773 			info.flags = 0;
774 
775 			/* Report the BAR size, not the ROM size */
776 			info.size = pci_resource_len(pdev, info.index);
777 			if (!info.size) {
778 				/* Shadow ROMs appear as PCI option ROMs */
779 				if (pdev->resource[PCI_ROM_RESOURCE].flags &
780 							IORESOURCE_ROM_SHADOW)
781 					info.size = 0x20000;
782 				else
783 					break;
784 			}
785 
786 			/*
787 			 * Is it really there?  Enable memory decode for
788 			 * implicit access in pci_map_rom().
789 			 */
790 			cmd = vfio_pci_memory_lock_and_enable(vdev);
791 			io = pci_map_rom(pdev, &size);
792 			if (io) {
793 				info.flags = VFIO_REGION_INFO_FLAG_READ;
794 				pci_unmap_rom(pdev, io);
795 			} else {
796 				info.size = 0;
797 			}
798 			vfio_pci_memory_unlock_and_restore(vdev, cmd);
799 
800 			break;
801 		}
802 		case VFIO_PCI_VGA_REGION_INDEX:
803 			if (!vdev->has_vga)
804 				return -EINVAL;
805 
806 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
807 			info.size = 0xc0000;
808 			info.flags = VFIO_REGION_INFO_FLAG_READ |
809 				     VFIO_REGION_INFO_FLAG_WRITE;
810 
811 			break;
812 		default:
813 		{
814 			struct vfio_region_info_cap_type cap_type = {
815 					.header.id = VFIO_REGION_INFO_CAP_TYPE,
816 					.header.version = 1 };
817 
818 			if (info.index >=
819 			    VFIO_PCI_NUM_REGIONS + vdev->num_regions)
820 				return -EINVAL;
821 			info.index = array_index_nospec(info.index,
822 							VFIO_PCI_NUM_REGIONS +
823 							vdev->num_regions);
824 
825 			i = info.index - VFIO_PCI_NUM_REGIONS;
826 
827 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
828 			info.size = vdev->region[i].size;
829 			info.flags = vdev->region[i].flags;
830 
831 			cap_type.type = vdev->region[i].type;
832 			cap_type.subtype = vdev->region[i].subtype;
833 
834 			ret = vfio_info_add_capability(&caps, &cap_type.header,
835 						       sizeof(cap_type));
836 			if (ret)
837 				return ret;
838 
839 			if (vdev->region[i].ops->add_capability) {
840 				ret = vdev->region[i].ops->add_capability(vdev,
841 						&vdev->region[i], &caps);
842 				if (ret)
843 					return ret;
844 			}
845 		}
846 		}
847 
848 		if (caps.size) {
849 			info.flags |= VFIO_REGION_INFO_FLAG_CAPS;
850 			if (info.argsz < sizeof(info) + caps.size) {
851 				info.argsz = sizeof(info) + caps.size;
852 				info.cap_offset = 0;
853 			} else {
854 				vfio_info_cap_shift(&caps, sizeof(info));
855 				if (copy_to_user((void __user *)arg +
856 						  sizeof(info), caps.buf,
857 						  caps.size)) {
858 					kfree(caps.buf);
859 					return -EFAULT;
860 				}
861 				info.cap_offset = sizeof(info);
862 			}
863 
864 			kfree(caps.buf);
865 		}
866 
867 		return copy_to_user((void __user *)arg, &info, minsz) ?
868 			-EFAULT : 0;
869 
870 	} else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
871 		struct vfio_irq_info info;
872 
873 		minsz = offsetofend(struct vfio_irq_info, count);
874 
875 		if (copy_from_user(&info, (void __user *)arg, minsz))
876 			return -EFAULT;
877 
878 		if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
879 			return -EINVAL;
880 
881 		switch (info.index) {
882 		case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
883 		case VFIO_PCI_REQ_IRQ_INDEX:
884 			break;
885 		case VFIO_PCI_ERR_IRQ_INDEX:
886 			if (pci_is_pcie(vdev->pdev))
887 				break;
888 			fallthrough;
889 		default:
890 			return -EINVAL;
891 		}
892 
893 		info.flags = VFIO_IRQ_INFO_EVENTFD;
894 
895 		info.count = vfio_pci_get_irq_count(vdev, info.index);
896 
897 		if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
898 			info.flags |= (VFIO_IRQ_INFO_MASKABLE |
899 				       VFIO_IRQ_INFO_AUTOMASKED);
900 		else
901 			info.flags |= VFIO_IRQ_INFO_NORESIZE;
902 
903 		return copy_to_user((void __user *)arg, &info, minsz) ?
904 			-EFAULT : 0;
905 
906 	} else if (cmd == VFIO_DEVICE_SET_IRQS) {
907 		struct vfio_irq_set hdr;
908 		u8 *data = NULL;
909 		int max, ret = 0;
910 		size_t data_size = 0;
911 
912 		minsz = offsetofend(struct vfio_irq_set, count);
913 
914 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
915 			return -EFAULT;
916 
917 		max = vfio_pci_get_irq_count(vdev, hdr.index);
918 
919 		ret = vfio_set_irqs_validate_and_prepare(&hdr, max,
920 						 VFIO_PCI_NUM_IRQS, &data_size);
921 		if (ret)
922 			return ret;
923 
924 		if (data_size) {
925 			data = memdup_user((void __user *)(arg + minsz),
926 					    data_size);
927 			if (IS_ERR(data))
928 				return PTR_ERR(data);
929 		}
930 
931 		mutex_lock(&vdev->igate);
932 
933 		ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
934 					      hdr.start, hdr.count, data);
935 
936 		mutex_unlock(&vdev->igate);
937 		kfree(data);
938 
939 		return ret;
940 
941 	} else if (cmd == VFIO_DEVICE_RESET) {
942 		int ret;
943 
944 		if (!vdev->reset_works)
945 			return -EINVAL;
946 
947 		vfio_pci_zap_and_down_write_memory_lock(vdev);
948 
949 		/*
950 		 * This function can be invoked while the power state is non-D0.
951 		 * If pci_try_reset_function() has been called while the power
952 		 * state is non-D0, then pci_try_reset_function() will
953 		 * internally set the power state to D0 without vfio driver
954 		 * involvement. For the devices which have NoSoftRst-, the
955 		 * reset function can cause the PCI config space reset without
956 		 * restoring the original state (saved locally in
957 		 * 'vdev->pm_save').
958 		 */
959 		vfio_pci_set_power_state(vdev, PCI_D0);
960 
961 		ret = pci_try_reset_function(vdev->pdev);
962 		up_write(&vdev->memory_lock);
963 
964 		return ret;
965 
966 	} else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
967 		struct vfio_pci_hot_reset_info hdr;
968 		struct vfio_pci_fill_info fill = { 0 };
969 		struct vfio_pci_dependent_device *devices = NULL;
970 		bool slot = false;
971 		int ret = 0;
972 
973 		minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
974 
975 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
976 			return -EFAULT;
977 
978 		if (hdr.argsz < minsz)
979 			return -EINVAL;
980 
981 		hdr.flags = 0;
982 
983 		/* Can we do a slot or bus reset or neither? */
984 		if (!pci_probe_reset_slot(vdev->pdev->slot))
985 			slot = true;
986 		else if (pci_probe_reset_bus(vdev->pdev->bus))
987 			return -ENODEV;
988 
989 		/* How many devices are affected? */
990 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
991 						    vfio_pci_count_devs,
992 						    &fill.max, slot);
993 		if (ret)
994 			return ret;
995 
996 		WARN_ON(!fill.max); /* Should always be at least one */
997 
998 		/*
999 		 * If there's enough space, fill it now, otherwise return
1000 		 * -ENOSPC and the number of devices affected.
1001 		 */
1002 		if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
1003 			ret = -ENOSPC;
1004 			hdr.count = fill.max;
1005 			goto reset_info_exit;
1006 		}
1007 
1008 		devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
1009 		if (!devices)
1010 			return -ENOMEM;
1011 
1012 		fill.devices = devices;
1013 
1014 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1015 						    vfio_pci_fill_devs,
1016 						    &fill, slot);
1017 
1018 		/*
1019 		 * If a device was removed between counting and filling,
1020 		 * we may come up short of fill.max.  If a device was
1021 		 * added, we'll have a return of -EAGAIN above.
1022 		 */
1023 		if (!ret)
1024 			hdr.count = fill.cur;
1025 
1026 reset_info_exit:
1027 		if (copy_to_user((void __user *)arg, &hdr, minsz))
1028 			ret = -EFAULT;
1029 
1030 		if (!ret) {
1031 			if (copy_to_user((void __user *)(arg + minsz), devices,
1032 					 hdr.count * sizeof(*devices)))
1033 				ret = -EFAULT;
1034 		}
1035 
1036 		kfree(devices);
1037 		return ret;
1038 
1039 	} else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
1040 		struct vfio_pci_hot_reset hdr;
1041 		int32_t *group_fds;
1042 		struct vfio_group **groups;
1043 		struct vfio_pci_group_info info;
1044 		bool slot = false;
1045 		int group_idx, count = 0, ret = 0;
1046 
1047 		minsz = offsetofend(struct vfio_pci_hot_reset, count);
1048 
1049 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
1050 			return -EFAULT;
1051 
1052 		if (hdr.argsz < minsz || hdr.flags)
1053 			return -EINVAL;
1054 
1055 		/* Can we do a slot or bus reset or neither? */
1056 		if (!pci_probe_reset_slot(vdev->pdev->slot))
1057 			slot = true;
1058 		else if (pci_probe_reset_bus(vdev->pdev->bus))
1059 			return -ENODEV;
1060 
1061 		/*
1062 		 * We can't let userspace give us an arbitrarily large
1063 		 * buffer to copy, so verify how many we think there
1064 		 * could be.  Note groups can have multiple devices so
1065 		 * one group per device is the max.
1066 		 */
1067 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1068 						    vfio_pci_count_devs,
1069 						    &count, slot);
1070 		if (ret)
1071 			return ret;
1072 
1073 		/* Somewhere between 1 and count is OK */
1074 		if (!hdr.count || hdr.count > count)
1075 			return -EINVAL;
1076 
1077 		group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
1078 		groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);
1079 		if (!group_fds || !groups) {
1080 			kfree(group_fds);
1081 			kfree(groups);
1082 			return -ENOMEM;
1083 		}
1084 
1085 		if (copy_from_user(group_fds, (void __user *)(arg + minsz),
1086 				   hdr.count * sizeof(*group_fds))) {
1087 			kfree(group_fds);
1088 			kfree(groups);
1089 			return -EFAULT;
1090 		}
1091 
1092 		/*
1093 		 * For each group_fd, get the group through the vfio external
1094 		 * user interface and store the group and iommu ID.  This
1095 		 * ensures the group is held across the reset.
1096 		 */
1097 		for (group_idx = 0; group_idx < hdr.count; group_idx++) {
1098 			struct vfio_group *group;
1099 			struct fd f = fdget(group_fds[group_idx]);
1100 			if (!f.file) {
1101 				ret = -EBADF;
1102 				break;
1103 			}
1104 
1105 			group = vfio_group_get_external_user(f.file);
1106 			fdput(f);
1107 			if (IS_ERR(group)) {
1108 				ret = PTR_ERR(group);
1109 				break;
1110 			}
1111 
1112 			groups[group_idx] = group;
1113 		}
1114 
1115 		kfree(group_fds);
1116 
1117 		/* release reference to groups on error */
1118 		if (ret)
1119 			goto hot_reset_release;
1120 
1121 		info.count = hdr.count;
1122 		info.groups = groups;
1123 
1124 		ret = vfio_pci_dev_set_hot_reset(vdev->vdev.dev_set, &info);
1125 
1126 hot_reset_release:
1127 		for (group_idx--; group_idx >= 0; group_idx--)
1128 			vfio_group_put_external_user(groups[group_idx]);
1129 
1130 		kfree(groups);
1131 		return ret;
1132 	} else if (cmd == VFIO_DEVICE_IOEVENTFD) {
1133 		struct vfio_device_ioeventfd ioeventfd;
1134 		int count;
1135 
1136 		minsz = offsetofend(struct vfio_device_ioeventfd, fd);
1137 
1138 		if (copy_from_user(&ioeventfd, (void __user *)arg, minsz))
1139 			return -EFAULT;
1140 
1141 		if (ioeventfd.argsz < minsz)
1142 			return -EINVAL;
1143 
1144 		if (ioeventfd.flags & ~VFIO_DEVICE_IOEVENTFD_SIZE_MASK)
1145 			return -EINVAL;
1146 
1147 		count = ioeventfd.flags & VFIO_DEVICE_IOEVENTFD_SIZE_MASK;
1148 
1149 		if (hweight8(count) != 1 || ioeventfd.fd < -1)
1150 			return -EINVAL;
1151 
1152 		return vfio_pci_ioeventfd(vdev, ioeventfd.offset,
1153 					  ioeventfd.data, count, ioeventfd.fd);
1154 	}
1155 	return -ENOTTY;
1156 }
1157 EXPORT_SYMBOL_GPL(vfio_pci_core_ioctl);
1158 
1159 static int vfio_pci_core_feature_token(struct vfio_device *device, u32 flags,
1160 				       void __user *arg, size_t argsz)
1161 {
1162 	struct vfio_pci_core_device *vdev =
1163 		container_of(device, struct vfio_pci_core_device, vdev);
1164 	uuid_t uuid;
1165 	int ret;
1166 
1167 	if (!vdev->vf_token)
1168 		return -ENOTTY;
1169 	/*
1170 	 * We do not support GET of the VF Token UUID as this could
1171 	 * expose the token of the previous device user.
1172 	 */
1173 	ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_SET,
1174 				 sizeof(uuid));
1175 	if (ret != 1)
1176 		return ret;
1177 
1178 	if (copy_from_user(&uuid, arg, sizeof(uuid)))
1179 		return -EFAULT;
1180 
1181 	mutex_lock(&vdev->vf_token->lock);
1182 	uuid_copy(&vdev->vf_token->uuid, &uuid);
1183 	mutex_unlock(&vdev->vf_token->lock);
1184 	return 0;
1185 }
1186 
1187 int vfio_pci_core_ioctl_feature(struct vfio_device *device, u32 flags,
1188 				void __user *arg, size_t argsz)
1189 {
1190 	switch (flags & VFIO_DEVICE_FEATURE_MASK) {
1191 	case VFIO_DEVICE_FEATURE_PCI_VF_TOKEN:
1192 		return vfio_pci_core_feature_token(device, flags, arg, argsz);
1193 	default:
1194 		return -ENOTTY;
1195 	}
1196 }
1197 EXPORT_SYMBOL_GPL(vfio_pci_core_ioctl_feature);
1198 
1199 static ssize_t vfio_pci_rw(struct vfio_pci_core_device *vdev, char __user *buf,
1200 			   size_t count, loff_t *ppos, bool iswrite)
1201 {
1202 	unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
1203 
1204 	if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1205 		return -EINVAL;
1206 
1207 	switch (index) {
1208 	case VFIO_PCI_CONFIG_REGION_INDEX:
1209 		return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
1210 
1211 	case VFIO_PCI_ROM_REGION_INDEX:
1212 		if (iswrite)
1213 			return -EINVAL;
1214 		return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
1215 
1216 	case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
1217 		return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
1218 
1219 	case VFIO_PCI_VGA_REGION_INDEX:
1220 		return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
1221 	default:
1222 		index -= VFIO_PCI_NUM_REGIONS;
1223 		return vdev->region[index].ops->rw(vdev, buf,
1224 						   count, ppos, iswrite);
1225 	}
1226 
1227 	return -EINVAL;
1228 }
1229 
1230 ssize_t vfio_pci_core_read(struct vfio_device *core_vdev, char __user *buf,
1231 		size_t count, loff_t *ppos)
1232 {
1233 	struct vfio_pci_core_device *vdev =
1234 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1235 
1236 	if (!count)
1237 		return 0;
1238 
1239 	return vfio_pci_rw(vdev, buf, count, ppos, false);
1240 }
1241 EXPORT_SYMBOL_GPL(vfio_pci_core_read);
1242 
1243 ssize_t vfio_pci_core_write(struct vfio_device *core_vdev, const char __user *buf,
1244 		size_t count, loff_t *ppos)
1245 {
1246 	struct vfio_pci_core_device *vdev =
1247 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1248 
1249 	if (!count)
1250 		return 0;
1251 
1252 	return vfio_pci_rw(vdev, (char __user *)buf, count, ppos, true);
1253 }
1254 EXPORT_SYMBOL_GPL(vfio_pci_core_write);
1255 
1256 /* Return 1 on zap and vma_lock acquired, 0 on contention (only with @try) */
1257 static int vfio_pci_zap_and_vma_lock(struct vfio_pci_core_device *vdev, bool try)
1258 {
1259 	struct vfio_pci_mmap_vma *mmap_vma, *tmp;
1260 
1261 	/*
1262 	 * Lock ordering:
1263 	 * vma_lock is nested under mmap_lock for vm_ops callback paths.
1264 	 * The memory_lock semaphore is used by both code paths calling
1265 	 * into this function to zap vmas and the vm_ops.fault callback
1266 	 * to protect the memory enable state of the device.
1267 	 *
1268 	 * When zapping vmas we need to maintain the mmap_lock => vma_lock
1269 	 * ordering, which requires using vma_lock to walk vma_list to
1270 	 * acquire an mm, then dropping vma_lock to get the mmap_lock and
1271 	 * reacquiring vma_lock.  This logic is derived from similar
1272 	 * requirements in uverbs_user_mmap_disassociate().
1273 	 *
1274 	 * mmap_lock must always be the top-level lock when it is taken.
1275 	 * Therefore we can only hold the memory_lock write lock when
1276 	 * vma_list is empty, as we'd need to take mmap_lock to clear
1277 	 * entries.  vma_list can only be guaranteed empty when holding
1278 	 * vma_lock, thus memory_lock is nested under vma_lock.
1279 	 *
1280 	 * This enables the vm_ops.fault callback to acquire vma_lock,
1281 	 * followed by memory_lock read lock, while already holding
1282 	 * mmap_lock without risk of deadlock.
1283 	 */
1284 	while (1) {
1285 		struct mm_struct *mm = NULL;
1286 
1287 		if (try) {
1288 			if (!mutex_trylock(&vdev->vma_lock))
1289 				return 0;
1290 		} else {
1291 			mutex_lock(&vdev->vma_lock);
1292 		}
1293 		while (!list_empty(&vdev->vma_list)) {
1294 			mmap_vma = list_first_entry(&vdev->vma_list,
1295 						    struct vfio_pci_mmap_vma,
1296 						    vma_next);
1297 			mm = mmap_vma->vma->vm_mm;
1298 			if (mmget_not_zero(mm))
1299 				break;
1300 
1301 			list_del(&mmap_vma->vma_next);
1302 			kfree(mmap_vma);
1303 			mm = NULL;
1304 		}
1305 		if (!mm)
1306 			return 1;
1307 		mutex_unlock(&vdev->vma_lock);
1308 
1309 		if (try) {
1310 			if (!mmap_read_trylock(mm)) {
1311 				mmput(mm);
1312 				return 0;
1313 			}
1314 		} else {
1315 			mmap_read_lock(mm);
1316 		}
1317 		if (try) {
1318 			if (!mutex_trylock(&vdev->vma_lock)) {
1319 				mmap_read_unlock(mm);
1320 				mmput(mm);
1321 				return 0;
1322 			}
1323 		} else {
1324 			mutex_lock(&vdev->vma_lock);
1325 		}
1326 		list_for_each_entry_safe(mmap_vma, tmp,
1327 					 &vdev->vma_list, vma_next) {
1328 			struct vm_area_struct *vma = mmap_vma->vma;
1329 
1330 			if (vma->vm_mm != mm)
1331 				continue;
1332 
1333 			list_del(&mmap_vma->vma_next);
1334 			kfree(mmap_vma);
1335 
1336 			zap_vma_ptes(vma, vma->vm_start,
1337 				     vma->vm_end - vma->vm_start);
1338 		}
1339 		mutex_unlock(&vdev->vma_lock);
1340 		mmap_read_unlock(mm);
1341 		mmput(mm);
1342 	}
1343 }
1344 
1345 void vfio_pci_zap_and_down_write_memory_lock(struct vfio_pci_core_device *vdev)
1346 {
1347 	vfio_pci_zap_and_vma_lock(vdev, false);
1348 	down_write(&vdev->memory_lock);
1349 	mutex_unlock(&vdev->vma_lock);
1350 }
1351 
1352 u16 vfio_pci_memory_lock_and_enable(struct vfio_pci_core_device *vdev)
1353 {
1354 	u16 cmd;
1355 
1356 	down_write(&vdev->memory_lock);
1357 	pci_read_config_word(vdev->pdev, PCI_COMMAND, &cmd);
1358 	if (!(cmd & PCI_COMMAND_MEMORY))
1359 		pci_write_config_word(vdev->pdev, PCI_COMMAND,
1360 				      cmd | PCI_COMMAND_MEMORY);
1361 
1362 	return cmd;
1363 }
1364 
1365 void vfio_pci_memory_unlock_and_restore(struct vfio_pci_core_device *vdev, u16 cmd)
1366 {
1367 	pci_write_config_word(vdev->pdev, PCI_COMMAND, cmd);
1368 	up_write(&vdev->memory_lock);
1369 }
1370 
1371 /* Caller holds vma_lock */
1372 static int __vfio_pci_add_vma(struct vfio_pci_core_device *vdev,
1373 			      struct vm_area_struct *vma)
1374 {
1375 	struct vfio_pci_mmap_vma *mmap_vma;
1376 
1377 	mmap_vma = kmalloc(sizeof(*mmap_vma), GFP_KERNEL);
1378 	if (!mmap_vma)
1379 		return -ENOMEM;
1380 
1381 	mmap_vma->vma = vma;
1382 	list_add(&mmap_vma->vma_next, &vdev->vma_list);
1383 
1384 	return 0;
1385 }
1386 
1387 /*
1388  * Zap mmaps on open so that we can fault them in on access and therefore
1389  * our vma_list only tracks mappings accessed since last zap.
1390  */
1391 static void vfio_pci_mmap_open(struct vm_area_struct *vma)
1392 {
1393 	zap_vma_ptes(vma, vma->vm_start, vma->vm_end - vma->vm_start);
1394 }
1395 
1396 static void vfio_pci_mmap_close(struct vm_area_struct *vma)
1397 {
1398 	struct vfio_pci_core_device *vdev = vma->vm_private_data;
1399 	struct vfio_pci_mmap_vma *mmap_vma;
1400 
1401 	mutex_lock(&vdev->vma_lock);
1402 	list_for_each_entry(mmap_vma, &vdev->vma_list, vma_next) {
1403 		if (mmap_vma->vma == vma) {
1404 			list_del(&mmap_vma->vma_next);
1405 			kfree(mmap_vma);
1406 			break;
1407 		}
1408 	}
1409 	mutex_unlock(&vdev->vma_lock);
1410 }
1411 
1412 static vm_fault_t vfio_pci_mmap_fault(struct vm_fault *vmf)
1413 {
1414 	struct vm_area_struct *vma = vmf->vma;
1415 	struct vfio_pci_core_device *vdev = vma->vm_private_data;
1416 	struct vfio_pci_mmap_vma *mmap_vma;
1417 	vm_fault_t ret = VM_FAULT_NOPAGE;
1418 
1419 	mutex_lock(&vdev->vma_lock);
1420 	down_read(&vdev->memory_lock);
1421 
1422 	if (!__vfio_pci_memory_enabled(vdev)) {
1423 		ret = VM_FAULT_SIGBUS;
1424 		goto up_out;
1425 	}
1426 
1427 	/*
1428 	 * We populate the whole vma on fault, so we need to test whether
1429 	 * the vma has already been mapped, such as for concurrent faults
1430 	 * to the same vma.  io_remap_pfn_range() will trigger a BUG_ON if
1431 	 * we ask it to fill the same range again.
1432 	 */
1433 	list_for_each_entry(mmap_vma, &vdev->vma_list, vma_next) {
1434 		if (mmap_vma->vma == vma)
1435 			goto up_out;
1436 	}
1437 
1438 	if (io_remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
1439 			       vma->vm_end - vma->vm_start,
1440 			       vma->vm_page_prot)) {
1441 		ret = VM_FAULT_SIGBUS;
1442 		zap_vma_ptes(vma, vma->vm_start, vma->vm_end - vma->vm_start);
1443 		goto up_out;
1444 	}
1445 
1446 	if (__vfio_pci_add_vma(vdev, vma)) {
1447 		ret = VM_FAULT_OOM;
1448 		zap_vma_ptes(vma, vma->vm_start, vma->vm_end - vma->vm_start);
1449 	}
1450 
1451 up_out:
1452 	up_read(&vdev->memory_lock);
1453 	mutex_unlock(&vdev->vma_lock);
1454 	return ret;
1455 }
1456 
1457 static const struct vm_operations_struct vfio_pci_mmap_ops = {
1458 	.open = vfio_pci_mmap_open,
1459 	.close = vfio_pci_mmap_close,
1460 	.fault = vfio_pci_mmap_fault,
1461 };
1462 
1463 int vfio_pci_core_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma)
1464 {
1465 	struct vfio_pci_core_device *vdev =
1466 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1467 	struct pci_dev *pdev = vdev->pdev;
1468 	unsigned int index;
1469 	u64 phys_len, req_len, pgoff, req_start;
1470 	int ret;
1471 
1472 	index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1473 
1474 	if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1475 		return -EINVAL;
1476 	if (vma->vm_end < vma->vm_start)
1477 		return -EINVAL;
1478 	if ((vma->vm_flags & VM_SHARED) == 0)
1479 		return -EINVAL;
1480 	if (index >= VFIO_PCI_NUM_REGIONS) {
1481 		int regnum = index - VFIO_PCI_NUM_REGIONS;
1482 		struct vfio_pci_region *region = vdev->region + regnum;
1483 
1484 		if (region->ops && region->ops->mmap &&
1485 		    (region->flags & VFIO_REGION_INFO_FLAG_MMAP))
1486 			return region->ops->mmap(vdev, region, vma);
1487 		return -EINVAL;
1488 	}
1489 	if (index >= VFIO_PCI_ROM_REGION_INDEX)
1490 		return -EINVAL;
1491 	if (!vdev->bar_mmap_supported[index])
1492 		return -EINVAL;
1493 
1494 	phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1495 	req_len = vma->vm_end - vma->vm_start;
1496 	pgoff = vma->vm_pgoff &
1497 		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1498 	req_start = pgoff << PAGE_SHIFT;
1499 
1500 	if (req_start + req_len > phys_len)
1501 		return -EINVAL;
1502 
1503 	/*
1504 	 * Even though we don't make use of the barmap for the mmap,
1505 	 * we need to request the region and the barmap tracks that.
1506 	 */
1507 	if (!vdev->barmap[index]) {
1508 		ret = pci_request_selected_regions(pdev,
1509 						   1 << index, "vfio-pci");
1510 		if (ret)
1511 			return ret;
1512 
1513 		vdev->barmap[index] = pci_iomap(pdev, index, 0);
1514 		if (!vdev->barmap[index]) {
1515 			pci_release_selected_regions(pdev, 1 << index);
1516 			return -ENOMEM;
1517 		}
1518 	}
1519 
1520 	vma->vm_private_data = vdev;
1521 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1522 	vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
1523 
1524 	/*
1525 	 * See remap_pfn_range(), called from vfio_pci_fault() but we can't
1526 	 * change vm_flags within the fault handler.  Set them now.
1527 	 */
1528 	vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
1529 	vma->vm_ops = &vfio_pci_mmap_ops;
1530 
1531 	return 0;
1532 }
1533 EXPORT_SYMBOL_GPL(vfio_pci_core_mmap);
1534 
1535 void vfio_pci_core_request(struct vfio_device *core_vdev, unsigned int count)
1536 {
1537 	struct vfio_pci_core_device *vdev =
1538 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1539 	struct pci_dev *pdev = vdev->pdev;
1540 
1541 	mutex_lock(&vdev->igate);
1542 
1543 	if (vdev->req_trigger) {
1544 		if (!(count % 10))
1545 			pci_notice_ratelimited(pdev,
1546 				"Relaying device request to user (#%u)\n",
1547 				count);
1548 		eventfd_signal(vdev->req_trigger, 1);
1549 	} else if (count == 0) {
1550 		pci_warn(pdev,
1551 			"No device request channel registered, blocked until released by user\n");
1552 	}
1553 
1554 	mutex_unlock(&vdev->igate);
1555 }
1556 EXPORT_SYMBOL_GPL(vfio_pci_core_request);
1557 
1558 static int vfio_pci_validate_vf_token(struct vfio_pci_core_device *vdev,
1559 				      bool vf_token, uuid_t *uuid)
1560 {
1561 	/*
1562 	 * There's always some degree of trust or collaboration between SR-IOV
1563 	 * PF and VFs, even if just that the PF hosts the SR-IOV capability and
1564 	 * can disrupt VFs with a reset, but often the PF has more explicit
1565 	 * access to deny service to the VF or access data passed through the
1566 	 * VF.  We therefore require an opt-in via a shared VF token (UUID) to
1567 	 * represent this trust.  This both prevents that a VF driver might
1568 	 * assume the PF driver is a trusted, in-kernel driver, and also that
1569 	 * a PF driver might be replaced with a rogue driver, unknown to in-use
1570 	 * VF drivers.
1571 	 *
1572 	 * Therefore when presented with a VF, if the PF is a vfio device and
1573 	 * it is bound to the vfio-pci driver, the user needs to provide a VF
1574 	 * token to access the device, in the form of appending a vf_token to
1575 	 * the device name, for example:
1576 	 *
1577 	 * "0000:04:10.0 vf_token=bd8d9d2b-5a5f-4f5a-a211-f591514ba1f3"
1578 	 *
1579 	 * When presented with a PF which has VFs in use, the user must also
1580 	 * provide the current VF token to prove collaboration with existing
1581 	 * VF users.  If VFs are not in use, the VF token provided for the PF
1582 	 * device will act to set the VF token.
1583 	 *
1584 	 * If the VF token is provided but unused, an error is generated.
1585 	 */
1586 	if (!vdev->pdev->is_virtfn && !vdev->vf_token && !vf_token)
1587 		return 0; /* No VF token provided or required */
1588 
1589 	if (vdev->pdev->is_virtfn) {
1590 		struct vfio_pci_core_device *pf_vdev = get_pf_vdev(vdev);
1591 		bool match;
1592 
1593 		if (!pf_vdev) {
1594 			if (!vf_token)
1595 				return 0; /* PF is not vfio-pci, no VF token */
1596 
1597 			pci_info_ratelimited(vdev->pdev,
1598 				"VF token incorrectly provided, PF not bound to vfio-pci\n");
1599 			return -EINVAL;
1600 		}
1601 
1602 		if (!vf_token) {
1603 			vfio_device_put(&pf_vdev->vdev);
1604 			pci_info_ratelimited(vdev->pdev,
1605 				"VF token required to access device\n");
1606 			return -EACCES;
1607 		}
1608 
1609 		mutex_lock(&pf_vdev->vf_token->lock);
1610 		match = uuid_equal(uuid, &pf_vdev->vf_token->uuid);
1611 		mutex_unlock(&pf_vdev->vf_token->lock);
1612 
1613 		vfio_device_put(&pf_vdev->vdev);
1614 
1615 		if (!match) {
1616 			pci_info_ratelimited(vdev->pdev,
1617 				"Incorrect VF token provided for device\n");
1618 			return -EACCES;
1619 		}
1620 	} else if (vdev->vf_token) {
1621 		mutex_lock(&vdev->vf_token->lock);
1622 		if (vdev->vf_token->users) {
1623 			if (!vf_token) {
1624 				mutex_unlock(&vdev->vf_token->lock);
1625 				pci_info_ratelimited(vdev->pdev,
1626 					"VF token required to access device\n");
1627 				return -EACCES;
1628 			}
1629 
1630 			if (!uuid_equal(uuid, &vdev->vf_token->uuid)) {
1631 				mutex_unlock(&vdev->vf_token->lock);
1632 				pci_info_ratelimited(vdev->pdev,
1633 					"Incorrect VF token provided for device\n");
1634 				return -EACCES;
1635 			}
1636 		} else if (vf_token) {
1637 			uuid_copy(&vdev->vf_token->uuid, uuid);
1638 		}
1639 
1640 		mutex_unlock(&vdev->vf_token->lock);
1641 	} else if (vf_token) {
1642 		pci_info_ratelimited(vdev->pdev,
1643 			"VF token incorrectly provided, not a PF or VF\n");
1644 		return -EINVAL;
1645 	}
1646 
1647 	return 0;
1648 }
1649 
1650 #define VF_TOKEN_ARG "vf_token="
1651 
1652 int vfio_pci_core_match(struct vfio_device *core_vdev, char *buf)
1653 {
1654 	struct vfio_pci_core_device *vdev =
1655 		container_of(core_vdev, struct vfio_pci_core_device, vdev);
1656 	bool vf_token = false;
1657 	uuid_t uuid;
1658 	int ret;
1659 
1660 	if (strncmp(pci_name(vdev->pdev), buf, strlen(pci_name(vdev->pdev))))
1661 		return 0; /* No match */
1662 
1663 	if (strlen(buf) > strlen(pci_name(vdev->pdev))) {
1664 		buf += strlen(pci_name(vdev->pdev));
1665 
1666 		if (*buf != ' ')
1667 			return 0; /* No match: non-whitespace after name */
1668 
1669 		while (*buf) {
1670 			if (*buf == ' ') {
1671 				buf++;
1672 				continue;
1673 			}
1674 
1675 			if (!vf_token && !strncmp(buf, VF_TOKEN_ARG,
1676 						  strlen(VF_TOKEN_ARG))) {
1677 				buf += strlen(VF_TOKEN_ARG);
1678 
1679 				if (strlen(buf) < UUID_STRING_LEN)
1680 					return -EINVAL;
1681 
1682 				ret = uuid_parse(buf, &uuid);
1683 				if (ret)
1684 					return ret;
1685 
1686 				vf_token = true;
1687 				buf += UUID_STRING_LEN;
1688 			} else {
1689 				/* Unknown/duplicate option */
1690 				return -EINVAL;
1691 			}
1692 		}
1693 	}
1694 
1695 	ret = vfio_pci_validate_vf_token(vdev, vf_token, &uuid);
1696 	if (ret)
1697 		return ret;
1698 
1699 	return 1; /* Match */
1700 }
1701 EXPORT_SYMBOL_GPL(vfio_pci_core_match);
1702 
1703 static int vfio_pci_bus_notifier(struct notifier_block *nb,
1704 				 unsigned long action, void *data)
1705 {
1706 	struct vfio_pci_core_device *vdev = container_of(nb,
1707 						    struct vfio_pci_core_device, nb);
1708 	struct device *dev = data;
1709 	struct pci_dev *pdev = to_pci_dev(dev);
1710 	struct pci_dev *physfn = pci_physfn(pdev);
1711 
1712 	if (action == BUS_NOTIFY_ADD_DEVICE &&
1713 	    pdev->is_virtfn && physfn == vdev->pdev) {
1714 		pci_info(vdev->pdev, "Captured SR-IOV VF %s driver_override\n",
1715 			 pci_name(pdev));
1716 		pdev->driver_override = kasprintf(GFP_KERNEL, "%s",
1717 						  vdev->vdev.ops->name);
1718 	} else if (action == BUS_NOTIFY_BOUND_DRIVER &&
1719 		   pdev->is_virtfn && physfn == vdev->pdev) {
1720 		struct pci_driver *drv = pci_dev_driver(pdev);
1721 
1722 		if (drv && drv != pci_dev_driver(vdev->pdev))
1723 			pci_warn(vdev->pdev,
1724 				 "VF %s bound to driver %s while PF bound to driver %s\n",
1725 				 pci_name(pdev), drv->name,
1726 				 pci_dev_driver(vdev->pdev)->name);
1727 	}
1728 
1729 	return 0;
1730 }
1731 
1732 static int vfio_pci_vf_init(struct vfio_pci_core_device *vdev)
1733 {
1734 	struct pci_dev *pdev = vdev->pdev;
1735 	int ret;
1736 
1737 	if (!pdev->is_physfn)
1738 		return 0;
1739 
1740 	vdev->vf_token = kzalloc(sizeof(*vdev->vf_token), GFP_KERNEL);
1741 	if (!vdev->vf_token)
1742 		return -ENOMEM;
1743 
1744 	mutex_init(&vdev->vf_token->lock);
1745 	uuid_gen(&vdev->vf_token->uuid);
1746 
1747 	vdev->nb.notifier_call = vfio_pci_bus_notifier;
1748 	ret = bus_register_notifier(&pci_bus_type, &vdev->nb);
1749 	if (ret) {
1750 		kfree(vdev->vf_token);
1751 		return ret;
1752 	}
1753 	return 0;
1754 }
1755 
1756 static void vfio_pci_vf_uninit(struct vfio_pci_core_device *vdev)
1757 {
1758 	if (!vdev->vf_token)
1759 		return;
1760 
1761 	bus_unregister_notifier(&pci_bus_type, &vdev->nb);
1762 	WARN_ON(vdev->vf_token->users);
1763 	mutex_destroy(&vdev->vf_token->lock);
1764 	kfree(vdev->vf_token);
1765 }
1766 
1767 static int vfio_pci_vga_init(struct vfio_pci_core_device *vdev)
1768 {
1769 	struct pci_dev *pdev = vdev->pdev;
1770 	int ret;
1771 
1772 	if (!vfio_pci_is_vga(pdev))
1773 		return 0;
1774 
1775 	ret = vga_client_register(pdev, vfio_pci_set_decode);
1776 	if (ret)
1777 		return ret;
1778 	vga_set_legacy_decoding(pdev, vfio_pci_set_decode(pdev, false));
1779 	return 0;
1780 }
1781 
1782 static void vfio_pci_vga_uninit(struct vfio_pci_core_device *vdev)
1783 {
1784 	struct pci_dev *pdev = vdev->pdev;
1785 
1786 	if (!vfio_pci_is_vga(pdev))
1787 		return;
1788 	vga_client_unregister(pdev);
1789 	vga_set_legacy_decoding(pdev, VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
1790 					      VGA_RSRC_LEGACY_IO |
1791 					      VGA_RSRC_LEGACY_MEM);
1792 }
1793 
1794 void vfio_pci_core_init_device(struct vfio_pci_core_device *vdev,
1795 			       struct pci_dev *pdev,
1796 			       const struct vfio_device_ops *vfio_pci_ops)
1797 {
1798 	vfio_init_group_dev(&vdev->vdev, &pdev->dev, vfio_pci_ops);
1799 	vdev->pdev = pdev;
1800 	vdev->irq_type = VFIO_PCI_NUM_IRQS;
1801 	mutex_init(&vdev->igate);
1802 	spin_lock_init(&vdev->irqlock);
1803 	mutex_init(&vdev->ioeventfds_lock);
1804 	INIT_LIST_HEAD(&vdev->dummy_resources_list);
1805 	INIT_LIST_HEAD(&vdev->ioeventfds_list);
1806 	mutex_init(&vdev->vma_lock);
1807 	INIT_LIST_HEAD(&vdev->vma_list);
1808 	init_rwsem(&vdev->memory_lock);
1809 }
1810 EXPORT_SYMBOL_GPL(vfio_pci_core_init_device);
1811 
1812 void vfio_pci_core_uninit_device(struct vfio_pci_core_device *vdev)
1813 {
1814 	mutex_destroy(&vdev->igate);
1815 	mutex_destroy(&vdev->ioeventfds_lock);
1816 	mutex_destroy(&vdev->vma_lock);
1817 	vfio_uninit_group_dev(&vdev->vdev);
1818 	kfree(vdev->region);
1819 	kfree(vdev->pm_save);
1820 }
1821 EXPORT_SYMBOL_GPL(vfio_pci_core_uninit_device);
1822 
1823 int vfio_pci_core_register_device(struct vfio_pci_core_device *vdev)
1824 {
1825 	struct pci_dev *pdev = vdev->pdev;
1826 	int ret;
1827 
1828 	if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
1829 		return -EINVAL;
1830 
1831 	/*
1832 	 * Prevent binding to PFs with VFs enabled, the VFs might be in use
1833 	 * by the host or other users.  We cannot capture the VFs if they
1834 	 * already exist, nor can we track VF users.  Disabling SR-IOV here
1835 	 * would initiate removing the VFs, which would unbind the driver,
1836 	 * which is prone to blocking if that VF is also in use by vfio-pci.
1837 	 * Just reject these PFs and let the user sort it out.
1838 	 */
1839 	if (pci_num_vf(pdev)) {
1840 		pci_warn(pdev, "Cannot bind to PF with SR-IOV enabled\n");
1841 		return -EBUSY;
1842 	}
1843 
1844 	if (pci_is_root_bus(pdev->bus)) {
1845 		ret = vfio_assign_device_set(&vdev->vdev, vdev);
1846 	} else if (!pci_probe_reset_slot(pdev->slot)) {
1847 		ret = vfio_assign_device_set(&vdev->vdev, pdev->slot);
1848 	} else {
1849 		/*
1850 		 * If there is no slot reset support for this device, the whole
1851 		 * bus needs to be grouped together to support bus-wide resets.
1852 		 */
1853 		ret = vfio_assign_device_set(&vdev->vdev, pdev->bus);
1854 	}
1855 
1856 	if (ret)
1857 		return ret;
1858 	ret = vfio_pci_vf_init(vdev);
1859 	if (ret)
1860 		return ret;
1861 	ret = vfio_pci_vga_init(vdev);
1862 	if (ret)
1863 		goto out_vf;
1864 
1865 	vfio_pci_probe_power_state(vdev);
1866 
1867 	if (!disable_idle_d3) {
1868 		/*
1869 		 * pci-core sets the device power state to an unknown value at
1870 		 * bootup and after being removed from a driver.  The only
1871 		 * transition it allows from this unknown state is to D0, which
1872 		 * typically happens when a driver calls pci_enable_device().
1873 		 * We're not ready to enable the device yet, but we do want to
1874 		 * be able to get to D3.  Therefore first do a D0 transition
1875 		 * before going to D3.
1876 		 */
1877 		vfio_pci_set_power_state(vdev, PCI_D0);
1878 		vfio_pci_set_power_state(vdev, PCI_D3hot);
1879 	}
1880 
1881 	ret = vfio_register_group_dev(&vdev->vdev);
1882 	if (ret)
1883 		goto out_power;
1884 	return 0;
1885 
1886 out_power:
1887 	if (!disable_idle_d3)
1888 		vfio_pci_set_power_state(vdev, PCI_D0);
1889 out_vf:
1890 	vfio_pci_vf_uninit(vdev);
1891 	return ret;
1892 }
1893 EXPORT_SYMBOL_GPL(vfio_pci_core_register_device);
1894 
1895 void vfio_pci_core_unregister_device(struct vfio_pci_core_device *vdev)
1896 {
1897 	struct pci_dev *pdev = vdev->pdev;
1898 
1899 	pci_disable_sriov(pdev);
1900 
1901 	vfio_unregister_group_dev(&vdev->vdev);
1902 
1903 	vfio_pci_vf_uninit(vdev);
1904 	vfio_pci_vga_uninit(vdev);
1905 
1906 	if (!disable_idle_d3)
1907 		vfio_pci_set_power_state(vdev, PCI_D0);
1908 }
1909 EXPORT_SYMBOL_GPL(vfio_pci_core_unregister_device);
1910 
1911 pci_ers_result_t vfio_pci_core_aer_err_detected(struct pci_dev *pdev,
1912 						pci_channel_state_t state)
1913 {
1914 	struct vfio_pci_core_device *vdev;
1915 	struct vfio_device *device;
1916 
1917 	device = vfio_device_get_from_dev(&pdev->dev);
1918 	if (device == NULL)
1919 		return PCI_ERS_RESULT_DISCONNECT;
1920 
1921 	vdev = container_of(device, struct vfio_pci_core_device, vdev);
1922 
1923 	mutex_lock(&vdev->igate);
1924 
1925 	if (vdev->err_trigger)
1926 		eventfd_signal(vdev->err_trigger, 1);
1927 
1928 	mutex_unlock(&vdev->igate);
1929 
1930 	vfio_device_put(device);
1931 
1932 	return PCI_ERS_RESULT_CAN_RECOVER;
1933 }
1934 EXPORT_SYMBOL_GPL(vfio_pci_core_aer_err_detected);
1935 
1936 int vfio_pci_core_sriov_configure(struct pci_dev *pdev, int nr_virtfn)
1937 {
1938 	struct vfio_device *device;
1939 	int ret = 0;
1940 
1941 	device = vfio_device_get_from_dev(&pdev->dev);
1942 	if (!device)
1943 		return -ENODEV;
1944 
1945 	if (nr_virtfn == 0)
1946 		pci_disable_sriov(pdev);
1947 	else
1948 		ret = pci_enable_sriov(pdev, nr_virtfn);
1949 
1950 	vfio_device_put(device);
1951 
1952 	return ret < 0 ? ret : nr_virtfn;
1953 }
1954 EXPORT_SYMBOL_GPL(vfio_pci_core_sriov_configure);
1955 
1956 const struct pci_error_handlers vfio_pci_core_err_handlers = {
1957 	.error_detected = vfio_pci_core_aer_err_detected,
1958 };
1959 EXPORT_SYMBOL_GPL(vfio_pci_core_err_handlers);
1960 
1961 static bool vfio_dev_in_groups(struct vfio_pci_core_device *vdev,
1962 			       struct vfio_pci_group_info *groups)
1963 {
1964 	unsigned int i;
1965 
1966 	for (i = 0; i < groups->count; i++)
1967 		if (groups->groups[i] == vdev->vdev.group)
1968 			return true;
1969 	return false;
1970 }
1971 
1972 static int vfio_pci_is_device_in_set(struct pci_dev *pdev, void *data)
1973 {
1974 	struct vfio_device_set *dev_set = data;
1975 	struct vfio_device *cur;
1976 
1977 	list_for_each_entry(cur, &dev_set->device_list, dev_set_list)
1978 		if (cur->dev == &pdev->dev)
1979 			return 0;
1980 	return -EBUSY;
1981 }
1982 
1983 /*
1984  * vfio-core considers a group to be viable and will create a vfio_device even
1985  * if some devices are bound to drivers like pci-stub or pcieport. Here we
1986  * require all PCI devices to be inside our dev_set since that ensures they stay
1987  * put and that every driver controlling the device can co-ordinate with the
1988  * device reset.
1989  *
1990  * Returns the pci_dev to pass to pci_reset_bus() if every PCI device to be
1991  * reset is inside the dev_set, and pci_reset_bus() can succeed. NULL otherwise.
1992  */
1993 static struct pci_dev *
1994 vfio_pci_dev_set_resettable(struct vfio_device_set *dev_set)
1995 {
1996 	struct pci_dev *pdev;
1997 
1998 	lockdep_assert_held(&dev_set->lock);
1999 
2000 	/*
2001 	 * By definition all PCI devices in the dev_set share the same PCI
2002 	 * reset, so any pci_dev will have the same outcomes for
2003 	 * pci_probe_reset_*() and pci_reset_bus().
2004 	 */
2005 	pdev = list_first_entry(&dev_set->device_list,
2006 				struct vfio_pci_core_device,
2007 				vdev.dev_set_list)->pdev;
2008 
2009 	/* pci_reset_bus() is supported */
2010 	if (pci_probe_reset_slot(pdev->slot) && pci_probe_reset_bus(pdev->bus))
2011 		return NULL;
2012 
2013 	if (vfio_pci_for_each_slot_or_bus(pdev, vfio_pci_is_device_in_set,
2014 					  dev_set,
2015 					  !pci_probe_reset_slot(pdev->slot)))
2016 		return NULL;
2017 	return pdev;
2018 }
2019 
2020 /*
2021  * We need to get memory_lock for each device, but devices can share mmap_lock,
2022  * therefore we need to zap and hold the vma_lock for each device, and only then
2023  * get each memory_lock.
2024  */
2025 static int vfio_pci_dev_set_hot_reset(struct vfio_device_set *dev_set,
2026 				      struct vfio_pci_group_info *groups)
2027 {
2028 	struct vfio_pci_core_device *cur_mem;
2029 	struct vfio_pci_core_device *cur_vma;
2030 	struct vfio_pci_core_device *cur;
2031 	struct pci_dev *pdev;
2032 	bool is_mem = true;
2033 	int ret;
2034 
2035 	mutex_lock(&dev_set->lock);
2036 	cur_mem = list_first_entry(&dev_set->device_list,
2037 				   struct vfio_pci_core_device,
2038 				   vdev.dev_set_list);
2039 
2040 	pdev = vfio_pci_dev_set_resettable(dev_set);
2041 	if (!pdev) {
2042 		ret = -EINVAL;
2043 		goto err_unlock;
2044 	}
2045 
2046 	list_for_each_entry(cur_vma, &dev_set->device_list, vdev.dev_set_list) {
2047 		/*
2048 		 * Test whether all the affected devices are contained by the
2049 		 * set of groups provided by the user.
2050 		 */
2051 		if (!vfio_dev_in_groups(cur_vma, groups)) {
2052 			ret = -EINVAL;
2053 			goto err_undo;
2054 		}
2055 
2056 		/*
2057 		 * Locking multiple devices is prone to deadlock, runaway and
2058 		 * unwind if we hit contention.
2059 		 */
2060 		if (!vfio_pci_zap_and_vma_lock(cur_vma, true)) {
2061 			ret = -EBUSY;
2062 			goto err_undo;
2063 		}
2064 	}
2065 	cur_vma = NULL;
2066 
2067 	list_for_each_entry(cur_mem, &dev_set->device_list, vdev.dev_set_list) {
2068 		if (!down_write_trylock(&cur_mem->memory_lock)) {
2069 			ret = -EBUSY;
2070 			goto err_undo;
2071 		}
2072 		mutex_unlock(&cur_mem->vma_lock);
2073 	}
2074 	cur_mem = NULL;
2075 
2076 	/*
2077 	 * The pci_reset_bus() will reset all the devices in the bus.
2078 	 * The power state can be non-D0 for some of the devices in the bus.
2079 	 * For these devices, the pci_reset_bus() will internally set
2080 	 * the power state to D0 without vfio driver involvement.
2081 	 * For the devices which have NoSoftRst-, the reset function can
2082 	 * cause the PCI config space reset without restoring the original
2083 	 * state (saved locally in 'vdev->pm_save').
2084 	 */
2085 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list)
2086 		vfio_pci_set_power_state(cur, PCI_D0);
2087 
2088 	ret = pci_reset_bus(pdev);
2089 
2090 err_undo:
2091 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2092 		if (cur == cur_mem)
2093 			is_mem = false;
2094 		if (cur == cur_vma)
2095 			break;
2096 		if (is_mem)
2097 			up_write(&cur->memory_lock);
2098 		else
2099 			mutex_unlock(&cur->vma_lock);
2100 	}
2101 err_unlock:
2102 	mutex_unlock(&dev_set->lock);
2103 	return ret;
2104 }
2105 
2106 static bool vfio_pci_dev_set_needs_reset(struct vfio_device_set *dev_set)
2107 {
2108 	struct vfio_pci_core_device *cur;
2109 	bool needs_reset = false;
2110 
2111 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2112 		/* No VFIO device in the set can have an open device FD */
2113 		if (cur->vdev.open_count)
2114 			return false;
2115 		needs_reset |= cur->needs_reset;
2116 	}
2117 	return needs_reset;
2118 }
2119 
2120 /*
2121  * If a bus or slot reset is available for the provided dev_set and:
2122  *  - All of the devices affected by that bus or slot reset are unused
2123  *  - At least one of the affected devices is marked dirty via
2124  *    needs_reset (such as by lack of FLR support)
2125  * Then attempt to perform that bus or slot reset.
2126  * Returns true if the dev_set was reset.
2127  */
2128 static bool vfio_pci_dev_set_try_reset(struct vfio_device_set *dev_set)
2129 {
2130 	struct vfio_pci_core_device *cur;
2131 	struct pci_dev *pdev;
2132 	int ret;
2133 
2134 	if (!vfio_pci_dev_set_needs_reset(dev_set))
2135 		return false;
2136 
2137 	pdev = vfio_pci_dev_set_resettable(dev_set);
2138 	if (!pdev)
2139 		return false;
2140 
2141 	/*
2142 	 * The pci_reset_bus() will reset all the devices in the bus.
2143 	 * The power state can be non-D0 for some of the devices in the bus.
2144 	 * For these devices, the pci_reset_bus() will internally set
2145 	 * the power state to D0 without vfio driver involvement.
2146 	 * For the devices which have NoSoftRst-, the reset function can
2147 	 * cause the PCI config space reset without restoring the original
2148 	 * state (saved locally in 'vdev->pm_save').
2149 	 */
2150 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list)
2151 		vfio_pci_set_power_state(cur, PCI_D0);
2152 
2153 	ret = pci_reset_bus(pdev);
2154 	if (ret)
2155 		return false;
2156 
2157 	list_for_each_entry(cur, &dev_set->device_list, vdev.dev_set_list) {
2158 		cur->needs_reset = false;
2159 		if (!disable_idle_d3)
2160 			vfio_pci_set_power_state(cur, PCI_D3hot);
2161 	}
2162 	return true;
2163 }
2164 
2165 void vfio_pci_core_set_params(bool is_nointxmask, bool is_disable_vga,
2166 			      bool is_disable_idle_d3)
2167 {
2168 	nointxmask = is_nointxmask;
2169 	disable_vga = is_disable_vga;
2170 	disable_idle_d3 = is_disable_idle_d3;
2171 }
2172 EXPORT_SYMBOL_GPL(vfio_pci_core_set_params);
2173 
2174 static void vfio_pci_core_cleanup(void)
2175 {
2176 	vfio_pci_uninit_perm_bits();
2177 }
2178 
2179 static int __init vfio_pci_core_init(void)
2180 {
2181 	/* Allocate shared config space permission data used by all devices */
2182 	return vfio_pci_init_perm_bits();
2183 }
2184 
2185 module_init(vfio_pci_core_init);
2186 module_exit(vfio_pci_core_cleanup);
2187 
2188 MODULE_LICENSE("GPL v2");
2189 MODULE_AUTHOR(DRIVER_AUTHOR);
2190 MODULE_DESCRIPTION(DRIVER_DESC);
2191