• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 Red Hat, Inc.  All rights reserved.
3  *     Author: Alex Williamson <alex.williamson@redhat.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Derived from original vfio:
10  * Copyright 2010 Cisco Systems, Inc.  All rights reserved.
11  * Author: Tom Lyon, pugs@cisco.com
12  */
13 
14 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15 
16 #include <linux/device.h>
17 #include <linux/eventfd.h>
18 #include <linux/file.h>
19 #include <linux/interrupt.h>
20 #include <linux/iommu.h>
21 #include <linux/module.h>
22 #include <linux/mutex.h>
23 #include <linux/notifier.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/vfio.h>
30 #include <linux/vgaarb.h>
31 #include <linux/nospec.h>
32 #include <linux/sched/mm.h>
33 
34 #include "vfio_pci_private.h"
35 
36 #define DRIVER_VERSION  "0.2"
37 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
38 #define DRIVER_DESC     "VFIO PCI - User Level meta-driver"
39 
40 static char ids[1024] __initdata;
41 module_param_string(ids, ids, sizeof(ids), 0);
42 MODULE_PARM_DESC(ids, "Initial PCI IDs to add to the vfio driver, format is \"vendor:device[:subvendor[:subdevice[:class[:class_mask]]]]\" and multiple comma separated entries can be specified");
43 
44 static bool nointxmask;
45 module_param_named(nointxmask, nointxmask, bool, S_IRUGO | S_IWUSR);
46 MODULE_PARM_DESC(nointxmask,
47 		  "Disable support for PCI 2.3 style INTx masking.  If this resolves problems for specific devices, report lspci -vvvxxx to linux-pci@vger.kernel.org so the device can be fixed automatically via the broken_intx_masking flag.");
48 
49 #ifdef CONFIG_VFIO_PCI_VGA
50 static bool disable_vga;
51 module_param(disable_vga, bool, S_IRUGO);
52 MODULE_PARM_DESC(disable_vga, "Disable VGA resource access through vfio-pci");
53 #endif
54 
55 static bool disable_idle_d3;
56 module_param(disable_idle_d3, bool, S_IRUGO | S_IWUSR);
57 MODULE_PARM_DESC(disable_idle_d3,
58 		 "Disable using the PCI D3 low power state for idle, unused devices");
59 
60 static DEFINE_MUTEX(driver_lock);
61 
vfio_vga_disabled(void)62 static inline bool vfio_vga_disabled(void)
63 {
64 #ifdef CONFIG_VFIO_PCI_VGA
65 	return disable_vga;
66 #else
67 	return true;
68 #endif
69 }
70 
71 /*
72  * Our VGA arbiter participation is limited since we don't know anything
73  * about the device itself.  However, if the device is the only VGA device
74  * downstream of a bridge and VFIO VGA support is disabled, then we can
75  * safely return legacy VGA IO and memory as not decoded since the user
76  * has no way to get to it and routing can be disabled externally at the
77  * bridge.
78  */
vfio_pci_set_vga_decode(void * opaque,bool single_vga)79 static unsigned int vfio_pci_set_vga_decode(void *opaque, bool single_vga)
80 {
81 	struct vfio_pci_device *vdev = opaque;
82 	struct pci_dev *tmp = NULL, *pdev = vdev->pdev;
83 	unsigned char max_busnr;
84 	unsigned int decodes;
85 
86 	if (single_vga || !vfio_vga_disabled() || pci_is_root_bus(pdev->bus))
87 		return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
88 		       VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
89 
90 	max_busnr = pci_bus_max_busnr(pdev->bus);
91 	decodes = VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
92 
93 	while ((tmp = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, tmp)) != NULL) {
94 		if (tmp == pdev ||
95 		    pci_domain_nr(tmp->bus) != pci_domain_nr(pdev->bus) ||
96 		    pci_is_root_bus(tmp->bus))
97 			continue;
98 
99 		if (tmp->bus->number >= pdev->bus->number &&
100 		    tmp->bus->number <= max_busnr) {
101 			pci_dev_put(tmp);
102 			decodes |= VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
103 			break;
104 		}
105 	}
106 
107 	return decodes;
108 }
109 
vfio_pci_is_vga(struct pci_dev * pdev)110 static inline bool vfio_pci_is_vga(struct pci_dev *pdev)
111 {
112 	return (pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA;
113 }
114 
vfio_pci_probe_mmaps(struct vfio_pci_device * vdev)115 static void vfio_pci_probe_mmaps(struct vfio_pci_device *vdev)
116 {
117 	struct resource *res;
118 	int bar;
119 	struct vfio_pci_dummy_resource *dummy_res;
120 
121 	INIT_LIST_HEAD(&vdev->dummy_resources_list);
122 
123 	for (bar = PCI_STD_RESOURCES; bar <= PCI_STD_RESOURCE_END; bar++) {
124 		res = vdev->pdev->resource + bar;
125 
126 		if (!IS_ENABLED(CONFIG_VFIO_PCI_MMAP))
127 			goto no_mmap;
128 
129 		if (!(res->flags & IORESOURCE_MEM))
130 			goto no_mmap;
131 
132 		/*
133 		 * The PCI core shouldn't set up a resource with a
134 		 * type but zero size. But there may be bugs that
135 		 * cause us to do that.
136 		 */
137 		if (!resource_size(res))
138 			goto no_mmap;
139 
140 		if (resource_size(res) >= PAGE_SIZE) {
141 			vdev->bar_mmap_supported[bar] = true;
142 			continue;
143 		}
144 
145 		if (!(res->start & ~PAGE_MASK)) {
146 			/*
147 			 * Add a dummy resource to reserve the remainder
148 			 * of the exclusive page in case that hot-add
149 			 * device's bar is assigned into it.
150 			 */
151 			dummy_res = kzalloc(sizeof(*dummy_res), GFP_KERNEL);
152 			if (dummy_res == NULL)
153 				goto no_mmap;
154 
155 			dummy_res->resource.name = "vfio sub-page reserved";
156 			dummy_res->resource.start = res->end + 1;
157 			dummy_res->resource.end = res->start + PAGE_SIZE - 1;
158 			dummy_res->resource.flags = res->flags;
159 			if (request_resource(res->parent,
160 						&dummy_res->resource)) {
161 				kfree(dummy_res);
162 				goto no_mmap;
163 			}
164 			dummy_res->index = bar;
165 			list_add(&dummy_res->res_next,
166 					&vdev->dummy_resources_list);
167 			vdev->bar_mmap_supported[bar] = true;
168 			continue;
169 		}
170 		/*
171 		 * Here we don't handle the case when the BAR is not page
172 		 * aligned because we can't expect the BAR will be
173 		 * assigned into the same location in a page in guest
174 		 * when we passthrough the BAR. And it's hard to access
175 		 * this BAR in userspace because we have no way to get
176 		 * the BAR's location in a page.
177 		 */
178 no_mmap:
179 		vdev->bar_mmap_supported[bar] = false;
180 	}
181 }
182 
183 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev);
184 static void vfio_pci_disable(struct vfio_pci_device *vdev);
185 static int vfio_pci_try_zap_and_vma_lock_cb(struct pci_dev *pdev, void *data);
186 
187 /*
188  * INTx masking requires the ability to disable INTx signaling via PCI_COMMAND
189  * _and_ the ability detect when the device is asserting INTx via PCI_STATUS.
190  * If a device implements the former but not the latter we would typically
191  * expect broken_intx_masking be set and require an exclusive interrupt.
192  * However since we do have control of the device's ability to assert INTx,
193  * we can instead pretend that the device does not implement INTx, virtualizing
194  * the pin register to report zero and maintaining DisINTx set on the host.
195  */
vfio_pci_nointx(struct pci_dev * pdev)196 static bool vfio_pci_nointx(struct pci_dev *pdev)
197 {
198 	switch (pdev->vendor) {
199 	case PCI_VENDOR_ID_INTEL:
200 		switch (pdev->device) {
201 		/* All i40e (XL710/X710/XXV710) 10/20/25/40GbE NICs */
202 		case 0x1572:
203 		case 0x1574:
204 		case 0x1580 ... 0x1581:
205 		case 0x1583 ... 0x158b:
206 		case 0x37d0 ... 0x37d2:
207 			return true;
208 		default:
209 			return false;
210 		}
211 	}
212 
213 	return false;
214 }
215 
vfio_pci_enable(struct vfio_pci_device * vdev)216 static int vfio_pci_enable(struct vfio_pci_device *vdev)
217 {
218 	struct pci_dev *pdev = vdev->pdev;
219 	int ret;
220 	u16 cmd;
221 	u8 msix_pos;
222 
223 	pci_set_power_state(pdev, PCI_D0);
224 
225 	/* Don't allow our initial saved state to include busmaster */
226 	pci_clear_master(pdev);
227 
228 	ret = pci_enable_device(pdev);
229 	if (ret)
230 		return ret;
231 
232 	/* If reset fails because of the device lock, fail this path entirely */
233 	ret = pci_try_reset_function(pdev);
234 	if (ret == -EAGAIN) {
235 		pci_disable_device(pdev);
236 		return ret;
237 	}
238 
239 	vdev->reset_works = !ret;
240 	pci_save_state(pdev);
241 	vdev->pci_saved_state = pci_store_saved_state(pdev);
242 	if (!vdev->pci_saved_state)
243 		pr_debug("%s: Couldn't store %s saved state\n",
244 			 __func__, dev_name(&pdev->dev));
245 
246 	if (likely(!nointxmask)) {
247 		if (vfio_pci_nointx(pdev)) {
248 			dev_info(&pdev->dev, "Masking broken INTx support\n");
249 			vdev->nointx = true;
250 			pci_intx(pdev, 0);
251 		} else
252 			vdev->pci_2_3 = pci_intx_mask_supported(pdev);
253 	}
254 
255 	pci_read_config_word(pdev, PCI_COMMAND, &cmd);
256 	if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
257 		cmd &= ~PCI_COMMAND_INTX_DISABLE;
258 		pci_write_config_word(pdev, PCI_COMMAND, cmd);
259 	}
260 
261 	ret = vfio_config_init(vdev);
262 	if (ret) {
263 		kfree(vdev->pci_saved_state);
264 		vdev->pci_saved_state = NULL;
265 		pci_disable_device(pdev);
266 		return ret;
267 	}
268 
269 	msix_pos = pdev->msix_cap;
270 	if (msix_pos) {
271 		u16 flags;
272 		u32 table;
273 
274 		pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
275 		pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
276 
277 		vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
278 		vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
279 		vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
280 	} else
281 		vdev->msix_bar = 0xFF;
282 
283 	if (!vfio_vga_disabled() && vfio_pci_is_vga(pdev))
284 		vdev->has_vga = true;
285 
286 
287 	if (vfio_pci_is_vga(pdev) &&
288 	    pdev->vendor == PCI_VENDOR_ID_INTEL &&
289 	    IS_ENABLED(CONFIG_VFIO_PCI_IGD)) {
290 		ret = vfio_pci_igd_init(vdev);
291 		if (ret) {
292 			dev_warn(&vdev->pdev->dev,
293 				 "Failed to setup Intel IGD regions\n");
294 			vfio_pci_disable(vdev);
295 			return ret;
296 		}
297 	}
298 
299 	vfio_pci_probe_mmaps(vdev);
300 
301 	return 0;
302 }
303 
vfio_pci_disable(struct vfio_pci_device * vdev)304 static void vfio_pci_disable(struct vfio_pci_device *vdev)
305 {
306 	struct pci_dev *pdev = vdev->pdev;
307 	struct vfio_pci_dummy_resource *dummy_res, *tmp;
308 	struct vfio_pci_ioeventfd *ioeventfd, *ioeventfd_tmp;
309 	int i, bar;
310 
311 	/* Stop the device from further DMA */
312 	pci_clear_master(pdev);
313 
314 	vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
315 				VFIO_IRQ_SET_ACTION_TRIGGER,
316 				vdev->irq_type, 0, 0, NULL);
317 
318 	/* Device closed, don't need mutex here */
319 	list_for_each_entry_safe(ioeventfd, ioeventfd_tmp,
320 				 &vdev->ioeventfds_list, next) {
321 		vfio_virqfd_disable(&ioeventfd->virqfd);
322 		list_del(&ioeventfd->next);
323 		kfree(ioeventfd);
324 	}
325 	vdev->ioeventfds_nr = 0;
326 
327 	vdev->virq_disabled = false;
328 
329 	for (i = 0; i < vdev->num_regions; i++)
330 		vdev->region[i].ops->release(vdev, &vdev->region[i]);
331 
332 	vdev->num_regions = 0;
333 	kfree(vdev->region);
334 	vdev->region = NULL; /* don't krealloc a freed pointer */
335 
336 	vfio_config_free(vdev);
337 
338 	for (bar = PCI_STD_RESOURCES; bar <= PCI_STD_RESOURCE_END; bar++) {
339 		if (!vdev->barmap[bar])
340 			continue;
341 		pci_iounmap(pdev, vdev->barmap[bar]);
342 		pci_release_selected_regions(pdev, 1 << bar);
343 		vdev->barmap[bar] = NULL;
344 	}
345 
346 	list_for_each_entry_safe(dummy_res, tmp,
347 				 &vdev->dummy_resources_list, res_next) {
348 		list_del(&dummy_res->res_next);
349 		release_resource(&dummy_res->resource);
350 		kfree(dummy_res);
351 	}
352 
353 	vdev->needs_reset = true;
354 
355 	/*
356 	 * If we have saved state, restore it.  If we can reset the device,
357 	 * even better.  Resetting with current state seems better than
358 	 * nothing, but saving and restoring current state without reset
359 	 * is just busy work.
360 	 */
361 	if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
362 		pr_info("%s: Couldn't reload %s saved state\n",
363 			__func__, dev_name(&pdev->dev));
364 
365 		if (!vdev->reset_works)
366 			goto out;
367 
368 		pci_save_state(pdev);
369 	}
370 
371 	/*
372 	 * Disable INTx and MSI, presumably to avoid spurious interrupts
373 	 * during reset.  Stolen from pci_reset_function()
374 	 */
375 	pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
376 
377 	/*
378 	 * Try to get the locks ourselves to prevent a deadlock. The
379 	 * success of this is dependent on being able to lock the device,
380 	 * which is not always possible.
381 	 * We can not use the "try" reset interface here, which will
382 	 * overwrite the previously restored configuration information.
383 	 */
384 	if (vdev->reset_works && pci_cfg_access_trylock(pdev)) {
385 		if (device_trylock(&pdev->dev)) {
386 			if (!__pci_reset_function_locked(pdev))
387 				vdev->needs_reset = false;
388 			device_unlock(&pdev->dev);
389 		}
390 		pci_cfg_access_unlock(pdev);
391 	}
392 
393 	pci_restore_state(pdev);
394 out:
395 	pci_disable_device(pdev);
396 
397 	vfio_pci_try_bus_reset(vdev);
398 
399 	if (!disable_idle_d3)
400 		pci_set_power_state(pdev, PCI_D3hot);
401 }
402 
vfio_pci_release(void * device_data)403 static void vfio_pci_release(void *device_data)
404 {
405 	struct vfio_pci_device *vdev = device_data;
406 
407 	mutex_lock(&driver_lock);
408 
409 	if (!(--vdev->refcnt)) {
410 		vfio_spapr_pci_eeh_release(vdev->pdev);
411 		vfio_pci_disable(vdev);
412 		mutex_lock(&vdev->igate);
413 		if (vdev->err_trigger) {
414 			eventfd_ctx_put(vdev->err_trigger);
415 			vdev->err_trigger = NULL;
416 		}
417 		mutex_unlock(&vdev->igate);
418 
419 		mutex_lock(&vdev->igate);
420 		if (vdev->req_trigger) {
421 			eventfd_ctx_put(vdev->req_trigger);
422 			vdev->req_trigger = NULL;
423 		}
424 		mutex_unlock(&vdev->igate);
425 	}
426 
427 	mutex_unlock(&driver_lock);
428 
429 	module_put(THIS_MODULE);
430 }
431 
vfio_pci_open(void * device_data)432 static int vfio_pci_open(void *device_data)
433 {
434 	struct vfio_pci_device *vdev = device_data;
435 	int ret = 0;
436 
437 	if (!try_module_get(THIS_MODULE))
438 		return -ENODEV;
439 
440 	mutex_lock(&driver_lock);
441 
442 	if (!vdev->refcnt) {
443 		ret = vfio_pci_enable(vdev);
444 		if (ret)
445 			goto error;
446 
447 		vfio_spapr_pci_eeh_open(vdev->pdev);
448 	}
449 	vdev->refcnt++;
450 error:
451 	mutex_unlock(&driver_lock);
452 	if (ret)
453 		module_put(THIS_MODULE);
454 	return ret;
455 }
456 
vfio_pci_get_irq_count(struct vfio_pci_device * vdev,int irq_type)457 static int vfio_pci_get_irq_count(struct vfio_pci_device *vdev, int irq_type)
458 {
459 	if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
460 		u8 pin;
461 
462 		if (!IS_ENABLED(CONFIG_VFIO_PCI_INTX) ||
463 		    vdev->nointx || vdev->pdev->is_virtfn)
464 			return 0;
465 
466 		pci_read_config_byte(vdev->pdev, PCI_INTERRUPT_PIN, &pin);
467 
468 		return pin ? 1 : 0;
469 	} else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
470 		u8 pos;
471 		u16 flags;
472 
473 		pos = vdev->pdev->msi_cap;
474 		if (pos) {
475 			pci_read_config_word(vdev->pdev,
476 					     pos + PCI_MSI_FLAGS, &flags);
477 			return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
478 		}
479 	} else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
480 		u8 pos;
481 		u16 flags;
482 
483 		pos = vdev->pdev->msix_cap;
484 		if (pos) {
485 			pci_read_config_word(vdev->pdev,
486 					     pos + PCI_MSIX_FLAGS, &flags);
487 
488 			return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
489 		}
490 	} else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX) {
491 		if (pci_is_pcie(vdev->pdev))
492 			return 1;
493 	} else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
494 		return 1;
495 	}
496 
497 	return 0;
498 }
499 
vfio_pci_count_devs(struct pci_dev * pdev,void * data)500 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
501 {
502 	(*(int *)data)++;
503 	return 0;
504 }
505 
506 struct vfio_pci_fill_info {
507 	int max;
508 	int cur;
509 	struct vfio_pci_dependent_device *devices;
510 };
511 
vfio_pci_fill_devs(struct pci_dev * pdev,void * data)512 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
513 {
514 	struct vfio_pci_fill_info *fill = data;
515 	struct iommu_group *iommu_group;
516 
517 	if (fill->cur == fill->max)
518 		return -EAGAIN; /* Something changed, try again */
519 
520 	iommu_group = iommu_group_get(&pdev->dev);
521 	if (!iommu_group)
522 		return -EPERM; /* Cannot reset non-isolated devices */
523 
524 	fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
525 	fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
526 	fill->devices[fill->cur].bus = pdev->bus->number;
527 	fill->devices[fill->cur].devfn = pdev->devfn;
528 	fill->cur++;
529 	iommu_group_put(iommu_group);
530 	return 0;
531 }
532 
533 struct vfio_pci_group_entry {
534 	struct vfio_group *group;
535 	int id;
536 };
537 
538 struct vfio_pci_group_info {
539 	int count;
540 	struct vfio_pci_group_entry *groups;
541 };
542 
vfio_pci_validate_devs(struct pci_dev * pdev,void * data)543 static int vfio_pci_validate_devs(struct pci_dev *pdev, void *data)
544 {
545 	struct vfio_pci_group_info *info = data;
546 	struct iommu_group *group;
547 	int id, i;
548 
549 	group = iommu_group_get(&pdev->dev);
550 	if (!group)
551 		return -EPERM;
552 
553 	id = iommu_group_id(group);
554 
555 	for (i = 0; i < info->count; i++)
556 		if (info->groups[i].id == id)
557 			break;
558 
559 	iommu_group_put(group);
560 
561 	return (i == info->count) ? -EINVAL : 0;
562 }
563 
vfio_pci_dev_below_slot(struct pci_dev * pdev,struct pci_slot * slot)564 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
565 {
566 	for (; pdev; pdev = pdev->bus->self)
567 		if (pdev->bus == slot->bus)
568 			return (pdev->slot == slot);
569 	return false;
570 }
571 
572 struct vfio_pci_walk_info {
573 	int (*fn)(struct pci_dev *, void *data);
574 	void *data;
575 	struct pci_dev *pdev;
576 	bool slot;
577 	int ret;
578 };
579 
vfio_pci_walk_wrapper(struct pci_dev * pdev,void * data)580 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
581 {
582 	struct vfio_pci_walk_info *walk = data;
583 
584 	if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
585 		walk->ret = walk->fn(pdev, walk->data);
586 
587 	return walk->ret;
588 }
589 
vfio_pci_for_each_slot_or_bus(struct pci_dev * pdev,int (* fn)(struct pci_dev *,void * data),void * data,bool slot)590 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
591 					 int (*fn)(struct pci_dev *,
592 						   void *data), void *data,
593 					 bool slot)
594 {
595 	struct vfio_pci_walk_info walk = {
596 		.fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
597 	};
598 
599 	pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
600 
601 	return walk.ret;
602 }
603 
msix_mmappable_cap(struct vfio_pci_device * vdev,struct vfio_info_cap * caps)604 static int msix_mmappable_cap(struct vfio_pci_device *vdev,
605 			      struct vfio_info_cap *caps)
606 {
607 	struct vfio_info_cap_header header = {
608 		.id = VFIO_REGION_INFO_CAP_MSIX_MAPPABLE,
609 		.version = 1
610 	};
611 
612 	return vfio_info_add_capability(caps, &header, sizeof(header));
613 }
614 
vfio_pci_register_dev_region(struct vfio_pci_device * vdev,unsigned int type,unsigned int subtype,const struct vfio_pci_regops * ops,size_t size,u32 flags,void * data)615 int vfio_pci_register_dev_region(struct vfio_pci_device *vdev,
616 				 unsigned int type, unsigned int subtype,
617 				 const struct vfio_pci_regops *ops,
618 				 size_t size, u32 flags, void *data)
619 {
620 	struct vfio_pci_region *region;
621 
622 	region = krealloc(vdev->region,
623 			  (vdev->num_regions + 1) * sizeof(*region),
624 			  GFP_KERNEL);
625 	if (!region)
626 		return -ENOMEM;
627 
628 	vdev->region = region;
629 	vdev->region[vdev->num_regions].type = type;
630 	vdev->region[vdev->num_regions].subtype = subtype;
631 	vdev->region[vdev->num_regions].ops = ops;
632 	vdev->region[vdev->num_regions].size = size;
633 	vdev->region[vdev->num_regions].flags = flags;
634 	vdev->region[vdev->num_regions].data = data;
635 
636 	vdev->num_regions++;
637 
638 	return 0;
639 }
640 
641 struct vfio_devices {
642 	struct vfio_device **devices;
643 	int cur_index;
644 	int max_index;
645 };
646 
vfio_pci_ioctl(void * device_data,unsigned int cmd,unsigned long arg)647 static long vfio_pci_ioctl(void *device_data,
648 			   unsigned int cmd, unsigned long arg)
649 {
650 	struct vfio_pci_device *vdev = device_data;
651 	unsigned long minsz;
652 
653 	if (cmd == VFIO_DEVICE_GET_INFO) {
654 		struct vfio_device_info info;
655 
656 		minsz = offsetofend(struct vfio_device_info, num_irqs);
657 
658 		if (copy_from_user(&info, (void __user *)arg, minsz))
659 			return -EFAULT;
660 
661 		if (info.argsz < minsz)
662 			return -EINVAL;
663 
664 		info.flags = VFIO_DEVICE_FLAGS_PCI;
665 
666 		if (vdev->reset_works)
667 			info.flags |= VFIO_DEVICE_FLAGS_RESET;
668 
669 		info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions;
670 		info.num_irqs = VFIO_PCI_NUM_IRQS;
671 
672 		return copy_to_user((void __user *)arg, &info, minsz) ?
673 			-EFAULT : 0;
674 
675 	} else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
676 		struct pci_dev *pdev = vdev->pdev;
677 		struct vfio_region_info info;
678 		struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
679 		int i, ret;
680 
681 		minsz = offsetofend(struct vfio_region_info, offset);
682 
683 		if (copy_from_user(&info, (void __user *)arg, minsz))
684 			return -EFAULT;
685 
686 		if (info.argsz < minsz)
687 			return -EINVAL;
688 
689 		switch (info.index) {
690 		case VFIO_PCI_CONFIG_REGION_INDEX:
691 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
692 			info.size = pdev->cfg_size;
693 			info.flags = VFIO_REGION_INFO_FLAG_READ |
694 				     VFIO_REGION_INFO_FLAG_WRITE;
695 			break;
696 		case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
697 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
698 			info.size = pci_resource_len(pdev, info.index);
699 			if (!info.size) {
700 				info.flags = 0;
701 				break;
702 			}
703 
704 			info.flags = VFIO_REGION_INFO_FLAG_READ |
705 				     VFIO_REGION_INFO_FLAG_WRITE;
706 			if (vdev->bar_mmap_supported[info.index]) {
707 				info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
708 				if (info.index == vdev->msix_bar) {
709 					ret = msix_mmappable_cap(vdev, &caps);
710 					if (ret)
711 						return ret;
712 				}
713 			}
714 
715 			break;
716 		case VFIO_PCI_ROM_REGION_INDEX:
717 		{
718 			void __iomem *io;
719 			size_t size;
720 			u16 cmd;
721 
722 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
723 			info.flags = 0;
724 
725 			/* Report the BAR size, not the ROM size */
726 			info.size = pci_resource_len(pdev, info.index);
727 			if (!info.size) {
728 				/* Shadow ROMs appear as PCI option ROMs */
729 				if (pdev->resource[PCI_ROM_RESOURCE].flags &
730 							IORESOURCE_ROM_SHADOW)
731 					info.size = 0x20000;
732 				else
733 					break;
734 			}
735 
736 			/*
737 			 * Is it really there?  Enable memory decode for
738 			 * implicit access in pci_map_rom().
739 			 */
740 			cmd = vfio_pci_memory_lock_and_enable(vdev);
741 			io = pci_map_rom(pdev, &size);
742 			if (io) {
743 				info.flags = VFIO_REGION_INFO_FLAG_READ;
744 				pci_unmap_rom(pdev, io);
745 			} else {
746 				info.size = 0;
747 			}
748 			vfio_pci_memory_unlock_and_restore(vdev, cmd);
749 
750 			break;
751 		}
752 		case VFIO_PCI_VGA_REGION_INDEX:
753 			if (!vdev->has_vga)
754 				return -EINVAL;
755 
756 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
757 			info.size = 0xc0000;
758 			info.flags = VFIO_REGION_INFO_FLAG_READ |
759 				     VFIO_REGION_INFO_FLAG_WRITE;
760 
761 			break;
762 		default:
763 		{
764 			struct vfio_region_info_cap_type cap_type = {
765 					.header.id = VFIO_REGION_INFO_CAP_TYPE,
766 					.header.version = 1 };
767 
768 			if (info.index >=
769 			    VFIO_PCI_NUM_REGIONS + vdev->num_regions)
770 				return -EINVAL;
771 			info.index = array_index_nospec(info.index,
772 							VFIO_PCI_NUM_REGIONS +
773 							vdev->num_regions);
774 
775 			i = info.index - VFIO_PCI_NUM_REGIONS;
776 
777 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
778 			info.size = vdev->region[i].size;
779 			info.flags = vdev->region[i].flags;
780 
781 			cap_type.type = vdev->region[i].type;
782 			cap_type.subtype = vdev->region[i].subtype;
783 
784 			ret = vfio_info_add_capability(&caps, &cap_type.header,
785 						       sizeof(cap_type));
786 			if (ret)
787 				return ret;
788 
789 		}
790 		}
791 
792 		if (caps.size) {
793 			info.flags |= VFIO_REGION_INFO_FLAG_CAPS;
794 			if (info.argsz < sizeof(info) + caps.size) {
795 				info.argsz = sizeof(info) + caps.size;
796 				info.cap_offset = 0;
797 			} else {
798 				vfio_info_cap_shift(&caps, sizeof(info));
799 				if (copy_to_user((void __user *)arg +
800 						  sizeof(info), caps.buf,
801 						  caps.size)) {
802 					kfree(caps.buf);
803 					return -EFAULT;
804 				}
805 				info.cap_offset = sizeof(info);
806 			}
807 
808 			kfree(caps.buf);
809 		}
810 
811 		return copy_to_user((void __user *)arg, &info, minsz) ?
812 			-EFAULT : 0;
813 
814 	} else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
815 		struct vfio_irq_info info;
816 
817 		minsz = offsetofend(struct vfio_irq_info, count);
818 
819 		if (copy_from_user(&info, (void __user *)arg, minsz))
820 			return -EFAULT;
821 
822 		if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
823 			return -EINVAL;
824 
825 		switch (info.index) {
826 		case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
827 		case VFIO_PCI_REQ_IRQ_INDEX:
828 			break;
829 		case VFIO_PCI_ERR_IRQ_INDEX:
830 			if (pci_is_pcie(vdev->pdev))
831 				break;
832 		/* fall through */
833 		default:
834 			return -EINVAL;
835 		}
836 
837 		info.flags = VFIO_IRQ_INFO_EVENTFD;
838 
839 		info.count = vfio_pci_get_irq_count(vdev, info.index);
840 
841 		if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
842 			info.flags |= (VFIO_IRQ_INFO_MASKABLE |
843 				       VFIO_IRQ_INFO_AUTOMASKED);
844 		else
845 			info.flags |= VFIO_IRQ_INFO_NORESIZE;
846 
847 		return copy_to_user((void __user *)arg, &info, minsz) ?
848 			-EFAULT : 0;
849 
850 	} else if (cmd == VFIO_DEVICE_SET_IRQS) {
851 		struct vfio_irq_set hdr;
852 		u8 *data = NULL;
853 		int max, ret = 0;
854 		size_t data_size = 0;
855 
856 		minsz = offsetofend(struct vfio_irq_set, count);
857 
858 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
859 			return -EFAULT;
860 
861 		max = vfio_pci_get_irq_count(vdev, hdr.index);
862 
863 		ret = vfio_set_irqs_validate_and_prepare(&hdr, max,
864 						 VFIO_PCI_NUM_IRQS, &data_size);
865 		if (ret)
866 			return ret;
867 
868 		if (data_size) {
869 			data = memdup_user((void __user *)(arg + minsz),
870 					    data_size);
871 			if (IS_ERR(data))
872 				return PTR_ERR(data);
873 		}
874 
875 		mutex_lock(&vdev->igate);
876 
877 		ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
878 					      hdr.start, hdr.count, data);
879 
880 		mutex_unlock(&vdev->igate);
881 		kfree(data);
882 
883 		return ret;
884 
885 	} else if (cmd == VFIO_DEVICE_RESET) {
886 		int ret;
887 
888 		if (!vdev->reset_works)
889 			return -EINVAL;
890 
891 		vfio_pci_zap_and_down_write_memory_lock(vdev);
892 		ret = pci_try_reset_function(vdev->pdev);
893 		up_write(&vdev->memory_lock);
894 
895 		return ret;
896 
897 	} else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
898 		struct vfio_pci_hot_reset_info hdr;
899 		struct vfio_pci_fill_info fill = { 0 };
900 		struct vfio_pci_dependent_device *devices = NULL;
901 		bool slot = false;
902 		int ret = 0;
903 
904 		minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
905 
906 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
907 			return -EFAULT;
908 
909 		if (hdr.argsz < minsz)
910 			return -EINVAL;
911 
912 		hdr.flags = 0;
913 
914 		/* Can we do a slot or bus reset or neither? */
915 		if (!pci_probe_reset_slot(vdev->pdev->slot))
916 			slot = true;
917 		else if (pci_probe_reset_bus(vdev->pdev->bus))
918 			return -ENODEV;
919 
920 		/* How many devices are affected? */
921 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
922 						    vfio_pci_count_devs,
923 						    &fill.max, slot);
924 		if (ret)
925 			return ret;
926 
927 		WARN_ON(!fill.max); /* Should always be at least one */
928 
929 		/*
930 		 * If there's enough space, fill it now, otherwise return
931 		 * -ENOSPC and the number of devices affected.
932 		 */
933 		if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
934 			ret = -ENOSPC;
935 			hdr.count = fill.max;
936 			goto reset_info_exit;
937 		}
938 
939 		devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
940 		if (!devices)
941 			return -ENOMEM;
942 
943 		fill.devices = devices;
944 
945 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
946 						    vfio_pci_fill_devs,
947 						    &fill, slot);
948 
949 		/*
950 		 * If a device was removed between counting and filling,
951 		 * we may come up short of fill.max.  If a device was
952 		 * added, we'll have a return of -EAGAIN above.
953 		 */
954 		if (!ret)
955 			hdr.count = fill.cur;
956 
957 reset_info_exit:
958 		if (copy_to_user((void __user *)arg, &hdr, minsz))
959 			ret = -EFAULT;
960 
961 		if (!ret) {
962 			if (copy_to_user((void __user *)(arg + minsz), devices,
963 					 hdr.count * sizeof(*devices)))
964 				ret = -EFAULT;
965 		}
966 
967 		kfree(devices);
968 		return ret;
969 
970 	} else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
971 		struct vfio_pci_hot_reset hdr;
972 		int32_t *group_fds;
973 		struct vfio_pci_group_entry *groups;
974 		struct vfio_pci_group_info info;
975 		struct vfio_devices devs = { .cur_index = 0 };
976 		bool slot = false;
977 		int i, group_idx, mem_idx = 0, count = 0, ret = 0;
978 
979 		minsz = offsetofend(struct vfio_pci_hot_reset, count);
980 
981 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
982 			return -EFAULT;
983 
984 		if (hdr.argsz < minsz || hdr.flags)
985 			return -EINVAL;
986 
987 		/* Can we do a slot or bus reset or neither? */
988 		if (!pci_probe_reset_slot(vdev->pdev->slot))
989 			slot = true;
990 		else if (pci_probe_reset_bus(vdev->pdev->bus))
991 			return -ENODEV;
992 
993 		/*
994 		 * We can't let userspace give us an arbitrarily large
995 		 * buffer to copy, so verify how many we think there
996 		 * could be.  Note groups can have multiple devices so
997 		 * one group per device is the max.
998 		 */
999 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1000 						    vfio_pci_count_devs,
1001 						    &count, slot);
1002 		if (ret)
1003 			return ret;
1004 
1005 		/* Somewhere between 1 and count is OK */
1006 		if (!hdr.count || hdr.count > count)
1007 			return -EINVAL;
1008 
1009 		group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
1010 		groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);
1011 		if (!group_fds || !groups) {
1012 			kfree(group_fds);
1013 			kfree(groups);
1014 			return -ENOMEM;
1015 		}
1016 
1017 		if (copy_from_user(group_fds, (void __user *)(arg + minsz),
1018 				   hdr.count * sizeof(*group_fds))) {
1019 			kfree(group_fds);
1020 			kfree(groups);
1021 			return -EFAULT;
1022 		}
1023 
1024 		/*
1025 		 * For each group_fd, get the group through the vfio external
1026 		 * user interface and store the group and iommu ID.  This
1027 		 * ensures the group is held across the reset.
1028 		 */
1029 		for (group_idx = 0; group_idx < hdr.count; group_idx++) {
1030 			struct vfio_group *group;
1031 			struct fd f = fdget(group_fds[group_idx]);
1032 			if (!f.file) {
1033 				ret = -EBADF;
1034 				break;
1035 			}
1036 
1037 			group = vfio_group_get_external_user(f.file);
1038 			fdput(f);
1039 			if (IS_ERR(group)) {
1040 				ret = PTR_ERR(group);
1041 				break;
1042 			}
1043 
1044 			groups[group_idx].group = group;
1045 			groups[group_idx].id =
1046 					vfio_external_user_iommu_id(group);
1047 		}
1048 
1049 		kfree(group_fds);
1050 
1051 		/* release reference to groups on error */
1052 		if (ret)
1053 			goto hot_reset_release;
1054 
1055 		info.count = hdr.count;
1056 		info.groups = groups;
1057 
1058 		/*
1059 		 * Test whether all the affected devices are contained
1060 		 * by the set of groups provided by the user.
1061 		 */
1062 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1063 						    vfio_pci_validate_devs,
1064 						    &info, slot);
1065 		if (ret)
1066 			goto hot_reset_release;
1067 
1068 		devs.max_index = count;
1069 		devs.devices = kcalloc(count, sizeof(struct vfio_device *),
1070 				       GFP_KERNEL);
1071 		if (!devs.devices) {
1072 			ret = -ENOMEM;
1073 			goto hot_reset_release;
1074 		}
1075 
1076 		/*
1077 		 * We need to get memory_lock for each device, but devices
1078 		 * can share mmap_sem, therefore we need to zap and hold
1079 		 * the vma_lock for each device, and only then get each
1080 		 * memory_lock.
1081 		 */
1082 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1083 					    vfio_pci_try_zap_and_vma_lock_cb,
1084 					    &devs, slot);
1085 		if (ret)
1086 			goto hot_reset_release;
1087 
1088 		for (; mem_idx < devs.cur_index; mem_idx++) {
1089 			struct vfio_pci_device *tmp;
1090 
1091 			tmp = vfio_device_data(devs.devices[mem_idx]);
1092 
1093 			ret = down_write_trylock(&tmp->memory_lock);
1094 			if (!ret) {
1095 				ret = -EBUSY;
1096 				goto hot_reset_release;
1097 			}
1098 			mutex_unlock(&tmp->vma_lock);
1099 		}
1100 
1101 		/* User has access, do the reset */
1102 		ret = pci_reset_bus(vdev->pdev);
1103 
1104 hot_reset_release:
1105 		for (i = 0; i < devs.cur_index; i++) {
1106 			struct vfio_device *device;
1107 			struct vfio_pci_device *tmp;
1108 
1109 			device = devs.devices[i];
1110 			tmp = vfio_device_data(device);
1111 
1112 			if (i < mem_idx)
1113 				up_write(&tmp->memory_lock);
1114 			else
1115 				mutex_unlock(&tmp->vma_lock);
1116 			vfio_device_put(device);
1117 		}
1118 		kfree(devs.devices);
1119 
1120 		for (group_idx--; group_idx >= 0; group_idx--)
1121 			vfio_group_put_external_user(groups[group_idx].group);
1122 
1123 		kfree(groups);
1124 		return ret;
1125 	} else if (cmd == VFIO_DEVICE_IOEVENTFD) {
1126 		struct vfio_device_ioeventfd ioeventfd;
1127 		int count;
1128 
1129 		minsz = offsetofend(struct vfio_device_ioeventfd, fd);
1130 
1131 		if (copy_from_user(&ioeventfd, (void __user *)arg, minsz))
1132 			return -EFAULT;
1133 
1134 		if (ioeventfd.argsz < minsz)
1135 			return -EINVAL;
1136 
1137 		if (ioeventfd.flags & ~VFIO_DEVICE_IOEVENTFD_SIZE_MASK)
1138 			return -EINVAL;
1139 
1140 		count = ioeventfd.flags & VFIO_DEVICE_IOEVENTFD_SIZE_MASK;
1141 
1142 		if (hweight8(count) != 1 || ioeventfd.fd < -1)
1143 			return -EINVAL;
1144 
1145 		return vfio_pci_ioeventfd(vdev, ioeventfd.offset,
1146 					  ioeventfd.data, count, ioeventfd.fd);
1147 	}
1148 
1149 	return -ENOTTY;
1150 }
1151 
vfio_pci_rw(void * device_data,char __user * buf,size_t count,loff_t * ppos,bool iswrite)1152 static ssize_t vfio_pci_rw(void *device_data, char __user *buf,
1153 			   size_t count, loff_t *ppos, bool iswrite)
1154 {
1155 	unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
1156 	struct vfio_pci_device *vdev = device_data;
1157 
1158 	if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1159 		return -EINVAL;
1160 
1161 	switch (index) {
1162 	case VFIO_PCI_CONFIG_REGION_INDEX:
1163 		return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
1164 
1165 	case VFIO_PCI_ROM_REGION_INDEX:
1166 		if (iswrite)
1167 			return -EINVAL;
1168 		return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
1169 
1170 	case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
1171 		return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
1172 
1173 	case VFIO_PCI_VGA_REGION_INDEX:
1174 		return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
1175 	default:
1176 		index -= VFIO_PCI_NUM_REGIONS;
1177 		return vdev->region[index].ops->rw(vdev, buf,
1178 						   count, ppos, iswrite);
1179 	}
1180 
1181 	return -EINVAL;
1182 }
1183 
vfio_pci_read(void * device_data,char __user * buf,size_t count,loff_t * ppos)1184 static ssize_t vfio_pci_read(void *device_data, char __user *buf,
1185 			     size_t count, loff_t *ppos)
1186 {
1187 	if (!count)
1188 		return 0;
1189 
1190 	return vfio_pci_rw(device_data, buf, count, ppos, false);
1191 }
1192 
vfio_pci_write(void * device_data,const char __user * buf,size_t count,loff_t * ppos)1193 static ssize_t vfio_pci_write(void *device_data, const char __user *buf,
1194 			      size_t count, loff_t *ppos)
1195 {
1196 	if (!count)
1197 		return 0;
1198 
1199 	return vfio_pci_rw(device_data, (char __user *)buf, count, ppos, true);
1200 }
1201 
1202 /* Return 1 on zap and vma_lock acquired, 0 on contention (only with @try) */
vfio_pci_zap_and_vma_lock(struct vfio_pci_device * vdev,bool try)1203 static int vfio_pci_zap_and_vma_lock(struct vfio_pci_device *vdev, bool try)
1204 {
1205 	struct vfio_pci_mmap_vma *mmap_vma, *tmp;
1206 
1207 	/*
1208 	 * Lock ordering:
1209 	 * vma_lock is nested under mmap_sem for vm_ops callback paths.
1210 	 * The memory_lock semaphore is used by both code paths calling
1211 	 * into this function to zap vmas and the vm_ops.fault callback
1212 	 * to protect the memory enable state of the device.
1213 	 *
1214 	 * When zapping vmas we need to maintain the mmap_sem => vma_lock
1215 	 * ordering, which requires using vma_lock to walk vma_list to
1216 	 * acquire an mm, then dropping vma_lock to get the mmap_sem and
1217 	 * reacquiring vma_lock.  This logic is derived from similar
1218 	 * requirements in uverbs_user_mmap_disassociate().
1219 	 *
1220 	 * mmap_sem must always be the top-level lock when it is taken.
1221 	 * Therefore we can only hold the memory_lock write lock when
1222 	 * vma_list is empty, as we'd need to take mmap_sem to clear
1223 	 * entries.  vma_list can only be guaranteed empty when holding
1224 	 * vma_lock, thus memory_lock is nested under vma_lock.
1225 	 *
1226 	 * This enables the vm_ops.fault callback to acquire vma_lock,
1227 	 * followed by memory_lock read lock, while already holding
1228 	 * mmap_sem without risk of deadlock.
1229 	 */
1230 	while (1) {
1231 		struct mm_struct *mm = NULL;
1232 
1233 		if (try) {
1234 			if (!mutex_trylock(&vdev->vma_lock))
1235 				return 0;
1236 		} else {
1237 			mutex_lock(&vdev->vma_lock);
1238 		}
1239 		while (!list_empty(&vdev->vma_list)) {
1240 			mmap_vma = list_first_entry(&vdev->vma_list,
1241 						    struct vfio_pci_mmap_vma,
1242 						    vma_next);
1243 			mm = mmap_vma->vma->vm_mm;
1244 			if (mmget_not_zero(mm))
1245 				break;
1246 
1247 			list_del(&mmap_vma->vma_next);
1248 			kfree(mmap_vma);
1249 			mm = NULL;
1250 		}
1251 		if (!mm)
1252 			return 1;
1253 		mutex_unlock(&vdev->vma_lock);
1254 
1255 		if (try) {
1256 			if (!down_read_trylock(&mm->mmap_sem)) {
1257 				mmput(mm);
1258 				return 0;
1259 			}
1260 		} else {
1261 			down_read(&mm->mmap_sem);
1262 		}
1263 		if (mmget_still_valid(mm)) {
1264 			if (try) {
1265 				if (!mutex_trylock(&vdev->vma_lock)) {
1266 					up_read(&mm->mmap_sem);
1267 					mmput(mm);
1268 					return 0;
1269 				}
1270 			} else {
1271 				mutex_lock(&vdev->vma_lock);
1272 			}
1273 			list_for_each_entry_safe(mmap_vma, tmp,
1274 						 &vdev->vma_list, vma_next) {
1275 				struct vm_area_struct *vma = mmap_vma->vma;
1276 
1277 				if (vma->vm_mm != mm)
1278 					continue;
1279 
1280 				list_del(&mmap_vma->vma_next);
1281 				kfree(mmap_vma);
1282 
1283 				zap_vma_ptes(vma, vma->vm_start,
1284 					     vma->vm_end - vma->vm_start);
1285 			}
1286 			mutex_unlock(&vdev->vma_lock);
1287 		}
1288 		up_read(&mm->mmap_sem);
1289 		mmput(mm);
1290 	}
1291 }
1292 
vfio_pci_zap_and_down_write_memory_lock(struct vfio_pci_device * vdev)1293 void vfio_pci_zap_and_down_write_memory_lock(struct vfio_pci_device *vdev)
1294 {
1295 	vfio_pci_zap_and_vma_lock(vdev, false);
1296 	down_write(&vdev->memory_lock);
1297 	mutex_unlock(&vdev->vma_lock);
1298 }
1299 
vfio_pci_memory_lock_and_enable(struct vfio_pci_device * vdev)1300 u16 vfio_pci_memory_lock_and_enable(struct vfio_pci_device *vdev)
1301 {
1302 	u16 cmd;
1303 
1304 	down_write(&vdev->memory_lock);
1305 	pci_read_config_word(vdev->pdev, PCI_COMMAND, &cmd);
1306 	if (!(cmd & PCI_COMMAND_MEMORY))
1307 		pci_write_config_word(vdev->pdev, PCI_COMMAND,
1308 				      cmd | PCI_COMMAND_MEMORY);
1309 
1310 	return cmd;
1311 }
1312 
vfio_pci_memory_unlock_and_restore(struct vfio_pci_device * vdev,u16 cmd)1313 void vfio_pci_memory_unlock_and_restore(struct vfio_pci_device *vdev, u16 cmd)
1314 {
1315 	pci_write_config_word(vdev->pdev, PCI_COMMAND, cmd);
1316 	up_write(&vdev->memory_lock);
1317 }
1318 
1319 /* Caller holds vma_lock */
__vfio_pci_add_vma(struct vfio_pci_device * vdev,struct vm_area_struct * vma)1320 static int __vfio_pci_add_vma(struct vfio_pci_device *vdev,
1321 			      struct vm_area_struct *vma)
1322 {
1323 	struct vfio_pci_mmap_vma *mmap_vma;
1324 
1325 	mmap_vma = kmalloc(sizeof(*mmap_vma), GFP_KERNEL);
1326 	if (!mmap_vma)
1327 		return -ENOMEM;
1328 
1329 	mmap_vma->vma = vma;
1330 	list_add(&mmap_vma->vma_next, &vdev->vma_list);
1331 
1332 	return 0;
1333 }
1334 
1335 /*
1336  * Zap mmaps on open so that we can fault them in on access and therefore
1337  * our vma_list only tracks mappings accessed since last zap.
1338  */
vfio_pci_mmap_open(struct vm_area_struct * vma)1339 static void vfio_pci_mmap_open(struct vm_area_struct *vma)
1340 {
1341 	zap_vma_ptes(vma, vma->vm_start, vma->vm_end - vma->vm_start);
1342 }
1343 
vfio_pci_mmap_close(struct vm_area_struct * vma)1344 static void vfio_pci_mmap_close(struct vm_area_struct *vma)
1345 {
1346 	struct vfio_pci_device *vdev = vma->vm_private_data;
1347 	struct vfio_pci_mmap_vma *mmap_vma;
1348 
1349 	mutex_lock(&vdev->vma_lock);
1350 	list_for_each_entry(mmap_vma, &vdev->vma_list, vma_next) {
1351 		if (mmap_vma->vma == vma) {
1352 			list_del(&mmap_vma->vma_next);
1353 			kfree(mmap_vma);
1354 			break;
1355 		}
1356 	}
1357 	mutex_unlock(&vdev->vma_lock);
1358 }
1359 
vfio_pci_mmap_fault(struct vm_fault * vmf)1360 static vm_fault_t vfio_pci_mmap_fault(struct vm_fault *vmf)
1361 {
1362 	struct vm_area_struct *vma = vmf->vma;
1363 	struct vfio_pci_device *vdev = vma->vm_private_data;
1364 	vm_fault_t ret = VM_FAULT_NOPAGE;
1365 
1366 	mutex_lock(&vdev->vma_lock);
1367 	down_read(&vdev->memory_lock);
1368 
1369 	if (!__vfio_pci_memory_enabled(vdev)) {
1370 		ret = VM_FAULT_SIGBUS;
1371 		mutex_unlock(&vdev->vma_lock);
1372 		goto up_out;
1373 	}
1374 
1375 	if (__vfio_pci_add_vma(vdev, vma)) {
1376 		ret = VM_FAULT_OOM;
1377 		mutex_unlock(&vdev->vma_lock);
1378 		goto up_out;
1379 	}
1380 
1381 	mutex_unlock(&vdev->vma_lock);
1382 
1383 	if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
1384 			    vma->vm_end - vma->vm_start, vma->vm_page_prot))
1385 		ret = VM_FAULT_SIGBUS;
1386 
1387 up_out:
1388 	up_read(&vdev->memory_lock);
1389 	return ret;
1390 }
1391 
1392 static const struct vm_operations_struct vfio_pci_mmap_ops = {
1393 	.open = vfio_pci_mmap_open,
1394 	.close = vfio_pci_mmap_close,
1395 	.fault = vfio_pci_mmap_fault,
1396 };
1397 
vfio_pci_mmap(void * device_data,struct vm_area_struct * vma)1398 static int vfio_pci_mmap(void *device_data, struct vm_area_struct *vma)
1399 {
1400 	struct vfio_pci_device *vdev = device_data;
1401 	struct pci_dev *pdev = vdev->pdev;
1402 	unsigned int index;
1403 	u64 phys_len, req_len, pgoff, req_start;
1404 	int ret;
1405 
1406 	index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1407 
1408 	if (vma->vm_end < vma->vm_start)
1409 		return -EINVAL;
1410 	if ((vma->vm_flags & VM_SHARED) == 0)
1411 		return -EINVAL;
1412 	if (index >= VFIO_PCI_ROM_REGION_INDEX)
1413 		return -EINVAL;
1414 	if (!vdev->bar_mmap_supported[index])
1415 		return -EINVAL;
1416 
1417 	phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1418 	req_len = vma->vm_end - vma->vm_start;
1419 	pgoff = vma->vm_pgoff &
1420 		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1421 	req_start = pgoff << PAGE_SHIFT;
1422 
1423 	if (req_start + req_len > phys_len)
1424 		return -EINVAL;
1425 
1426 	/*
1427 	 * Even though we don't make use of the barmap for the mmap,
1428 	 * we need to request the region and the barmap tracks that.
1429 	 */
1430 	if (!vdev->barmap[index]) {
1431 		ret = pci_request_selected_regions(pdev,
1432 						   1 << index, "vfio-pci");
1433 		if (ret)
1434 			return ret;
1435 
1436 		vdev->barmap[index] = pci_iomap(pdev, index, 0);
1437 		if (!vdev->barmap[index]) {
1438 			pci_release_selected_regions(pdev, 1 << index);
1439 			return -ENOMEM;
1440 		}
1441 	}
1442 
1443 	vma->vm_private_data = vdev;
1444 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1445 	vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
1446 
1447 	/*
1448 	 * See remap_pfn_range(), called from vfio_pci_fault() but we can't
1449 	 * change vm_flags within the fault handler.  Set them now.
1450 	 */
1451 	vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
1452 	vma->vm_ops = &vfio_pci_mmap_ops;
1453 
1454 	return 0;
1455 }
1456 
vfio_pci_request(void * device_data,unsigned int count)1457 static void vfio_pci_request(void *device_data, unsigned int count)
1458 {
1459 	struct vfio_pci_device *vdev = device_data;
1460 
1461 	mutex_lock(&vdev->igate);
1462 
1463 	if (vdev->req_trigger) {
1464 		if (!(count % 10))
1465 			dev_notice_ratelimited(&vdev->pdev->dev,
1466 				"Relaying device request to user (#%u)\n",
1467 				count);
1468 		eventfd_signal(vdev->req_trigger, 1);
1469 	} else if (count == 0) {
1470 		dev_warn(&vdev->pdev->dev,
1471 			"No device request channel registered, blocked until released by user\n");
1472 	}
1473 
1474 	mutex_unlock(&vdev->igate);
1475 }
1476 
1477 static const struct vfio_device_ops vfio_pci_ops = {
1478 	.name		= "vfio-pci",
1479 	.open		= vfio_pci_open,
1480 	.release	= vfio_pci_release,
1481 	.ioctl		= vfio_pci_ioctl,
1482 	.read		= vfio_pci_read,
1483 	.write		= vfio_pci_write,
1484 	.mmap		= vfio_pci_mmap,
1485 	.request	= vfio_pci_request,
1486 };
1487 
vfio_pci_probe(struct pci_dev * pdev,const struct pci_device_id * id)1488 static int vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1489 {
1490 	struct vfio_pci_device *vdev;
1491 	struct iommu_group *group;
1492 	int ret;
1493 
1494 	if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
1495 		return -EINVAL;
1496 
1497 	/*
1498 	 * Prevent binding to PFs with VFs enabled, this too easily allows
1499 	 * userspace instance with VFs and PFs from the same device, which
1500 	 * cannot work.  Disabling SR-IOV here would initiate removing the
1501 	 * VFs, which would unbind the driver, which is prone to blocking
1502 	 * if that VF is also in use by vfio-pci.  Just reject these PFs
1503 	 * and let the user sort it out.
1504 	 */
1505 	if (pci_num_vf(pdev)) {
1506 		pci_warn(pdev, "Cannot bind to PF with SR-IOV enabled\n");
1507 		return -EBUSY;
1508 	}
1509 
1510 	group = vfio_iommu_group_get(&pdev->dev);
1511 	if (!group)
1512 		return -EINVAL;
1513 
1514 	vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
1515 	if (!vdev) {
1516 		vfio_iommu_group_put(group, &pdev->dev);
1517 		return -ENOMEM;
1518 	}
1519 
1520 	vdev->pdev = pdev;
1521 	vdev->irq_type = VFIO_PCI_NUM_IRQS;
1522 	mutex_init(&vdev->igate);
1523 	spin_lock_init(&vdev->irqlock);
1524 	mutex_init(&vdev->ioeventfds_lock);
1525 	INIT_LIST_HEAD(&vdev->ioeventfds_list);
1526 	mutex_init(&vdev->vma_lock);
1527 	INIT_LIST_HEAD(&vdev->vma_list);
1528 	init_rwsem(&vdev->memory_lock);
1529 
1530 	ret = vfio_add_group_dev(&pdev->dev, &vfio_pci_ops, vdev);
1531 	if (ret) {
1532 		vfio_iommu_group_put(group, &pdev->dev);
1533 		kfree(vdev);
1534 		return ret;
1535 	}
1536 
1537 	if (vfio_pci_is_vga(pdev)) {
1538 		vga_client_register(pdev, vdev, NULL, vfio_pci_set_vga_decode);
1539 		vga_set_legacy_decoding(pdev,
1540 					vfio_pci_set_vga_decode(vdev, false));
1541 	}
1542 
1543 	if (!disable_idle_d3) {
1544 		/*
1545 		 * pci-core sets the device power state to an unknown value at
1546 		 * bootup and after being removed from a driver.  The only
1547 		 * transition it allows from this unknown state is to D0, which
1548 		 * typically happens when a driver calls pci_enable_device().
1549 		 * We're not ready to enable the device yet, but we do want to
1550 		 * be able to get to D3.  Therefore first do a D0 transition
1551 		 * before going to D3.
1552 		 */
1553 		pci_set_power_state(pdev, PCI_D0);
1554 		pci_set_power_state(pdev, PCI_D3hot);
1555 	}
1556 
1557 	return ret;
1558 }
1559 
vfio_pci_remove(struct pci_dev * pdev)1560 static void vfio_pci_remove(struct pci_dev *pdev)
1561 {
1562 	struct vfio_pci_device *vdev;
1563 
1564 	vdev = vfio_del_group_dev(&pdev->dev);
1565 	if (!vdev)
1566 		return;
1567 
1568 	vfio_iommu_group_put(pdev->dev.iommu_group, &pdev->dev);
1569 	kfree(vdev->region);
1570 	mutex_destroy(&vdev->ioeventfds_lock);
1571 	kfree(vdev);
1572 
1573 	if (vfio_pci_is_vga(pdev)) {
1574 		vga_client_register(pdev, NULL, NULL, NULL);
1575 		vga_set_legacy_decoding(pdev,
1576 				VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
1577 				VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM);
1578 	}
1579 
1580 	if (!disable_idle_d3)
1581 		pci_set_power_state(pdev, PCI_D0);
1582 }
1583 
vfio_pci_aer_err_detected(struct pci_dev * pdev,pci_channel_state_t state)1584 static pci_ers_result_t vfio_pci_aer_err_detected(struct pci_dev *pdev,
1585 						  pci_channel_state_t state)
1586 {
1587 	struct vfio_pci_device *vdev;
1588 	struct vfio_device *device;
1589 
1590 	device = vfio_device_get_from_dev(&pdev->dev);
1591 	if (device == NULL)
1592 		return PCI_ERS_RESULT_DISCONNECT;
1593 
1594 	vdev = vfio_device_data(device);
1595 	if (vdev == NULL) {
1596 		vfio_device_put(device);
1597 		return PCI_ERS_RESULT_DISCONNECT;
1598 	}
1599 
1600 	mutex_lock(&vdev->igate);
1601 
1602 	if (vdev->err_trigger)
1603 		eventfd_signal(vdev->err_trigger, 1);
1604 
1605 	mutex_unlock(&vdev->igate);
1606 
1607 	vfio_device_put(device);
1608 
1609 	return PCI_ERS_RESULT_CAN_RECOVER;
1610 }
1611 
1612 static const struct pci_error_handlers vfio_err_handlers = {
1613 	.error_detected = vfio_pci_aer_err_detected,
1614 };
1615 
1616 static struct pci_driver vfio_pci_driver = {
1617 	.name		= "vfio-pci",
1618 	.id_table	= NULL, /* only dynamic ids */
1619 	.probe		= vfio_pci_probe,
1620 	.remove		= vfio_pci_remove,
1621 	.err_handler	= &vfio_err_handlers,
1622 };
1623 
vfio_pci_get_devs(struct pci_dev * pdev,void * data)1624 static int vfio_pci_get_devs(struct pci_dev *pdev, void *data)
1625 {
1626 	struct vfio_devices *devs = data;
1627 	struct vfio_device *device;
1628 
1629 	if (devs->cur_index == devs->max_index)
1630 		return -ENOSPC;
1631 
1632 	device = vfio_device_get_from_dev(&pdev->dev);
1633 	if (!device)
1634 		return -EINVAL;
1635 
1636 	if (pci_dev_driver(pdev) != &vfio_pci_driver) {
1637 		vfio_device_put(device);
1638 		return -EBUSY;
1639 	}
1640 
1641 	devs->devices[devs->cur_index++] = device;
1642 	return 0;
1643 }
1644 
vfio_pci_try_zap_and_vma_lock_cb(struct pci_dev * pdev,void * data)1645 static int vfio_pci_try_zap_and_vma_lock_cb(struct pci_dev *pdev, void *data)
1646 {
1647 	struct vfio_devices *devs = data;
1648 	struct vfio_device *device;
1649 	struct vfio_pci_device *vdev;
1650 
1651 	if (devs->cur_index == devs->max_index)
1652 		return -ENOSPC;
1653 
1654 	device = vfio_device_get_from_dev(&pdev->dev);
1655 	if (!device)
1656 		return -EINVAL;
1657 
1658 	if (pci_dev_driver(pdev) != &vfio_pci_driver) {
1659 		vfio_device_put(device);
1660 		return -EBUSY;
1661 	}
1662 
1663 	vdev = vfio_device_data(device);
1664 
1665 	/*
1666 	 * Locking multiple devices is prone to deadlock, runaway and
1667 	 * unwind if we hit contention.
1668 	 */
1669 	if (!vfio_pci_zap_and_vma_lock(vdev, true)) {
1670 		vfio_device_put(device);
1671 		return -EBUSY;
1672 	}
1673 
1674 	devs->devices[devs->cur_index++] = device;
1675 	return 0;
1676 }
1677 
1678 /*
1679  * Attempt to do a bus/slot reset if there are devices affected by a reset for
1680  * this device that are needs_reset and all of the affected devices are unused
1681  * (!refcnt).  Callers are required to hold driver_lock when calling this to
1682  * prevent device opens and concurrent bus reset attempts.  We prevent device
1683  * unbinds by acquiring and holding a reference to the vfio_device.
1684  *
1685  * NB: vfio-core considers a group to be viable even if some devices are
1686  * bound to drivers like pci-stub or pcieport.  Here we require all devices
1687  * to be bound to vfio_pci since that's the only way we can be sure they
1688  * stay put.
1689  */
vfio_pci_try_bus_reset(struct vfio_pci_device * vdev)1690 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev)
1691 {
1692 	struct vfio_devices devs = { .cur_index = 0 };
1693 	int i = 0, ret = -EINVAL;
1694 	bool needs_reset = false, slot = false;
1695 	struct vfio_pci_device *tmp;
1696 
1697 	if (!pci_probe_reset_slot(vdev->pdev->slot))
1698 		slot = true;
1699 	else if (pci_probe_reset_bus(vdev->pdev->bus))
1700 		return;
1701 
1702 	if (vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
1703 					  &i, slot) || !i)
1704 		return;
1705 
1706 	devs.max_index = i;
1707 	devs.devices = kcalloc(i, sizeof(struct vfio_device *), GFP_KERNEL);
1708 	if (!devs.devices)
1709 		return;
1710 
1711 	if (vfio_pci_for_each_slot_or_bus(vdev->pdev,
1712 					  vfio_pci_get_devs, &devs, slot))
1713 		goto put_devs;
1714 
1715 	for (i = 0; i < devs.cur_index; i++) {
1716 		tmp = vfio_device_data(devs.devices[i]);
1717 		if (tmp->needs_reset)
1718 			needs_reset = true;
1719 		if (tmp->refcnt)
1720 			goto put_devs;
1721 	}
1722 
1723 	if (needs_reset)
1724 		ret = pci_reset_bus(vdev->pdev);
1725 
1726 put_devs:
1727 	for (i = 0; i < devs.cur_index; i++) {
1728 		tmp = vfio_device_data(devs.devices[i]);
1729 		if (!ret)
1730 			tmp->needs_reset = false;
1731 
1732 		if (!tmp->refcnt && !disable_idle_d3)
1733 			pci_set_power_state(tmp->pdev, PCI_D3hot);
1734 
1735 		vfio_device_put(devs.devices[i]);
1736 	}
1737 
1738 	kfree(devs.devices);
1739 }
1740 
vfio_pci_cleanup(void)1741 static void __exit vfio_pci_cleanup(void)
1742 {
1743 	pci_unregister_driver(&vfio_pci_driver);
1744 	vfio_pci_uninit_perm_bits();
1745 }
1746 
vfio_pci_fill_ids(void)1747 static void __init vfio_pci_fill_ids(void)
1748 {
1749 	char *p, *id;
1750 	int rc;
1751 
1752 	/* no ids passed actually */
1753 	if (ids[0] == '\0')
1754 		return;
1755 
1756 	/* add ids specified in the module parameter */
1757 	p = ids;
1758 	while ((id = strsep(&p, ","))) {
1759 		unsigned int vendor, device, subvendor = PCI_ANY_ID,
1760 			subdevice = PCI_ANY_ID, class = 0, class_mask = 0;
1761 		int fields;
1762 
1763 		if (!strlen(id))
1764 			continue;
1765 
1766 		fields = sscanf(id, "%x:%x:%x:%x:%x:%x",
1767 				&vendor, &device, &subvendor, &subdevice,
1768 				&class, &class_mask);
1769 
1770 		if (fields < 2) {
1771 			pr_warn("invalid id string \"%s\"\n", id);
1772 			continue;
1773 		}
1774 
1775 		rc = pci_add_dynid(&vfio_pci_driver, vendor, device,
1776 				   subvendor, subdevice, class, class_mask, 0);
1777 		if (rc)
1778 			pr_warn("failed to add dynamic id [%04x:%04x[%04x:%04x]] class %#08x/%08x (%d)\n",
1779 				vendor, device, subvendor, subdevice,
1780 				class, class_mask, rc);
1781 		else
1782 			pr_info("add [%04x:%04x[%04x:%04x]] class %#08x/%08x\n",
1783 				vendor, device, subvendor, subdevice,
1784 				class, class_mask);
1785 	}
1786 }
1787 
vfio_pci_init(void)1788 static int __init vfio_pci_init(void)
1789 {
1790 	int ret;
1791 
1792 	/* Allocate shared config space permision data used by all devices */
1793 	ret = vfio_pci_init_perm_bits();
1794 	if (ret)
1795 		return ret;
1796 
1797 	/* Register and scan for devices */
1798 	ret = pci_register_driver(&vfio_pci_driver);
1799 	if (ret)
1800 		goto out_driver;
1801 
1802 	vfio_pci_fill_ids();
1803 
1804 	return 0;
1805 
1806 out_driver:
1807 	vfio_pci_uninit_perm_bits();
1808 	return ret;
1809 }
1810 
1811 module_init(vfio_pci_init);
1812 module_exit(vfio_pci_cleanup);
1813 
1814 MODULE_VERSION(DRIVER_VERSION);
1815 MODULE_LICENSE("GPL v2");
1816 MODULE_AUTHOR(DRIVER_AUTHOR);
1817 MODULE_DESCRIPTION(DRIVER_DESC);
1818