• 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 #include <linux/device.h>
15 #include <linux/eventfd.h>
16 #include <linux/file.h>
17 #include <linux/interrupt.h>
18 #include <linux/iommu.h>
19 #include <linux/module.h>
20 #include <linux/mutex.h>
21 #include <linux/notifier.h>
22 #include <linux/pci.h>
23 #include <linux/pm_runtime.h>
24 #include <linux/slab.h>
25 #include <linux/types.h>
26 #include <linux/uaccess.h>
27 #include <linux/vfio.h>
28 
29 #include "vfio_pci_private.h"
30 
31 #define DRIVER_VERSION  "0.2"
32 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
33 #define DRIVER_DESC     "VFIO PCI - User Level meta-driver"
34 
35 static bool nointxmask;
36 module_param_named(nointxmask, nointxmask, bool, S_IRUGO | S_IWUSR);
37 MODULE_PARM_DESC(nointxmask,
38 		  "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.");
39 
40 static DEFINE_MUTEX(driver_lock);
41 
42 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev);
43 
vfio_pci_enable(struct vfio_pci_device * vdev)44 static int vfio_pci_enable(struct vfio_pci_device *vdev)
45 {
46 	struct pci_dev *pdev = vdev->pdev;
47 	int ret;
48 	u16 cmd;
49 	u8 msix_pos;
50 
51 	/* Don't allow our initial saved state to include busmaster */
52 	pci_clear_master(pdev);
53 
54 	ret = pci_enable_device(pdev);
55 	if (ret)
56 		return ret;
57 
58 	vdev->reset_works = (pci_reset_function(pdev) == 0);
59 	pci_save_state(pdev);
60 	vdev->pci_saved_state = pci_store_saved_state(pdev);
61 	if (!vdev->pci_saved_state)
62 		pr_debug("%s: Couldn't store %s saved state\n",
63 			 __func__, dev_name(&pdev->dev));
64 
65 	ret = vfio_config_init(vdev);
66 	if (ret) {
67 		kfree(vdev->pci_saved_state);
68 		vdev->pci_saved_state = NULL;
69 		pci_disable_device(pdev);
70 		return ret;
71 	}
72 
73 	if (likely(!nointxmask))
74 		vdev->pci_2_3 = pci_intx_mask_supported(pdev);
75 
76 	pci_read_config_word(pdev, PCI_COMMAND, &cmd);
77 	if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
78 		cmd &= ~PCI_COMMAND_INTX_DISABLE;
79 		pci_write_config_word(pdev, PCI_COMMAND, cmd);
80 	}
81 
82 	msix_pos = pdev->msix_cap;
83 	if (msix_pos) {
84 		u16 flags;
85 		u32 table;
86 
87 		pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
88 		pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
89 
90 		vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
91 		vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
92 		vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
93 	} else
94 		vdev->msix_bar = 0xFF;
95 
96 #ifdef CONFIG_VFIO_PCI_VGA
97 	if ((pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA)
98 		vdev->has_vga = true;
99 #endif
100 
101 	return 0;
102 }
103 
vfio_pci_disable(struct vfio_pci_device * vdev)104 static void vfio_pci_disable(struct vfio_pci_device *vdev)
105 {
106 	struct pci_dev *pdev = vdev->pdev;
107 	int bar;
108 
109 	/* Stop the device from further DMA */
110 	pci_clear_master(pdev);
111 
112 	vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
113 				VFIO_IRQ_SET_ACTION_TRIGGER,
114 				vdev->irq_type, 0, 0, NULL);
115 
116 	vdev->virq_disabled = false;
117 
118 	vfio_config_free(vdev);
119 
120 	for (bar = PCI_STD_RESOURCES; bar <= PCI_STD_RESOURCE_END; bar++) {
121 		if (!vdev->barmap[bar])
122 			continue;
123 		pci_iounmap(pdev, vdev->barmap[bar]);
124 		pci_release_selected_regions(pdev, 1 << bar);
125 		vdev->barmap[bar] = NULL;
126 	}
127 
128 	vdev->needs_reset = true;
129 
130 	/*
131 	 * If we have saved state, restore it.  If we can reset the device,
132 	 * even better.  Resetting with current state seems better than
133 	 * nothing, but saving and restoring current state without reset
134 	 * is just busy work.
135 	 */
136 	if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
137 		pr_info("%s: Couldn't reload %s saved state\n",
138 			__func__, dev_name(&pdev->dev));
139 
140 		if (!vdev->reset_works)
141 			goto out;
142 
143 		pci_save_state(pdev);
144 	}
145 
146 	/*
147 	 * Disable INTx and MSI, presumably to avoid spurious interrupts
148 	 * during reset.  Stolen from pci_reset_function()
149 	 */
150 	pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
151 
152 	/*
153 	 * Try to reset the device.  The success of this is dependent on
154 	 * being able to lock the device, which is not always possible.
155 	 */
156 	if (vdev->reset_works) {
157 		int ret = pci_try_reset_function(pdev);
158 		if (ret)
159 			pr_warn("%s: Failed to reset device %s (%d)\n",
160 				__func__, dev_name(&pdev->dev), ret);
161 		else
162 			vdev->needs_reset = false;
163 	}
164 
165 	pci_restore_state(pdev);
166 out:
167 	pci_disable_device(pdev);
168 
169 	vfio_pci_try_bus_reset(vdev);
170 }
171 
vfio_pci_release(void * device_data)172 static void vfio_pci_release(void *device_data)
173 {
174 	struct vfio_pci_device *vdev = device_data;
175 
176 	mutex_lock(&driver_lock);
177 
178 	if (!(--vdev->refcnt)) {
179 		vfio_spapr_pci_eeh_release(vdev->pdev);
180 		vfio_pci_disable(vdev);
181 	}
182 
183 	mutex_unlock(&driver_lock);
184 
185 	module_put(THIS_MODULE);
186 }
187 
vfio_pci_open(void * device_data)188 static int vfio_pci_open(void *device_data)
189 {
190 	struct vfio_pci_device *vdev = device_data;
191 	int ret = 0;
192 
193 	if (!try_module_get(THIS_MODULE))
194 		return -ENODEV;
195 
196 	mutex_lock(&driver_lock);
197 
198 	if (!vdev->refcnt) {
199 		ret = vfio_pci_enable(vdev);
200 		if (ret)
201 			goto error;
202 
203 		vfio_spapr_pci_eeh_open(vdev->pdev);
204 	}
205 	vdev->refcnt++;
206 error:
207 	mutex_unlock(&driver_lock);
208 	if (ret)
209 		module_put(THIS_MODULE);
210 	return ret;
211 }
212 
vfio_pci_get_irq_count(struct vfio_pci_device * vdev,int irq_type)213 static int vfio_pci_get_irq_count(struct vfio_pci_device *vdev, int irq_type)
214 {
215 	if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
216 		u8 pin;
217 		pci_read_config_byte(vdev->pdev, PCI_INTERRUPT_PIN, &pin);
218 		if (pin)
219 			return 1;
220 
221 	} else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
222 		u8 pos;
223 		u16 flags;
224 
225 		pos = vdev->pdev->msi_cap;
226 		if (pos) {
227 			pci_read_config_word(vdev->pdev,
228 					     pos + PCI_MSI_FLAGS, &flags);
229 			return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
230 		}
231 	} else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
232 		u8 pos;
233 		u16 flags;
234 
235 		pos = vdev->pdev->msix_cap;
236 		if (pos) {
237 			pci_read_config_word(vdev->pdev,
238 					     pos + PCI_MSIX_FLAGS, &flags);
239 
240 			return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
241 		}
242 	} else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX)
243 		if (pci_is_pcie(vdev->pdev))
244 			return 1;
245 
246 	return 0;
247 }
248 
vfio_pci_count_devs(struct pci_dev * pdev,void * data)249 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
250 {
251 	(*(int *)data)++;
252 	return 0;
253 }
254 
255 struct vfio_pci_fill_info {
256 	int max;
257 	int cur;
258 	struct vfio_pci_dependent_device *devices;
259 };
260 
vfio_pci_fill_devs(struct pci_dev * pdev,void * data)261 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
262 {
263 	struct vfio_pci_fill_info *fill = data;
264 	struct iommu_group *iommu_group;
265 
266 	if (fill->cur == fill->max)
267 		return -EAGAIN; /* Something changed, try again */
268 
269 	iommu_group = iommu_group_get(&pdev->dev);
270 	if (!iommu_group)
271 		return -EPERM; /* Cannot reset non-isolated devices */
272 
273 	fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
274 	fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
275 	fill->devices[fill->cur].bus = pdev->bus->number;
276 	fill->devices[fill->cur].devfn = pdev->devfn;
277 	fill->cur++;
278 	iommu_group_put(iommu_group);
279 	return 0;
280 }
281 
282 struct vfio_pci_group_entry {
283 	struct vfio_group *group;
284 	int id;
285 };
286 
287 struct vfio_pci_group_info {
288 	int count;
289 	struct vfio_pci_group_entry *groups;
290 };
291 
vfio_pci_validate_devs(struct pci_dev * pdev,void * data)292 static int vfio_pci_validate_devs(struct pci_dev *pdev, void *data)
293 {
294 	struct vfio_pci_group_info *info = data;
295 	struct iommu_group *group;
296 	int id, i;
297 
298 	group = iommu_group_get(&pdev->dev);
299 	if (!group)
300 		return -EPERM;
301 
302 	id = iommu_group_id(group);
303 
304 	for (i = 0; i < info->count; i++)
305 		if (info->groups[i].id == id)
306 			break;
307 
308 	iommu_group_put(group);
309 
310 	return (i == info->count) ? -EINVAL : 0;
311 }
312 
vfio_pci_dev_below_slot(struct pci_dev * pdev,struct pci_slot * slot)313 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
314 {
315 	for (; pdev; pdev = pdev->bus->self)
316 		if (pdev->bus == slot->bus)
317 			return (pdev->slot == slot);
318 	return false;
319 }
320 
321 struct vfio_pci_walk_info {
322 	int (*fn)(struct pci_dev *, void *data);
323 	void *data;
324 	struct pci_dev *pdev;
325 	bool slot;
326 	int ret;
327 };
328 
vfio_pci_walk_wrapper(struct pci_dev * pdev,void * data)329 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
330 {
331 	struct vfio_pci_walk_info *walk = data;
332 
333 	if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
334 		walk->ret = walk->fn(pdev, walk->data);
335 
336 	return walk->ret;
337 }
338 
vfio_pci_for_each_slot_or_bus(struct pci_dev * pdev,int (* fn)(struct pci_dev *,void * data),void * data,bool slot)339 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
340 					 int (*fn)(struct pci_dev *,
341 						   void *data), void *data,
342 					 bool slot)
343 {
344 	struct vfio_pci_walk_info walk = {
345 		.fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
346 	};
347 
348 	pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
349 
350 	return walk.ret;
351 }
352 
vfio_pci_ioctl(void * device_data,unsigned int cmd,unsigned long arg)353 static long vfio_pci_ioctl(void *device_data,
354 			   unsigned int cmd, unsigned long arg)
355 {
356 	struct vfio_pci_device *vdev = device_data;
357 	unsigned long minsz;
358 
359 	if (cmd == VFIO_DEVICE_GET_INFO) {
360 		struct vfio_device_info info;
361 
362 		minsz = offsetofend(struct vfio_device_info, num_irqs);
363 
364 		if (copy_from_user(&info, (void __user *)arg, minsz))
365 			return -EFAULT;
366 
367 		if (info.argsz < minsz)
368 			return -EINVAL;
369 
370 		info.flags = VFIO_DEVICE_FLAGS_PCI;
371 
372 		if (vdev->reset_works)
373 			info.flags |= VFIO_DEVICE_FLAGS_RESET;
374 
375 		info.num_regions = VFIO_PCI_NUM_REGIONS;
376 		info.num_irqs = VFIO_PCI_NUM_IRQS;
377 
378 		return copy_to_user((void __user *)arg, &info, minsz) ?
379 			-EFAULT : 0;
380 
381 	} else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
382 		struct pci_dev *pdev = vdev->pdev;
383 		struct vfio_region_info info;
384 
385 		minsz = offsetofend(struct vfio_region_info, offset);
386 
387 		if (copy_from_user(&info, (void __user *)arg, minsz))
388 			return -EFAULT;
389 
390 		if (info.argsz < minsz)
391 			return -EINVAL;
392 
393 		switch (info.index) {
394 		case VFIO_PCI_CONFIG_REGION_INDEX:
395 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
396 			info.size = pdev->cfg_size;
397 			info.flags = VFIO_REGION_INFO_FLAG_READ |
398 				     VFIO_REGION_INFO_FLAG_WRITE;
399 			break;
400 		case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
401 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
402 			info.size = pci_resource_len(pdev, info.index);
403 			if (!info.size) {
404 				info.flags = 0;
405 				break;
406 			}
407 
408 			info.flags = VFIO_REGION_INFO_FLAG_READ |
409 				     VFIO_REGION_INFO_FLAG_WRITE;
410 			if (pci_resource_flags(pdev, info.index) &
411 			    IORESOURCE_MEM && info.size >= PAGE_SIZE)
412 				info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
413 			break;
414 		case VFIO_PCI_ROM_REGION_INDEX:
415 		{
416 			void __iomem *io;
417 			size_t size;
418 
419 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
420 			info.flags = 0;
421 
422 			/* Report the BAR size, not the ROM size */
423 			info.size = pci_resource_len(pdev, info.index);
424 			if (!info.size)
425 				break;
426 
427 			/* Is it really there? */
428 			io = pci_map_rom(pdev, &size);
429 			if (!io || !size) {
430 				info.size = 0;
431 				break;
432 			}
433 			pci_unmap_rom(pdev, io);
434 
435 			info.flags = VFIO_REGION_INFO_FLAG_READ;
436 			break;
437 		}
438 		case VFIO_PCI_VGA_REGION_INDEX:
439 			if (!vdev->has_vga)
440 				return -EINVAL;
441 
442 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
443 			info.size = 0xc0000;
444 			info.flags = VFIO_REGION_INFO_FLAG_READ |
445 				     VFIO_REGION_INFO_FLAG_WRITE;
446 
447 			break;
448 		default:
449 			return -EINVAL;
450 		}
451 
452 		return copy_to_user((void __user *)arg, &info, minsz) ?
453 			-EFAULT : 0;
454 
455 	} else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
456 		struct vfio_irq_info info;
457 
458 		minsz = offsetofend(struct vfio_irq_info, count);
459 
460 		if (copy_from_user(&info, (void __user *)arg, minsz))
461 			return -EFAULT;
462 
463 		if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
464 			return -EINVAL;
465 
466 		switch (info.index) {
467 		case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
468 			break;
469 		case VFIO_PCI_ERR_IRQ_INDEX:
470 			if (pci_is_pcie(vdev->pdev))
471 				break;
472 		/* pass thru to return error */
473 		default:
474 			return -EINVAL;
475 		}
476 
477 		info.flags = VFIO_IRQ_INFO_EVENTFD;
478 
479 		info.count = vfio_pci_get_irq_count(vdev, info.index);
480 
481 		if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
482 			info.flags |= (VFIO_IRQ_INFO_MASKABLE |
483 				       VFIO_IRQ_INFO_AUTOMASKED);
484 		else
485 			info.flags |= VFIO_IRQ_INFO_NORESIZE;
486 
487 		return copy_to_user((void __user *)arg, &info, minsz) ?
488 			-EFAULT : 0;
489 
490 	} else if (cmd == VFIO_DEVICE_SET_IRQS) {
491 		struct vfio_irq_set hdr;
492 		size_t size;
493 		u8 *data = NULL;
494 		int max, ret = 0;
495 
496 		minsz = offsetofend(struct vfio_irq_set, count);
497 
498 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
499 			return -EFAULT;
500 
501 		if (hdr.argsz < minsz || hdr.index >= VFIO_PCI_NUM_IRQS ||
502 		    hdr.count >= (U32_MAX - hdr.start) ||
503 		    hdr.flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK |
504 				  VFIO_IRQ_SET_ACTION_TYPE_MASK))
505 			return -EINVAL;
506 
507 		max = vfio_pci_get_irq_count(vdev, hdr.index);
508 		if (hdr.start >= max || hdr.start + hdr.count > max)
509 			return -EINVAL;
510 
511 		switch (hdr.flags & VFIO_IRQ_SET_DATA_TYPE_MASK) {
512 		case VFIO_IRQ_SET_DATA_NONE:
513 			size = 0;
514 			break;
515 		case VFIO_IRQ_SET_DATA_BOOL:
516 			size = sizeof(uint8_t);
517 			break;
518 		case VFIO_IRQ_SET_DATA_EVENTFD:
519 			size = sizeof(int32_t);
520 			break;
521 		default:
522 			return -EINVAL;
523 		}
524 
525 		if (size) {
526 			if (hdr.argsz - minsz < hdr.count * size)
527 				return -EINVAL;
528 
529 			data = memdup_user((void __user *)(arg + minsz),
530 					   hdr.count * size);
531 			if (IS_ERR(data))
532 				return PTR_ERR(data);
533 		}
534 
535 		mutex_lock(&vdev->igate);
536 
537 		ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
538 					      hdr.start, hdr.count, data);
539 
540 		mutex_unlock(&vdev->igate);
541 		kfree(data);
542 
543 		return ret;
544 
545 	} else if (cmd == VFIO_DEVICE_RESET) {
546 		return vdev->reset_works ?
547 			pci_try_reset_function(vdev->pdev) : -EINVAL;
548 
549 	} else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
550 		struct vfio_pci_hot_reset_info hdr;
551 		struct vfio_pci_fill_info fill = { 0 };
552 		struct vfio_pci_dependent_device *devices = NULL;
553 		bool slot = false;
554 		int ret = 0;
555 
556 		minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
557 
558 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
559 			return -EFAULT;
560 
561 		if (hdr.argsz < minsz)
562 			return -EINVAL;
563 
564 		hdr.flags = 0;
565 
566 		/* Can we do a slot or bus reset or neither? */
567 		if (!pci_probe_reset_slot(vdev->pdev->slot))
568 			slot = true;
569 		else if (pci_probe_reset_bus(vdev->pdev->bus))
570 			return -ENODEV;
571 
572 		/* How many devices are affected? */
573 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
574 						    vfio_pci_count_devs,
575 						    &fill.max, slot);
576 		if (ret)
577 			return ret;
578 
579 		WARN_ON(!fill.max); /* Should always be at least one */
580 
581 		/*
582 		 * If there's enough space, fill it now, otherwise return
583 		 * -ENOSPC and the number of devices affected.
584 		 */
585 		if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
586 			ret = -ENOSPC;
587 			hdr.count = fill.max;
588 			goto reset_info_exit;
589 		}
590 
591 		devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
592 		if (!devices)
593 			return -ENOMEM;
594 
595 		fill.devices = devices;
596 
597 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
598 						    vfio_pci_fill_devs,
599 						    &fill, slot);
600 
601 		/*
602 		 * If a device was removed between counting and filling,
603 		 * we may come up short of fill.max.  If a device was
604 		 * added, we'll have a return of -EAGAIN above.
605 		 */
606 		if (!ret)
607 			hdr.count = fill.cur;
608 
609 reset_info_exit:
610 		if (copy_to_user((void __user *)arg, &hdr, minsz))
611 			ret = -EFAULT;
612 
613 		if (!ret) {
614 			if (copy_to_user((void __user *)(arg + minsz), devices,
615 					 hdr.count * sizeof(*devices)))
616 				ret = -EFAULT;
617 		}
618 
619 		kfree(devices);
620 		return ret;
621 
622 	} else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
623 		struct vfio_pci_hot_reset hdr;
624 		int32_t *group_fds;
625 		struct vfio_pci_group_entry *groups;
626 		struct vfio_pci_group_info info;
627 		bool slot = false;
628 		int i, count = 0, ret = 0;
629 
630 		minsz = offsetofend(struct vfio_pci_hot_reset, count);
631 
632 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
633 			return -EFAULT;
634 
635 		if (hdr.argsz < minsz || hdr.flags)
636 			return -EINVAL;
637 
638 		/* Can we do a slot or bus reset or neither? */
639 		if (!pci_probe_reset_slot(vdev->pdev->slot))
640 			slot = true;
641 		else if (pci_probe_reset_bus(vdev->pdev->bus))
642 			return -ENODEV;
643 
644 		/*
645 		 * We can't let userspace give us an arbitrarily large
646 		 * buffer to copy, so verify how many we think there
647 		 * could be.  Note groups can have multiple devices so
648 		 * one group per device is the max.
649 		 */
650 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
651 						    vfio_pci_count_devs,
652 						    &count, slot);
653 		if (ret)
654 			return ret;
655 
656 		/* Somewhere between 1 and count is OK */
657 		if (!hdr.count || hdr.count > count)
658 			return -EINVAL;
659 
660 		group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
661 		groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);
662 		if (!group_fds || !groups) {
663 			kfree(group_fds);
664 			kfree(groups);
665 			return -ENOMEM;
666 		}
667 
668 		if (copy_from_user(group_fds, (void __user *)(arg + minsz),
669 				   hdr.count * sizeof(*group_fds))) {
670 			kfree(group_fds);
671 			kfree(groups);
672 			return -EFAULT;
673 		}
674 
675 		/*
676 		 * For each group_fd, get the group through the vfio external
677 		 * user interface and store the group and iommu ID.  This
678 		 * ensures the group is held across the reset.
679 		 */
680 		for (i = 0; i < hdr.count; i++) {
681 			struct vfio_group *group;
682 			struct fd f = fdget(group_fds[i]);
683 			if (!f.file) {
684 				ret = -EBADF;
685 				break;
686 			}
687 
688 			group = vfio_group_get_external_user(f.file);
689 			fdput(f);
690 			if (IS_ERR(group)) {
691 				ret = PTR_ERR(group);
692 				break;
693 			}
694 
695 			groups[i].group = group;
696 			groups[i].id = vfio_external_user_iommu_id(group);
697 		}
698 
699 		kfree(group_fds);
700 
701 		/* release reference to groups on error */
702 		if (ret)
703 			goto hot_reset_release;
704 
705 		info.count = hdr.count;
706 		info.groups = groups;
707 
708 		/*
709 		 * Test whether all the affected devices are contained
710 		 * by the set of groups provided by the user.
711 		 */
712 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
713 						    vfio_pci_validate_devs,
714 						    &info, slot);
715 		if (!ret)
716 			/* User has access, do the reset */
717 			ret = slot ? pci_try_reset_slot(vdev->pdev->slot) :
718 				     pci_try_reset_bus(vdev->pdev->bus);
719 
720 hot_reset_release:
721 		for (i--; i >= 0; i--)
722 			vfio_group_put_external_user(groups[i].group);
723 
724 		kfree(groups);
725 		return ret;
726 	}
727 
728 	return -ENOTTY;
729 }
730 
vfio_pci_rw(void * device_data,char __user * buf,size_t count,loff_t * ppos,bool iswrite)731 static ssize_t vfio_pci_rw(void *device_data, char __user *buf,
732 			   size_t count, loff_t *ppos, bool iswrite)
733 {
734 	unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
735 	struct vfio_pci_device *vdev = device_data;
736 
737 	if (index >= VFIO_PCI_NUM_REGIONS)
738 		return -EINVAL;
739 
740 	switch (index) {
741 	case VFIO_PCI_CONFIG_REGION_INDEX:
742 		return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
743 
744 	case VFIO_PCI_ROM_REGION_INDEX:
745 		if (iswrite)
746 			return -EINVAL;
747 		return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
748 
749 	case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
750 		return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
751 
752 	case VFIO_PCI_VGA_REGION_INDEX:
753 		return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
754 	}
755 
756 	return -EINVAL;
757 }
758 
vfio_pci_read(void * device_data,char __user * buf,size_t count,loff_t * ppos)759 static ssize_t vfio_pci_read(void *device_data, char __user *buf,
760 			     size_t count, loff_t *ppos)
761 {
762 	if (!count)
763 		return 0;
764 
765 	return vfio_pci_rw(device_data, buf, count, ppos, false);
766 }
767 
vfio_pci_write(void * device_data,const char __user * buf,size_t count,loff_t * ppos)768 static ssize_t vfio_pci_write(void *device_data, const char __user *buf,
769 			      size_t count, loff_t *ppos)
770 {
771 	if (!count)
772 		return 0;
773 
774 	return vfio_pci_rw(device_data, (char __user *)buf, count, ppos, true);
775 }
776 
vfio_pci_mmap(void * device_data,struct vm_area_struct * vma)777 static int vfio_pci_mmap(void *device_data, struct vm_area_struct *vma)
778 {
779 	struct vfio_pci_device *vdev = device_data;
780 	struct pci_dev *pdev = vdev->pdev;
781 	unsigned int index;
782 	u64 phys_len, req_len, pgoff, req_start;
783 	int ret;
784 
785 	index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
786 
787 	if (vma->vm_end < vma->vm_start)
788 		return -EINVAL;
789 	if ((vma->vm_flags & VM_SHARED) == 0)
790 		return -EINVAL;
791 	if (index >= VFIO_PCI_ROM_REGION_INDEX)
792 		return -EINVAL;
793 	if (!(pci_resource_flags(pdev, index) & IORESOURCE_MEM))
794 		return -EINVAL;
795 
796 	phys_len = pci_resource_len(pdev, index);
797 	req_len = vma->vm_end - vma->vm_start;
798 	pgoff = vma->vm_pgoff &
799 		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
800 	req_start = pgoff << PAGE_SHIFT;
801 
802 	if (phys_len < PAGE_SIZE || req_start + req_len > phys_len)
803 		return -EINVAL;
804 
805 	if (index == vdev->msix_bar) {
806 		/*
807 		 * Disallow mmaps overlapping the MSI-X table; users don't
808 		 * get to touch this directly.  We could find somewhere
809 		 * else to map the overlap, but page granularity is only
810 		 * a recommendation, not a requirement, so the user needs
811 		 * to know which bits are real.  Requiring them to mmap
812 		 * around the table makes that clear.
813 		 */
814 
815 		/* If neither entirely above nor below, then it overlaps */
816 		if (!(req_start >= vdev->msix_offset + vdev->msix_size ||
817 		      req_start + req_len <= vdev->msix_offset))
818 			return -EINVAL;
819 	}
820 
821 	/*
822 	 * Even though we don't make use of the barmap for the mmap,
823 	 * we need to request the region and the barmap tracks that.
824 	 */
825 	if (!vdev->barmap[index]) {
826 		ret = pci_request_selected_regions(pdev,
827 						   1 << index, "vfio-pci");
828 		if (ret)
829 			return ret;
830 
831 		vdev->barmap[index] = pci_iomap(pdev, index, 0);
832 	}
833 
834 	vma->vm_private_data = vdev;
835 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
836 	vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
837 
838 	return remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
839 			       req_len, vma->vm_page_prot);
840 }
841 
842 static const struct vfio_device_ops vfio_pci_ops = {
843 	.name		= "vfio-pci",
844 	.open		= vfio_pci_open,
845 	.release	= vfio_pci_release,
846 	.ioctl		= vfio_pci_ioctl,
847 	.read		= vfio_pci_read,
848 	.write		= vfio_pci_write,
849 	.mmap		= vfio_pci_mmap,
850 };
851 
vfio_pci_probe(struct pci_dev * pdev,const struct pci_device_id * id)852 static int vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
853 {
854 	struct vfio_pci_device *vdev;
855 	struct iommu_group *group;
856 	int ret;
857 
858 	if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
859 		return -EINVAL;
860 
861 	group = iommu_group_get(&pdev->dev);
862 	if (!group)
863 		return -EINVAL;
864 
865 	vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
866 	if (!vdev) {
867 		iommu_group_put(group);
868 		return -ENOMEM;
869 	}
870 
871 	vdev->pdev = pdev;
872 	vdev->irq_type = VFIO_PCI_NUM_IRQS;
873 	mutex_init(&vdev->igate);
874 	spin_lock_init(&vdev->irqlock);
875 
876 	ret = vfio_add_group_dev(&pdev->dev, &vfio_pci_ops, vdev);
877 	if (ret) {
878 		iommu_group_put(group);
879 		kfree(vdev);
880 	}
881 
882 	return ret;
883 }
884 
vfio_pci_remove(struct pci_dev * pdev)885 static void vfio_pci_remove(struct pci_dev *pdev)
886 {
887 	struct vfio_pci_device *vdev;
888 
889 	vdev = vfio_del_group_dev(&pdev->dev);
890 	if (vdev) {
891 		iommu_group_put(pdev->dev.iommu_group);
892 		kfree(vdev);
893 	}
894 }
895 
vfio_pci_aer_err_detected(struct pci_dev * pdev,pci_channel_state_t state)896 static pci_ers_result_t vfio_pci_aer_err_detected(struct pci_dev *pdev,
897 						  pci_channel_state_t state)
898 {
899 	struct vfio_pci_device *vdev;
900 	struct vfio_device *device;
901 
902 	device = vfio_device_get_from_dev(&pdev->dev);
903 	if (device == NULL)
904 		return PCI_ERS_RESULT_DISCONNECT;
905 
906 	vdev = vfio_device_data(device);
907 	if (vdev == NULL) {
908 		vfio_device_put(device);
909 		return PCI_ERS_RESULT_DISCONNECT;
910 	}
911 
912 	mutex_lock(&vdev->igate);
913 
914 	if (vdev->err_trigger)
915 		eventfd_signal(vdev->err_trigger, 1);
916 
917 	mutex_unlock(&vdev->igate);
918 
919 	vfio_device_put(device);
920 
921 	return PCI_ERS_RESULT_CAN_RECOVER;
922 }
923 
924 static struct pci_error_handlers vfio_err_handlers = {
925 	.error_detected = vfio_pci_aer_err_detected,
926 };
927 
928 static struct pci_driver vfio_pci_driver = {
929 	.name		= "vfio-pci",
930 	.id_table	= NULL, /* only dynamic ids */
931 	.probe		= vfio_pci_probe,
932 	.remove		= vfio_pci_remove,
933 	.err_handler	= &vfio_err_handlers,
934 };
935 
936 struct vfio_devices {
937 	struct vfio_device **devices;
938 	int cur_index;
939 	int max_index;
940 };
941 
vfio_pci_get_devs(struct pci_dev * pdev,void * data)942 static int vfio_pci_get_devs(struct pci_dev *pdev, void *data)
943 {
944 	struct vfio_devices *devs = data;
945 	struct pci_driver *pci_drv = ACCESS_ONCE(pdev->driver);
946 
947 	if (pci_drv != &vfio_pci_driver)
948 		return -EBUSY;
949 
950 	if (devs->cur_index == devs->max_index)
951 		return -ENOSPC;
952 
953 	devs->devices[devs->cur_index] = vfio_device_get_from_dev(&pdev->dev);
954 	if (!devs->devices[devs->cur_index])
955 		return -EINVAL;
956 
957 	devs->cur_index++;
958 	return 0;
959 }
960 
961 /*
962  * Attempt to do a bus/slot reset if there are devices affected by a reset for
963  * this device that are needs_reset and all of the affected devices are unused
964  * (!refcnt).  Callers are required to hold driver_lock when calling this to
965  * prevent device opens and concurrent bus reset attempts.  We prevent device
966  * unbinds by acquiring and holding a reference to the vfio_device.
967  *
968  * NB: vfio-core considers a group to be viable even if some devices are
969  * bound to drivers like pci-stub or pcieport.  Here we require all devices
970  * to be bound to vfio_pci since that's the only way we can be sure they
971  * stay put.
972  */
vfio_pci_try_bus_reset(struct vfio_pci_device * vdev)973 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev)
974 {
975 	struct vfio_devices devs = { .cur_index = 0 };
976 	int i = 0, ret = -EINVAL;
977 	bool needs_reset = false, slot = false;
978 	struct vfio_pci_device *tmp;
979 
980 	if (!pci_probe_reset_slot(vdev->pdev->slot))
981 		slot = true;
982 	else if (pci_probe_reset_bus(vdev->pdev->bus))
983 		return;
984 
985 	if (vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
986 					  &i, slot) || !i)
987 		return;
988 
989 	devs.max_index = i;
990 	devs.devices = kcalloc(i, sizeof(struct vfio_device *), GFP_KERNEL);
991 	if (!devs.devices)
992 		return;
993 
994 	if (vfio_pci_for_each_slot_or_bus(vdev->pdev,
995 					  vfio_pci_get_devs, &devs, slot))
996 		goto put_devs;
997 
998 	for (i = 0; i < devs.cur_index; i++) {
999 		tmp = vfio_device_data(devs.devices[i]);
1000 		if (tmp->needs_reset)
1001 			needs_reset = true;
1002 		if (tmp->refcnt)
1003 			goto put_devs;
1004 	}
1005 
1006 	if (needs_reset)
1007 		ret = slot ? pci_try_reset_slot(vdev->pdev->slot) :
1008 			     pci_try_reset_bus(vdev->pdev->bus);
1009 
1010 put_devs:
1011 	for (i = 0; i < devs.cur_index; i++) {
1012 		if (!ret) {
1013 			tmp = vfio_device_data(devs.devices[i]);
1014 			tmp->needs_reset = false;
1015 		}
1016 		vfio_device_put(devs.devices[i]);
1017 	}
1018 
1019 	kfree(devs.devices);
1020 }
1021 
vfio_pci_cleanup(void)1022 static void __exit vfio_pci_cleanup(void)
1023 {
1024 	pci_unregister_driver(&vfio_pci_driver);
1025 	vfio_pci_virqfd_exit();
1026 	vfio_pci_uninit_perm_bits();
1027 }
1028 
vfio_pci_init(void)1029 static int __init vfio_pci_init(void)
1030 {
1031 	int ret;
1032 
1033 	/* Allocate shared config space permision data used by all devices */
1034 	ret = vfio_pci_init_perm_bits();
1035 	if (ret)
1036 		return ret;
1037 
1038 	/* Start the virqfd cleanup handler */
1039 	ret = vfio_pci_virqfd_init();
1040 	if (ret)
1041 		goto out_virqfd;
1042 
1043 	/* Register and scan for devices */
1044 	ret = pci_register_driver(&vfio_pci_driver);
1045 	if (ret)
1046 		goto out_driver;
1047 
1048 	return 0;
1049 
1050 out_driver:
1051 	vfio_pci_virqfd_exit();
1052 out_virqfd:
1053 	vfio_pci_uninit_perm_bits();
1054 	return ret;
1055 }
1056 
1057 module_init(vfio_pci_init);
1058 module_exit(vfio_pci_cleanup);
1059 
1060 MODULE_VERSION(DRIVER_VERSION);
1061 MODULE_LICENSE("GPL v2");
1062 MODULE_AUTHOR(DRIVER_AUTHOR);
1063 MODULE_DESCRIPTION(DRIVER_DESC);
1064