xref: /openbmc/linux/drivers/vfio/pci/vfio_pci.c (revision 92a2c6b2)
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 
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 
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 
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 
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 
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 (IS_ENABLED(CONFIG_VFIO_PCI_INTX) && 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 	} else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
246 		return 1;
247 	}
248 
249 	return 0;
250 }
251 
252 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
253 {
254 	(*(int *)data)++;
255 	return 0;
256 }
257 
258 struct vfio_pci_fill_info {
259 	int max;
260 	int cur;
261 	struct vfio_pci_dependent_device *devices;
262 };
263 
264 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
265 {
266 	struct vfio_pci_fill_info *fill = data;
267 	struct iommu_group *iommu_group;
268 
269 	if (fill->cur == fill->max)
270 		return -EAGAIN; /* Something changed, try again */
271 
272 	iommu_group = iommu_group_get(&pdev->dev);
273 	if (!iommu_group)
274 		return -EPERM; /* Cannot reset non-isolated devices */
275 
276 	fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
277 	fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
278 	fill->devices[fill->cur].bus = pdev->bus->number;
279 	fill->devices[fill->cur].devfn = pdev->devfn;
280 	fill->cur++;
281 	iommu_group_put(iommu_group);
282 	return 0;
283 }
284 
285 struct vfio_pci_group_entry {
286 	struct vfio_group *group;
287 	int id;
288 };
289 
290 struct vfio_pci_group_info {
291 	int count;
292 	struct vfio_pci_group_entry *groups;
293 };
294 
295 static int vfio_pci_validate_devs(struct pci_dev *pdev, void *data)
296 {
297 	struct vfio_pci_group_info *info = data;
298 	struct iommu_group *group;
299 	int id, i;
300 
301 	group = iommu_group_get(&pdev->dev);
302 	if (!group)
303 		return -EPERM;
304 
305 	id = iommu_group_id(group);
306 
307 	for (i = 0; i < info->count; i++)
308 		if (info->groups[i].id == id)
309 			break;
310 
311 	iommu_group_put(group);
312 
313 	return (i == info->count) ? -EINVAL : 0;
314 }
315 
316 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
317 {
318 	for (; pdev; pdev = pdev->bus->self)
319 		if (pdev->bus == slot->bus)
320 			return (pdev->slot == slot);
321 	return false;
322 }
323 
324 struct vfio_pci_walk_info {
325 	int (*fn)(struct pci_dev *, void *data);
326 	void *data;
327 	struct pci_dev *pdev;
328 	bool slot;
329 	int ret;
330 };
331 
332 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
333 {
334 	struct vfio_pci_walk_info *walk = data;
335 
336 	if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
337 		walk->ret = walk->fn(pdev, walk->data);
338 
339 	return walk->ret;
340 }
341 
342 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
343 					 int (*fn)(struct pci_dev *,
344 						   void *data), void *data,
345 					 bool slot)
346 {
347 	struct vfio_pci_walk_info walk = {
348 		.fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
349 	};
350 
351 	pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
352 
353 	return walk.ret;
354 }
355 
356 static long vfio_pci_ioctl(void *device_data,
357 			   unsigned int cmd, unsigned long arg)
358 {
359 	struct vfio_pci_device *vdev = device_data;
360 	unsigned long minsz;
361 
362 	if (cmd == VFIO_DEVICE_GET_INFO) {
363 		struct vfio_device_info info;
364 
365 		minsz = offsetofend(struct vfio_device_info, num_irqs);
366 
367 		if (copy_from_user(&info, (void __user *)arg, minsz))
368 			return -EFAULT;
369 
370 		if (info.argsz < minsz)
371 			return -EINVAL;
372 
373 		info.flags = VFIO_DEVICE_FLAGS_PCI;
374 
375 		if (vdev->reset_works)
376 			info.flags |= VFIO_DEVICE_FLAGS_RESET;
377 
378 		info.num_regions = VFIO_PCI_NUM_REGIONS;
379 		info.num_irqs = VFIO_PCI_NUM_IRQS;
380 
381 		return copy_to_user((void __user *)arg, &info, minsz);
382 
383 	} else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
384 		struct pci_dev *pdev = vdev->pdev;
385 		struct vfio_region_info info;
386 
387 		minsz = offsetofend(struct vfio_region_info, offset);
388 
389 		if (copy_from_user(&info, (void __user *)arg, minsz))
390 			return -EFAULT;
391 
392 		if (info.argsz < minsz)
393 			return -EINVAL;
394 
395 		switch (info.index) {
396 		case VFIO_PCI_CONFIG_REGION_INDEX:
397 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
398 			info.size = pdev->cfg_size;
399 			info.flags = VFIO_REGION_INFO_FLAG_READ |
400 				     VFIO_REGION_INFO_FLAG_WRITE;
401 			break;
402 		case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
403 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
404 			info.size = pci_resource_len(pdev, info.index);
405 			if (!info.size) {
406 				info.flags = 0;
407 				break;
408 			}
409 
410 			info.flags = VFIO_REGION_INFO_FLAG_READ |
411 				     VFIO_REGION_INFO_FLAG_WRITE;
412 			if (IS_ENABLED(CONFIG_VFIO_PCI_MMAP) &&
413 			    pci_resource_flags(pdev, info.index) &
414 			    IORESOURCE_MEM && info.size >= PAGE_SIZE)
415 				info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
416 			break;
417 		case VFIO_PCI_ROM_REGION_INDEX:
418 		{
419 			void __iomem *io;
420 			size_t size;
421 
422 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
423 			info.flags = 0;
424 
425 			/* Report the BAR size, not the ROM size */
426 			info.size = pci_resource_len(pdev, info.index);
427 			if (!info.size)
428 				break;
429 
430 			/* Is it really there? */
431 			io = pci_map_rom(pdev, &size);
432 			if (!io || !size) {
433 				info.size = 0;
434 				break;
435 			}
436 			pci_unmap_rom(pdev, io);
437 
438 			info.flags = VFIO_REGION_INFO_FLAG_READ;
439 			break;
440 		}
441 		case VFIO_PCI_VGA_REGION_INDEX:
442 			if (!vdev->has_vga)
443 				return -EINVAL;
444 
445 			info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
446 			info.size = 0xc0000;
447 			info.flags = VFIO_REGION_INFO_FLAG_READ |
448 				     VFIO_REGION_INFO_FLAG_WRITE;
449 
450 			break;
451 		default:
452 			return -EINVAL;
453 		}
454 
455 		return copy_to_user((void __user *)arg, &info, minsz);
456 
457 	} else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
458 		struct vfio_irq_info info;
459 
460 		minsz = offsetofend(struct vfio_irq_info, count);
461 
462 		if (copy_from_user(&info, (void __user *)arg, minsz))
463 			return -EFAULT;
464 
465 		if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
466 			return -EINVAL;
467 
468 		switch (info.index) {
469 		case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
470 		case VFIO_PCI_REQ_IRQ_INDEX:
471 			break;
472 		case VFIO_PCI_ERR_IRQ_INDEX:
473 			if (pci_is_pcie(vdev->pdev))
474 				break;
475 		/* pass thru to return error */
476 		default:
477 			return -EINVAL;
478 		}
479 
480 		info.flags = VFIO_IRQ_INFO_EVENTFD;
481 
482 		info.count = vfio_pci_get_irq_count(vdev, info.index);
483 
484 		if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
485 			info.flags |= (VFIO_IRQ_INFO_MASKABLE |
486 				       VFIO_IRQ_INFO_AUTOMASKED);
487 		else
488 			info.flags |= VFIO_IRQ_INFO_NORESIZE;
489 
490 		return copy_to_user((void __user *)arg, &info, minsz);
491 
492 	} else if (cmd == VFIO_DEVICE_SET_IRQS) {
493 		struct vfio_irq_set hdr;
494 		u8 *data = NULL;
495 		int ret = 0;
496 
497 		minsz = offsetofend(struct vfio_irq_set, count);
498 
499 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
500 			return -EFAULT;
501 
502 		if (hdr.argsz < minsz || hdr.index >= VFIO_PCI_NUM_IRQS ||
503 		    hdr.flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK |
504 				  VFIO_IRQ_SET_ACTION_TYPE_MASK))
505 			return -EINVAL;
506 
507 		if (!(hdr.flags & VFIO_IRQ_SET_DATA_NONE)) {
508 			size_t size;
509 			int max = vfio_pci_get_irq_count(vdev, hdr.index);
510 
511 			if (hdr.flags & VFIO_IRQ_SET_DATA_BOOL)
512 				size = sizeof(uint8_t);
513 			else if (hdr.flags & VFIO_IRQ_SET_DATA_EVENTFD)
514 				size = sizeof(int32_t);
515 			else
516 				return -EINVAL;
517 
518 			if (hdr.argsz - minsz < hdr.count * size ||
519 			    hdr.start >= max || hdr.start + hdr.count > max)
520 				return -EINVAL;
521 
522 			data = memdup_user((void __user *)(arg + minsz),
523 					   hdr.count * size);
524 			if (IS_ERR(data))
525 				return PTR_ERR(data);
526 		}
527 
528 		mutex_lock(&vdev->igate);
529 
530 		ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
531 					      hdr.start, hdr.count, data);
532 
533 		mutex_unlock(&vdev->igate);
534 		kfree(data);
535 
536 		return ret;
537 
538 	} else if (cmd == VFIO_DEVICE_RESET) {
539 		return vdev->reset_works ?
540 			pci_try_reset_function(vdev->pdev) : -EINVAL;
541 
542 	} else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
543 		struct vfio_pci_hot_reset_info hdr;
544 		struct vfio_pci_fill_info fill = { 0 };
545 		struct vfio_pci_dependent_device *devices = NULL;
546 		bool slot = false;
547 		int ret = 0;
548 
549 		minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
550 
551 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
552 			return -EFAULT;
553 
554 		if (hdr.argsz < minsz)
555 			return -EINVAL;
556 
557 		hdr.flags = 0;
558 
559 		/* Can we do a slot or bus reset or neither? */
560 		if (!pci_probe_reset_slot(vdev->pdev->slot))
561 			slot = true;
562 		else if (pci_probe_reset_bus(vdev->pdev->bus))
563 			return -ENODEV;
564 
565 		/* How many devices are affected? */
566 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
567 						    vfio_pci_count_devs,
568 						    &fill.max, slot);
569 		if (ret)
570 			return ret;
571 
572 		WARN_ON(!fill.max); /* Should always be at least one */
573 
574 		/*
575 		 * If there's enough space, fill it now, otherwise return
576 		 * -ENOSPC and the number of devices affected.
577 		 */
578 		if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
579 			ret = -ENOSPC;
580 			hdr.count = fill.max;
581 			goto reset_info_exit;
582 		}
583 
584 		devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
585 		if (!devices)
586 			return -ENOMEM;
587 
588 		fill.devices = devices;
589 
590 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
591 						    vfio_pci_fill_devs,
592 						    &fill, slot);
593 
594 		/*
595 		 * If a device was removed between counting and filling,
596 		 * we may come up short of fill.max.  If a device was
597 		 * added, we'll have a return of -EAGAIN above.
598 		 */
599 		if (!ret)
600 			hdr.count = fill.cur;
601 
602 reset_info_exit:
603 		if (copy_to_user((void __user *)arg, &hdr, minsz))
604 			ret = -EFAULT;
605 
606 		if (!ret) {
607 			if (copy_to_user((void __user *)(arg + minsz), devices,
608 					 hdr.count * sizeof(*devices)))
609 				ret = -EFAULT;
610 		}
611 
612 		kfree(devices);
613 		return ret;
614 
615 	} else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
616 		struct vfio_pci_hot_reset hdr;
617 		int32_t *group_fds;
618 		struct vfio_pci_group_entry *groups;
619 		struct vfio_pci_group_info info;
620 		bool slot = false;
621 		int i, count = 0, ret = 0;
622 
623 		minsz = offsetofend(struct vfio_pci_hot_reset, count);
624 
625 		if (copy_from_user(&hdr, (void __user *)arg, minsz))
626 			return -EFAULT;
627 
628 		if (hdr.argsz < minsz || hdr.flags)
629 			return -EINVAL;
630 
631 		/* Can we do a slot or bus reset or neither? */
632 		if (!pci_probe_reset_slot(vdev->pdev->slot))
633 			slot = true;
634 		else if (pci_probe_reset_bus(vdev->pdev->bus))
635 			return -ENODEV;
636 
637 		/*
638 		 * We can't let userspace give us an arbitrarily large
639 		 * buffer to copy, so verify how many we think there
640 		 * could be.  Note groups can have multiple devices so
641 		 * one group per device is the max.
642 		 */
643 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
644 						    vfio_pci_count_devs,
645 						    &count, slot);
646 		if (ret)
647 			return ret;
648 
649 		/* Somewhere between 1 and count is OK */
650 		if (!hdr.count || hdr.count > count)
651 			return -EINVAL;
652 
653 		group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
654 		groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);
655 		if (!group_fds || !groups) {
656 			kfree(group_fds);
657 			kfree(groups);
658 			return -ENOMEM;
659 		}
660 
661 		if (copy_from_user(group_fds, (void __user *)(arg + minsz),
662 				   hdr.count * sizeof(*group_fds))) {
663 			kfree(group_fds);
664 			kfree(groups);
665 			return -EFAULT;
666 		}
667 
668 		/*
669 		 * For each group_fd, get the group through the vfio external
670 		 * user interface and store the group and iommu ID.  This
671 		 * ensures the group is held across the reset.
672 		 */
673 		for (i = 0; i < hdr.count; i++) {
674 			struct vfio_group *group;
675 			struct fd f = fdget(group_fds[i]);
676 			if (!f.file) {
677 				ret = -EBADF;
678 				break;
679 			}
680 
681 			group = vfio_group_get_external_user(f.file);
682 			fdput(f);
683 			if (IS_ERR(group)) {
684 				ret = PTR_ERR(group);
685 				break;
686 			}
687 
688 			groups[i].group = group;
689 			groups[i].id = vfio_external_user_iommu_id(group);
690 		}
691 
692 		kfree(group_fds);
693 
694 		/* release reference to groups on error */
695 		if (ret)
696 			goto hot_reset_release;
697 
698 		info.count = hdr.count;
699 		info.groups = groups;
700 
701 		/*
702 		 * Test whether all the affected devices are contained
703 		 * by the set of groups provided by the user.
704 		 */
705 		ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
706 						    vfio_pci_validate_devs,
707 						    &info, slot);
708 		if (!ret)
709 			/* User has access, do the reset */
710 			ret = slot ? pci_try_reset_slot(vdev->pdev->slot) :
711 				     pci_try_reset_bus(vdev->pdev->bus);
712 
713 hot_reset_release:
714 		for (i--; i >= 0; i--)
715 			vfio_group_put_external_user(groups[i].group);
716 
717 		kfree(groups);
718 		return ret;
719 	}
720 
721 	return -ENOTTY;
722 }
723 
724 static ssize_t vfio_pci_rw(void *device_data, char __user *buf,
725 			   size_t count, loff_t *ppos, bool iswrite)
726 {
727 	unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
728 	struct vfio_pci_device *vdev = device_data;
729 
730 	if (index >= VFIO_PCI_NUM_REGIONS)
731 		return -EINVAL;
732 
733 	switch (index) {
734 	case VFIO_PCI_CONFIG_REGION_INDEX:
735 		return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
736 
737 	case VFIO_PCI_ROM_REGION_INDEX:
738 		if (iswrite)
739 			return -EINVAL;
740 		return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
741 
742 	case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
743 		return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
744 
745 	case VFIO_PCI_VGA_REGION_INDEX:
746 		return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
747 	}
748 
749 	return -EINVAL;
750 }
751 
752 static ssize_t vfio_pci_read(void *device_data, char __user *buf,
753 			     size_t count, loff_t *ppos)
754 {
755 	if (!count)
756 		return 0;
757 
758 	return vfio_pci_rw(device_data, buf, count, ppos, false);
759 }
760 
761 static ssize_t vfio_pci_write(void *device_data, const char __user *buf,
762 			      size_t count, loff_t *ppos)
763 {
764 	if (!count)
765 		return 0;
766 
767 	return vfio_pci_rw(device_data, (char __user *)buf, count, ppos, true);
768 }
769 
770 static int vfio_pci_mmap(void *device_data, struct vm_area_struct *vma)
771 {
772 	struct vfio_pci_device *vdev = device_data;
773 	struct pci_dev *pdev = vdev->pdev;
774 	unsigned int index;
775 	u64 phys_len, req_len, pgoff, req_start;
776 	int ret;
777 
778 	index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
779 
780 	if (vma->vm_end < vma->vm_start)
781 		return -EINVAL;
782 	if ((vma->vm_flags & VM_SHARED) == 0)
783 		return -EINVAL;
784 	if (index >= VFIO_PCI_ROM_REGION_INDEX)
785 		return -EINVAL;
786 	if (!(pci_resource_flags(pdev, index) & IORESOURCE_MEM))
787 		return -EINVAL;
788 
789 	phys_len = pci_resource_len(pdev, index);
790 	req_len = vma->vm_end - vma->vm_start;
791 	pgoff = vma->vm_pgoff &
792 		((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
793 	req_start = pgoff << PAGE_SHIFT;
794 
795 	if (phys_len < PAGE_SIZE || req_start + req_len > phys_len)
796 		return -EINVAL;
797 
798 	if (index == vdev->msix_bar) {
799 		/*
800 		 * Disallow mmaps overlapping the MSI-X table; users don't
801 		 * get to touch this directly.  We could find somewhere
802 		 * else to map the overlap, but page granularity is only
803 		 * a recommendation, not a requirement, so the user needs
804 		 * to know which bits are real.  Requiring them to mmap
805 		 * around the table makes that clear.
806 		 */
807 
808 		/* If neither entirely above nor below, then it overlaps */
809 		if (!(req_start >= vdev->msix_offset + vdev->msix_size ||
810 		      req_start + req_len <= vdev->msix_offset))
811 			return -EINVAL;
812 	}
813 
814 	/*
815 	 * Even though we don't make use of the barmap for the mmap,
816 	 * we need to request the region and the barmap tracks that.
817 	 */
818 	if (!vdev->barmap[index]) {
819 		ret = pci_request_selected_regions(pdev,
820 						   1 << index, "vfio-pci");
821 		if (ret)
822 			return ret;
823 
824 		vdev->barmap[index] = pci_iomap(pdev, index, 0);
825 	}
826 
827 	vma->vm_private_data = vdev;
828 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
829 	vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
830 
831 	return remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
832 			       req_len, vma->vm_page_prot);
833 }
834 
835 static void vfio_pci_request(void *device_data, unsigned int count)
836 {
837 	struct vfio_pci_device *vdev = device_data;
838 
839 	mutex_lock(&vdev->igate);
840 
841 	if (vdev->req_trigger) {
842 		dev_dbg(&vdev->pdev->dev, "Requesting device from user\n");
843 		eventfd_signal(vdev->req_trigger, 1);
844 	}
845 
846 	mutex_unlock(&vdev->igate);
847 }
848 
849 static const struct vfio_device_ops vfio_pci_ops = {
850 	.name		= "vfio-pci",
851 	.open		= vfio_pci_open,
852 	.release	= vfio_pci_release,
853 	.ioctl		= vfio_pci_ioctl,
854 	.read		= vfio_pci_read,
855 	.write		= vfio_pci_write,
856 	.mmap		= vfio_pci_mmap,
857 	.request	= vfio_pci_request,
858 };
859 
860 static int vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
861 {
862 	struct vfio_pci_device *vdev;
863 	struct iommu_group *group;
864 	int ret;
865 
866 	if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
867 		return -EINVAL;
868 
869 	group = iommu_group_get(&pdev->dev);
870 	if (!group)
871 		return -EINVAL;
872 
873 	vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
874 	if (!vdev) {
875 		iommu_group_put(group);
876 		return -ENOMEM;
877 	}
878 
879 	vdev->pdev = pdev;
880 	vdev->irq_type = VFIO_PCI_NUM_IRQS;
881 	mutex_init(&vdev->igate);
882 	spin_lock_init(&vdev->irqlock);
883 
884 	ret = vfio_add_group_dev(&pdev->dev, &vfio_pci_ops, vdev);
885 	if (ret) {
886 		iommu_group_put(group);
887 		kfree(vdev);
888 	}
889 
890 	return ret;
891 }
892 
893 static void vfio_pci_remove(struct pci_dev *pdev)
894 {
895 	struct vfio_pci_device *vdev;
896 
897 	vdev = vfio_del_group_dev(&pdev->dev);
898 	if (vdev) {
899 		iommu_group_put(pdev->dev.iommu_group);
900 		kfree(vdev);
901 	}
902 }
903 
904 static pci_ers_result_t vfio_pci_aer_err_detected(struct pci_dev *pdev,
905 						  pci_channel_state_t state)
906 {
907 	struct vfio_pci_device *vdev;
908 	struct vfio_device *device;
909 
910 	device = vfio_device_get_from_dev(&pdev->dev);
911 	if (device == NULL)
912 		return PCI_ERS_RESULT_DISCONNECT;
913 
914 	vdev = vfio_device_data(device);
915 	if (vdev == NULL) {
916 		vfio_device_put(device);
917 		return PCI_ERS_RESULT_DISCONNECT;
918 	}
919 
920 	mutex_lock(&vdev->igate);
921 
922 	if (vdev->err_trigger)
923 		eventfd_signal(vdev->err_trigger, 1);
924 
925 	mutex_unlock(&vdev->igate);
926 
927 	vfio_device_put(device);
928 
929 	return PCI_ERS_RESULT_CAN_RECOVER;
930 }
931 
932 static struct pci_error_handlers vfio_err_handlers = {
933 	.error_detected = vfio_pci_aer_err_detected,
934 };
935 
936 static struct pci_driver vfio_pci_driver = {
937 	.name		= "vfio-pci",
938 	.id_table	= NULL, /* only dynamic ids */
939 	.probe		= vfio_pci_probe,
940 	.remove		= vfio_pci_remove,
941 	.err_handler	= &vfio_err_handlers,
942 };
943 
944 struct vfio_devices {
945 	struct vfio_device **devices;
946 	int cur_index;
947 	int max_index;
948 };
949 
950 static int vfio_pci_get_devs(struct pci_dev *pdev, void *data)
951 {
952 	struct vfio_devices *devs = data;
953 	struct pci_driver *pci_drv = ACCESS_ONCE(pdev->driver);
954 
955 	if (pci_drv != &vfio_pci_driver)
956 		return -EBUSY;
957 
958 	if (devs->cur_index == devs->max_index)
959 		return -ENOSPC;
960 
961 	devs->devices[devs->cur_index] = vfio_device_get_from_dev(&pdev->dev);
962 	if (!devs->devices[devs->cur_index])
963 		return -EINVAL;
964 
965 	devs->cur_index++;
966 	return 0;
967 }
968 
969 /*
970  * Attempt to do a bus/slot reset if there are devices affected by a reset for
971  * this device that are needs_reset and all of the affected devices are unused
972  * (!refcnt).  Callers are required to hold driver_lock when calling this to
973  * prevent device opens and concurrent bus reset attempts.  We prevent device
974  * unbinds by acquiring and holding a reference to the vfio_device.
975  *
976  * NB: vfio-core considers a group to be viable even if some devices are
977  * bound to drivers like pci-stub or pcieport.  Here we require all devices
978  * to be bound to vfio_pci since that's the only way we can be sure they
979  * stay put.
980  */
981 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev)
982 {
983 	struct vfio_devices devs = { .cur_index = 0 };
984 	int i = 0, ret = -EINVAL;
985 	bool needs_reset = false, slot = false;
986 	struct vfio_pci_device *tmp;
987 
988 	if (!pci_probe_reset_slot(vdev->pdev->slot))
989 		slot = true;
990 	else if (pci_probe_reset_bus(vdev->pdev->bus))
991 		return;
992 
993 	if (vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
994 					  &i, slot) || !i)
995 		return;
996 
997 	devs.max_index = i;
998 	devs.devices = kcalloc(i, sizeof(struct vfio_device *), GFP_KERNEL);
999 	if (!devs.devices)
1000 		return;
1001 
1002 	if (vfio_pci_for_each_slot_or_bus(vdev->pdev,
1003 					  vfio_pci_get_devs, &devs, slot))
1004 		goto put_devs;
1005 
1006 	for (i = 0; i < devs.cur_index; i++) {
1007 		tmp = vfio_device_data(devs.devices[i]);
1008 		if (tmp->needs_reset)
1009 			needs_reset = true;
1010 		if (tmp->refcnt)
1011 			goto put_devs;
1012 	}
1013 
1014 	if (needs_reset)
1015 		ret = slot ? pci_try_reset_slot(vdev->pdev->slot) :
1016 			     pci_try_reset_bus(vdev->pdev->bus);
1017 
1018 put_devs:
1019 	for (i = 0; i < devs.cur_index; i++) {
1020 		if (!ret) {
1021 			tmp = vfio_device_data(devs.devices[i]);
1022 			tmp->needs_reset = false;
1023 		}
1024 		vfio_device_put(devs.devices[i]);
1025 	}
1026 
1027 	kfree(devs.devices);
1028 }
1029 
1030 static void __exit vfio_pci_cleanup(void)
1031 {
1032 	pci_unregister_driver(&vfio_pci_driver);
1033 	vfio_pci_virqfd_exit();
1034 	vfio_pci_uninit_perm_bits();
1035 }
1036 
1037 static int __init vfio_pci_init(void)
1038 {
1039 	int ret;
1040 
1041 	/* Allocate shared config space permision data used by all devices */
1042 	ret = vfio_pci_init_perm_bits();
1043 	if (ret)
1044 		return ret;
1045 
1046 	/* Start the virqfd cleanup handler */
1047 	ret = vfio_pci_virqfd_init();
1048 	if (ret)
1049 		goto out_virqfd;
1050 
1051 	/* Register and scan for devices */
1052 	ret = pci_register_driver(&vfio_pci_driver);
1053 	if (ret)
1054 		goto out_driver;
1055 
1056 	return 0;
1057 
1058 out_driver:
1059 	vfio_pci_virqfd_exit();
1060 out_virqfd:
1061 	vfio_pci_uninit_perm_bits();
1062 	return ret;
1063 }
1064 
1065 module_init(vfio_pci_init);
1066 module_exit(vfio_pci_cleanup);
1067 
1068 MODULE_VERSION(DRIVER_VERSION);
1069 MODULE_LICENSE("GPL v2");
1070 MODULE_AUTHOR(DRIVER_AUTHOR);
1071 MODULE_DESCRIPTION(DRIVER_DESC);
1072