xref: /openbmc/linux/drivers/vfio/vfio_main.c (revision 913447d0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * VFIO core
4  *
5  * Copyright (C) 2012 Red Hat, Inc.  All rights reserved.
6  *     Author: Alex Williamson <alex.williamson@redhat.com>
7  *
8  * Derived from original vfio:
9  * Copyright 2010 Cisco Systems, Inc.  All rights reserved.
10  * Author: Tom Lyon, pugs@cisco.com
11  */
12 
13 #include <linux/cdev.h>
14 #include <linux/compat.h>
15 #include <linux/device.h>
16 #include <linux/file.h>
17 #include <linux/anon_inodes.h>
18 #include <linux/fs.h>
19 #include <linux/idr.h>
20 #include <linux/iommu.h>
21 #include <linux/list.h>
22 #include <linux/miscdevice.h>
23 #include <linux/module.h>
24 #include <linux/mutex.h>
25 #include <linux/pci.h>
26 #include <linux/rwsem.h>
27 #include <linux/sched.h>
28 #include <linux/slab.h>
29 #include <linux/stat.h>
30 #include <linux/string.h>
31 #include <linux/uaccess.h>
32 #include <linux/vfio.h>
33 #include <linux/wait.h>
34 #include <linux/sched/signal.h>
35 #include <linux/pm_runtime.h>
36 #include <linux/interval_tree.h>
37 #include <linux/iova_bitmap.h>
38 #include "vfio.h"
39 
40 #define DRIVER_VERSION	"0.3"
41 #define DRIVER_AUTHOR	"Alex Williamson <alex.williamson@redhat.com>"
42 #define DRIVER_DESC	"VFIO - User Level meta-driver"
43 
44 static struct vfio {
45 	struct class			*class;
46 	struct list_head		group_list;
47 	struct mutex			group_lock; /* locks group_list */
48 	struct ida			group_ida;
49 	dev_t				group_devt;
50 	struct class			*device_class;
51 	struct ida			device_ida;
52 } vfio;
53 
54 static DEFINE_XARRAY(vfio_device_set_xa);
55 static const struct file_operations vfio_group_fops;
56 
57 int vfio_assign_device_set(struct vfio_device *device, void *set_id)
58 {
59 	unsigned long idx = (unsigned long)set_id;
60 	struct vfio_device_set *new_dev_set;
61 	struct vfio_device_set *dev_set;
62 
63 	if (WARN_ON(!set_id))
64 		return -EINVAL;
65 
66 	/*
67 	 * Atomically acquire a singleton object in the xarray for this set_id
68 	 */
69 	xa_lock(&vfio_device_set_xa);
70 	dev_set = xa_load(&vfio_device_set_xa, idx);
71 	if (dev_set)
72 		goto found_get_ref;
73 	xa_unlock(&vfio_device_set_xa);
74 
75 	new_dev_set = kzalloc(sizeof(*new_dev_set), GFP_KERNEL);
76 	if (!new_dev_set)
77 		return -ENOMEM;
78 	mutex_init(&new_dev_set->lock);
79 	INIT_LIST_HEAD(&new_dev_set->device_list);
80 	new_dev_set->set_id = set_id;
81 
82 	xa_lock(&vfio_device_set_xa);
83 	dev_set = __xa_cmpxchg(&vfio_device_set_xa, idx, NULL, new_dev_set,
84 			       GFP_KERNEL);
85 	if (!dev_set) {
86 		dev_set = new_dev_set;
87 		goto found_get_ref;
88 	}
89 
90 	kfree(new_dev_set);
91 	if (xa_is_err(dev_set)) {
92 		xa_unlock(&vfio_device_set_xa);
93 		return xa_err(dev_set);
94 	}
95 
96 found_get_ref:
97 	dev_set->device_count++;
98 	xa_unlock(&vfio_device_set_xa);
99 	mutex_lock(&dev_set->lock);
100 	device->dev_set = dev_set;
101 	list_add_tail(&device->dev_set_list, &dev_set->device_list);
102 	mutex_unlock(&dev_set->lock);
103 	return 0;
104 }
105 EXPORT_SYMBOL_GPL(vfio_assign_device_set);
106 
107 static void vfio_release_device_set(struct vfio_device *device)
108 {
109 	struct vfio_device_set *dev_set = device->dev_set;
110 
111 	if (!dev_set)
112 		return;
113 
114 	mutex_lock(&dev_set->lock);
115 	list_del(&device->dev_set_list);
116 	mutex_unlock(&dev_set->lock);
117 
118 	xa_lock(&vfio_device_set_xa);
119 	if (!--dev_set->device_count) {
120 		__xa_erase(&vfio_device_set_xa,
121 			   (unsigned long)dev_set->set_id);
122 		mutex_destroy(&dev_set->lock);
123 		kfree(dev_set);
124 	}
125 	xa_unlock(&vfio_device_set_xa);
126 }
127 
128 /*
129  * Group objects - create, release, get, put, search
130  */
131 static struct vfio_group *
132 __vfio_group_get_from_iommu(struct iommu_group *iommu_group)
133 {
134 	struct vfio_group *group;
135 
136 	/*
137 	 * group->iommu_group from the vfio.group_list cannot be NULL
138 	 * under the vfio.group_lock.
139 	 */
140 	list_for_each_entry(group, &vfio.group_list, vfio_next) {
141 		if (group->iommu_group == iommu_group) {
142 			refcount_inc(&group->drivers);
143 			return group;
144 		}
145 	}
146 	return NULL;
147 }
148 
149 static struct vfio_group *
150 vfio_group_get_from_iommu(struct iommu_group *iommu_group)
151 {
152 	struct vfio_group *group;
153 
154 	mutex_lock(&vfio.group_lock);
155 	group = __vfio_group_get_from_iommu(iommu_group);
156 	mutex_unlock(&vfio.group_lock);
157 	return group;
158 }
159 
160 static void vfio_group_release(struct device *dev)
161 {
162 	struct vfio_group *group = container_of(dev, struct vfio_group, dev);
163 
164 	mutex_destroy(&group->device_lock);
165 	mutex_destroy(&group->group_lock);
166 	WARN_ON(group->iommu_group);
167 	ida_free(&vfio.group_ida, MINOR(group->dev.devt));
168 	kfree(group);
169 }
170 
171 static struct vfio_group *vfio_group_alloc(struct iommu_group *iommu_group,
172 					   enum vfio_group_type type)
173 {
174 	struct vfio_group *group;
175 	int minor;
176 
177 	group = kzalloc(sizeof(*group), GFP_KERNEL);
178 	if (!group)
179 		return ERR_PTR(-ENOMEM);
180 
181 	minor = ida_alloc_max(&vfio.group_ida, MINORMASK, GFP_KERNEL);
182 	if (minor < 0) {
183 		kfree(group);
184 		return ERR_PTR(minor);
185 	}
186 
187 	device_initialize(&group->dev);
188 	group->dev.devt = MKDEV(MAJOR(vfio.group_devt), minor);
189 	group->dev.class = vfio.class;
190 	group->dev.release = vfio_group_release;
191 	cdev_init(&group->cdev, &vfio_group_fops);
192 	group->cdev.owner = THIS_MODULE;
193 
194 	refcount_set(&group->drivers, 1);
195 	mutex_init(&group->group_lock);
196 	INIT_LIST_HEAD(&group->device_list);
197 	mutex_init(&group->device_lock);
198 	group->iommu_group = iommu_group;
199 	/* put in vfio_group_release() */
200 	iommu_group_ref_get(iommu_group);
201 	group->type = type;
202 	BLOCKING_INIT_NOTIFIER_HEAD(&group->notifier);
203 
204 	return group;
205 }
206 
207 static struct vfio_group *vfio_create_group(struct iommu_group *iommu_group,
208 		enum vfio_group_type type)
209 {
210 	struct vfio_group *group;
211 	struct vfio_group *ret;
212 	int err;
213 
214 	group = vfio_group_alloc(iommu_group, type);
215 	if (IS_ERR(group))
216 		return group;
217 
218 	err = dev_set_name(&group->dev, "%s%d",
219 			   group->type == VFIO_NO_IOMMU ? "noiommu-" : "",
220 			   iommu_group_id(iommu_group));
221 	if (err) {
222 		ret = ERR_PTR(err);
223 		goto err_put;
224 	}
225 
226 	mutex_lock(&vfio.group_lock);
227 
228 	/* Did we race creating this group? */
229 	ret = __vfio_group_get_from_iommu(iommu_group);
230 	if (ret)
231 		goto err_unlock;
232 
233 	err = cdev_device_add(&group->cdev, &group->dev);
234 	if (err) {
235 		ret = ERR_PTR(err);
236 		goto err_unlock;
237 	}
238 
239 	list_add(&group->vfio_next, &vfio.group_list);
240 
241 	mutex_unlock(&vfio.group_lock);
242 	return group;
243 
244 err_unlock:
245 	mutex_unlock(&vfio.group_lock);
246 err_put:
247 	put_device(&group->dev);
248 	return ret;
249 }
250 
251 static void vfio_device_remove_group(struct vfio_device *device)
252 {
253 	struct vfio_group *group = device->group;
254 	struct iommu_group *iommu_group;
255 
256 	if (group->type == VFIO_NO_IOMMU || group->type == VFIO_EMULATED_IOMMU)
257 		iommu_group_remove_device(device->dev);
258 
259 	/* Pairs with vfio_create_group() / vfio_group_get_from_iommu() */
260 	if (!refcount_dec_and_mutex_lock(&group->drivers, &vfio.group_lock))
261 		return;
262 	list_del(&group->vfio_next);
263 
264 	/*
265 	 * We could concurrently probe another driver in the group that might
266 	 * race vfio_device_remove_group() with vfio_get_group(), so we have to
267 	 * ensure that the sysfs is all cleaned up under lock otherwise the
268 	 * cdev_device_add() will fail due to the name aready existing.
269 	 */
270 	cdev_device_del(&group->cdev, &group->dev);
271 
272 	mutex_lock(&group->group_lock);
273 	/*
274 	 * These data structures all have paired operations that can only be
275 	 * undone when the caller holds a live reference on the device. Since
276 	 * all pairs must be undone these WARN_ON's indicate some caller did not
277 	 * properly hold the group reference.
278 	 */
279 	WARN_ON(!list_empty(&group->device_list));
280 	WARN_ON(group->notifier.head);
281 
282 	/*
283 	 * Revoke all users of group->iommu_group. At this point we know there
284 	 * are no devices active because we are unplugging the last one. Setting
285 	 * iommu_group to NULL blocks all new users.
286 	 */
287 	if (group->container)
288 		vfio_group_detach_container(group);
289 	iommu_group = group->iommu_group;
290 	group->iommu_group = NULL;
291 	mutex_unlock(&group->group_lock);
292 	mutex_unlock(&vfio.group_lock);
293 
294 	iommu_group_put(iommu_group);
295 	put_device(&group->dev);
296 }
297 
298 /*
299  * Device objects - create, release, get, put, search
300  */
301 /* Device reference always implies a group reference */
302 static void vfio_device_put_registration(struct vfio_device *device)
303 {
304 	if (refcount_dec_and_test(&device->refcount))
305 		complete(&device->comp);
306 }
307 
308 static bool vfio_device_try_get_registration(struct vfio_device *device)
309 {
310 	return refcount_inc_not_zero(&device->refcount);
311 }
312 
313 static struct vfio_device *vfio_group_get_device(struct vfio_group *group,
314 						 struct device *dev)
315 {
316 	struct vfio_device *device;
317 
318 	mutex_lock(&group->device_lock);
319 	list_for_each_entry(device, &group->device_list, group_next) {
320 		if (device->dev == dev &&
321 		    vfio_device_try_get_registration(device)) {
322 			mutex_unlock(&group->device_lock);
323 			return device;
324 		}
325 	}
326 	mutex_unlock(&group->device_lock);
327 	return NULL;
328 }
329 
330 /*
331  * VFIO driver API
332  */
333 /* Release helper called by vfio_put_device() */
334 static void vfio_device_release(struct device *dev)
335 {
336 	struct vfio_device *device =
337 			container_of(dev, struct vfio_device, device);
338 
339 	vfio_release_device_set(device);
340 	ida_free(&vfio.device_ida, device->index);
341 
342 	if (device->ops->release)
343 		device->ops->release(device);
344 
345 	kvfree(device);
346 }
347 
348 static int vfio_init_device(struct vfio_device *device, struct device *dev,
349 			    const struct vfio_device_ops *ops);
350 
351 /*
352  * Allocate and initialize vfio_device so it can be registered to vfio
353  * core.
354  *
355  * Drivers should use the wrapper vfio_alloc_device() for allocation.
356  * @size is the size of the structure to be allocated, including any
357  * private data used by the driver.
358  *
359  * Driver may provide an @init callback to cover device private data.
360  *
361  * Use vfio_put_device() to release the structure after success return.
362  */
363 struct vfio_device *_vfio_alloc_device(size_t size, struct device *dev,
364 				       const struct vfio_device_ops *ops)
365 {
366 	struct vfio_device *device;
367 	int ret;
368 
369 	if (WARN_ON(size < sizeof(struct vfio_device)))
370 		return ERR_PTR(-EINVAL);
371 
372 	device = kvzalloc(size, GFP_KERNEL);
373 	if (!device)
374 		return ERR_PTR(-ENOMEM);
375 
376 	ret = vfio_init_device(device, dev, ops);
377 	if (ret)
378 		goto out_free;
379 	return device;
380 
381 out_free:
382 	kvfree(device);
383 	return ERR_PTR(ret);
384 }
385 EXPORT_SYMBOL_GPL(_vfio_alloc_device);
386 
387 /*
388  * Initialize a vfio_device so it can be registered to vfio core.
389  */
390 static int vfio_init_device(struct vfio_device *device, struct device *dev,
391 			    const struct vfio_device_ops *ops)
392 {
393 	int ret;
394 
395 	ret = ida_alloc_max(&vfio.device_ida, MINORMASK, GFP_KERNEL);
396 	if (ret < 0) {
397 		dev_dbg(dev, "Error to alloc index\n");
398 		return ret;
399 	}
400 
401 	device->index = ret;
402 	init_completion(&device->comp);
403 	device->dev = dev;
404 	device->ops = ops;
405 
406 	if (ops->init) {
407 		ret = ops->init(device);
408 		if (ret)
409 			goto out_uninit;
410 	}
411 
412 	device_initialize(&device->device);
413 	device->device.release = vfio_device_release;
414 	device->device.class = vfio.device_class;
415 	device->device.parent = device->dev;
416 	return 0;
417 
418 out_uninit:
419 	vfio_release_device_set(device);
420 	ida_free(&vfio.device_ida, device->index);
421 	return ret;
422 }
423 
424 static struct vfio_group *vfio_noiommu_group_alloc(struct device *dev,
425 		enum vfio_group_type type)
426 {
427 	struct iommu_group *iommu_group;
428 	struct vfio_group *group;
429 	int ret;
430 
431 	iommu_group = iommu_group_alloc();
432 	if (IS_ERR(iommu_group))
433 		return ERR_CAST(iommu_group);
434 
435 	ret = iommu_group_set_name(iommu_group, "vfio-noiommu");
436 	if (ret)
437 		goto out_put_group;
438 	ret = iommu_group_add_device(iommu_group, dev);
439 	if (ret)
440 		goto out_put_group;
441 
442 	group = vfio_create_group(iommu_group, type);
443 	if (IS_ERR(group)) {
444 		ret = PTR_ERR(group);
445 		goto out_remove_device;
446 	}
447 	iommu_group_put(iommu_group);
448 	return group;
449 
450 out_remove_device:
451 	iommu_group_remove_device(dev);
452 out_put_group:
453 	iommu_group_put(iommu_group);
454 	return ERR_PTR(ret);
455 }
456 
457 static struct vfio_group *vfio_group_find_or_alloc(struct device *dev)
458 {
459 	struct iommu_group *iommu_group;
460 	struct vfio_group *group;
461 
462 	iommu_group = iommu_group_get(dev);
463 	if (!iommu_group && vfio_noiommu) {
464 		/*
465 		 * With noiommu enabled, create an IOMMU group for devices that
466 		 * don't already have one, implying no IOMMU hardware/driver
467 		 * exists.  Taint the kernel because we're about to give a DMA
468 		 * capable device to a user without IOMMU protection.
469 		 */
470 		group = vfio_noiommu_group_alloc(dev, VFIO_NO_IOMMU);
471 		if (!IS_ERR(group)) {
472 			add_taint(TAINT_USER, LOCKDEP_STILL_OK);
473 			dev_warn(dev, "Adding kernel taint for vfio-noiommu group on device\n");
474 		}
475 		return group;
476 	}
477 
478 	if (!iommu_group)
479 		return ERR_PTR(-EINVAL);
480 
481 	/*
482 	 * VFIO always sets IOMMU_CACHE because we offer no way for userspace to
483 	 * restore cache coherency. It has to be checked here because it is only
484 	 * valid for cases where we are using iommu groups.
485 	 */
486 	if (!device_iommu_capable(dev, IOMMU_CAP_CACHE_COHERENCY)) {
487 		iommu_group_put(iommu_group);
488 		return ERR_PTR(-EINVAL);
489 	}
490 
491 	group = vfio_group_get_from_iommu(iommu_group);
492 	if (!group)
493 		group = vfio_create_group(iommu_group, VFIO_IOMMU);
494 
495 	/* The vfio_group holds a reference to the iommu_group */
496 	iommu_group_put(iommu_group);
497 	return group;
498 }
499 
500 static int __vfio_register_dev(struct vfio_device *device,
501 		struct vfio_group *group)
502 {
503 	struct vfio_device *existing_device;
504 	int ret;
505 
506 	/*
507 	 * In all cases group is the output of one of the group allocation
508 	 * functions and we have group->drivers incremented for us.
509 	 */
510 	if (IS_ERR(group))
511 		return PTR_ERR(group);
512 
513 	/*
514 	 * If the driver doesn't specify a set then the device is added to a
515 	 * singleton set just for itself.
516 	 */
517 	if (!device->dev_set)
518 		vfio_assign_device_set(device, device);
519 
520 	existing_device = vfio_group_get_device(group, device->dev);
521 	if (existing_device) {
522 		/*
523 		 * group->iommu_group is non-NULL because we hold the drivers
524 		 * refcount.
525 		 */
526 		dev_WARN(device->dev, "Device already exists on group %d\n",
527 			 iommu_group_id(group->iommu_group));
528 		vfio_device_put_registration(existing_device);
529 		ret = -EBUSY;
530 		goto err_out;
531 	}
532 
533 	/* Our reference on group is moved to the device */
534 	device->group = group;
535 
536 	ret = dev_set_name(&device->device, "vfio%d", device->index);
537 	if (ret)
538 		goto err_out;
539 
540 	ret = device_add(&device->device);
541 	if (ret)
542 		goto err_out;
543 
544 	/* Refcounting can't start until the driver calls register */
545 	refcount_set(&device->refcount, 1);
546 
547 	mutex_lock(&group->device_lock);
548 	list_add(&device->group_next, &group->device_list);
549 	mutex_unlock(&group->device_lock);
550 
551 	return 0;
552 err_out:
553 	vfio_device_remove_group(device);
554 	return ret;
555 }
556 
557 int vfio_register_group_dev(struct vfio_device *device)
558 {
559 	return __vfio_register_dev(device,
560 		vfio_group_find_or_alloc(device->dev));
561 }
562 EXPORT_SYMBOL_GPL(vfio_register_group_dev);
563 
564 /*
565  * Register a virtual device without IOMMU backing.  The user of this
566  * device must not be able to directly trigger unmediated DMA.
567  */
568 int vfio_register_emulated_iommu_dev(struct vfio_device *device)
569 {
570 	return __vfio_register_dev(device,
571 		vfio_noiommu_group_alloc(device->dev, VFIO_EMULATED_IOMMU));
572 }
573 EXPORT_SYMBOL_GPL(vfio_register_emulated_iommu_dev);
574 
575 static struct vfio_device *vfio_device_get_from_name(struct vfio_group *group,
576 						     char *buf)
577 {
578 	struct vfio_device *it, *device = ERR_PTR(-ENODEV);
579 
580 	mutex_lock(&group->device_lock);
581 	list_for_each_entry(it, &group->device_list, group_next) {
582 		int ret;
583 
584 		if (it->ops->match) {
585 			ret = it->ops->match(it, buf);
586 			if (ret < 0) {
587 				device = ERR_PTR(ret);
588 				break;
589 			}
590 		} else {
591 			ret = !strcmp(dev_name(it->dev), buf);
592 		}
593 
594 		if (ret && vfio_device_try_get_registration(it)) {
595 			device = it;
596 			break;
597 		}
598 	}
599 	mutex_unlock(&group->device_lock);
600 
601 	return device;
602 }
603 
604 /*
605  * Decrement the device reference count and wait for the device to be
606  * removed.  Open file descriptors for the device... */
607 void vfio_unregister_group_dev(struct vfio_device *device)
608 {
609 	struct vfio_group *group = device->group;
610 	unsigned int i = 0;
611 	bool interrupted = false;
612 	long rc;
613 
614 	vfio_device_put_registration(device);
615 	rc = try_wait_for_completion(&device->comp);
616 	while (rc <= 0) {
617 		if (device->ops->request)
618 			device->ops->request(device, i++);
619 
620 		if (interrupted) {
621 			rc = wait_for_completion_timeout(&device->comp,
622 							 HZ * 10);
623 		} else {
624 			rc = wait_for_completion_interruptible_timeout(
625 				&device->comp, HZ * 10);
626 			if (rc < 0) {
627 				interrupted = true;
628 				dev_warn(device->dev,
629 					 "Device is currently in use, task"
630 					 " \"%s\" (%d) "
631 					 "blocked until device is released",
632 					 current->comm, task_pid_nr(current));
633 			}
634 		}
635 	}
636 
637 	mutex_lock(&group->device_lock);
638 	list_del(&device->group_next);
639 	mutex_unlock(&group->device_lock);
640 
641 	/* Balances device_add in register path */
642 	device_del(&device->device);
643 
644 	vfio_device_remove_group(device);
645 }
646 EXPORT_SYMBOL_GPL(vfio_unregister_group_dev);
647 
648 /*
649  * VFIO Group fd, /dev/vfio/$GROUP
650  */
651 /*
652  * VFIO_GROUP_UNSET_CONTAINER should fail if there are other users or
653  * if there was no container to unset.  Since the ioctl is called on
654  * the group, we know that still exists, therefore the only valid
655  * transition here is 1->0.
656  */
657 static int vfio_group_ioctl_unset_container(struct vfio_group *group)
658 {
659 	int ret = 0;
660 
661 	mutex_lock(&group->group_lock);
662 	if (!group->container) {
663 		ret = -EINVAL;
664 		goto out_unlock;
665 	}
666 	if (group->container_users != 1) {
667 		ret = -EBUSY;
668 		goto out_unlock;
669 	}
670 	vfio_group_detach_container(group);
671 
672 out_unlock:
673 	mutex_unlock(&group->group_lock);
674 	return ret;
675 }
676 
677 static int vfio_group_ioctl_set_container(struct vfio_group *group,
678 					  int __user *arg)
679 {
680 	struct vfio_container *container;
681 	struct fd f;
682 	int ret;
683 	int fd;
684 
685 	if (get_user(fd, arg))
686 		return -EFAULT;
687 
688 	f = fdget(fd);
689 	if (!f.file)
690 		return -EBADF;
691 
692 	mutex_lock(&group->group_lock);
693 	if (group->container || WARN_ON(group->container_users)) {
694 		ret = -EINVAL;
695 		goto out_unlock;
696 	}
697 	if (!group->iommu_group) {
698 		ret = -ENODEV;
699 		goto out_unlock;
700 	}
701 
702 	container = vfio_container_from_file(f.file);
703 	ret = -EINVAL;
704 	if (container) {
705 		ret = vfio_container_attach_group(container, group);
706 		goto out_unlock;
707 	}
708 
709 out_unlock:
710 	mutex_unlock(&group->group_lock);
711 	fdput(f);
712 	return ret;
713 }
714 
715 static const struct file_operations vfio_device_fops;
716 
717 /* true if the vfio_device has open_device() called but not close_device() */
718 bool vfio_assert_device_open(struct vfio_device *device)
719 {
720 	return !WARN_ON_ONCE(!READ_ONCE(device->open_count));
721 }
722 
723 static struct file *vfio_device_open(struct vfio_device *device)
724 {
725 	struct file *filep;
726 	int ret;
727 
728 	mutex_lock(&device->group->group_lock);
729 	ret = vfio_device_assign_container(device);
730 	mutex_unlock(&device->group->group_lock);
731 	if (ret)
732 		return ERR_PTR(ret);
733 
734 	if (!try_module_get(device->dev->driver->owner)) {
735 		ret = -ENODEV;
736 		goto err_unassign_container;
737 	}
738 
739 	mutex_lock(&device->dev_set->lock);
740 	device->open_count++;
741 	if (device->open_count == 1) {
742 		/*
743 		 * Here we pass the KVM pointer with the group under the read
744 		 * lock.  If the device driver will use it, it must obtain a
745 		 * reference and release it during close_device.
746 		 */
747 		mutex_lock(&device->group->group_lock);
748 		device->kvm = device->group->kvm;
749 
750 		if (device->ops->open_device) {
751 			ret = device->ops->open_device(device);
752 			if (ret)
753 				goto err_undo_count;
754 		}
755 		vfio_device_container_register(device);
756 		mutex_unlock(&device->group->group_lock);
757 	}
758 	mutex_unlock(&device->dev_set->lock);
759 
760 	/*
761 	 * We can't use anon_inode_getfd() because we need to modify
762 	 * the f_mode flags directly to allow more than just ioctls
763 	 */
764 	filep = anon_inode_getfile("[vfio-device]", &vfio_device_fops,
765 				   device, O_RDWR);
766 	if (IS_ERR(filep)) {
767 		ret = PTR_ERR(filep);
768 		goto err_close_device;
769 	}
770 
771 	/*
772 	 * TODO: add an anon_inode interface to do this.
773 	 * Appears to be missing by lack of need rather than
774 	 * explicitly prevented.  Now there's need.
775 	 */
776 	filep->f_mode |= (FMODE_PREAD | FMODE_PWRITE);
777 
778 	if (device->group->type == VFIO_NO_IOMMU)
779 		dev_warn(device->dev, "vfio-noiommu device opened by user "
780 			 "(%s:%d)\n", current->comm, task_pid_nr(current));
781 	/*
782 	 * On success the ref of device is moved to the file and
783 	 * put in vfio_device_fops_release()
784 	 */
785 	return filep;
786 
787 err_close_device:
788 	mutex_lock(&device->dev_set->lock);
789 	mutex_lock(&device->group->group_lock);
790 	if (device->open_count == 1 && device->ops->close_device) {
791 		device->ops->close_device(device);
792 
793 		vfio_device_container_unregister(device);
794 	}
795 err_undo_count:
796 	mutex_unlock(&device->group->group_lock);
797 	device->open_count--;
798 	if (device->open_count == 0 && device->kvm)
799 		device->kvm = NULL;
800 	mutex_unlock(&device->dev_set->lock);
801 	module_put(device->dev->driver->owner);
802 err_unassign_container:
803 	vfio_device_unassign_container(device);
804 	return ERR_PTR(ret);
805 }
806 
807 static int vfio_group_ioctl_get_device_fd(struct vfio_group *group,
808 					  char __user *arg)
809 {
810 	struct vfio_device *device;
811 	struct file *filep;
812 	char *buf;
813 	int fdno;
814 	int ret;
815 
816 	buf = strndup_user(arg, PAGE_SIZE);
817 	if (IS_ERR(buf))
818 		return PTR_ERR(buf);
819 
820 	device = vfio_device_get_from_name(group, buf);
821 	kfree(buf);
822 	if (IS_ERR(device))
823 		return PTR_ERR(device);
824 
825 	fdno = get_unused_fd_flags(O_CLOEXEC);
826 	if (fdno < 0) {
827 		ret = fdno;
828 		goto err_put_device;
829 	}
830 
831 	filep = vfio_device_open(device);
832 	if (IS_ERR(filep)) {
833 		ret = PTR_ERR(filep);
834 		goto err_put_fdno;
835 	}
836 
837 	fd_install(fdno, filep);
838 	return fdno;
839 
840 err_put_fdno:
841 	put_unused_fd(fdno);
842 err_put_device:
843 	vfio_device_put_registration(device);
844 	return ret;
845 }
846 
847 static int vfio_group_ioctl_get_status(struct vfio_group *group,
848 				       struct vfio_group_status __user *arg)
849 {
850 	unsigned long minsz = offsetofend(struct vfio_group_status, flags);
851 	struct vfio_group_status status;
852 
853 	if (copy_from_user(&status, arg, minsz))
854 		return -EFAULT;
855 
856 	if (status.argsz < minsz)
857 		return -EINVAL;
858 
859 	status.flags = 0;
860 
861 	mutex_lock(&group->group_lock);
862 	if (!group->iommu_group) {
863 		mutex_unlock(&group->group_lock);
864 		return -ENODEV;
865 	}
866 
867 	if (group->container)
868 		status.flags |= VFIO_GROUP_FLAGS_CONTAINER_SET |
869 				VFIO_GROUP_FLAGS_VIABLE;
870 	else if (!iommu_group_dma_owner_claimed(group->iommu_group))
871 		status.flags |= VFIO_GROUP_FLAGS_VIABLE;
872 	mutex_unlock(&group->group_lock);
873 
874 	if (copy_to_user(arg, &status, minsz))
875 		return -EFAULT;
876 	return 0;
877 }
878 
879 static long vfio_group_fops_unl_ioctl(struct file *filep,
880 				      unsigned int cmd, unsigned long arg)
881 {
882 	struct vfio_group *group = filep->private_data;
883 	void __user *uarg = (void __user *)arg;
884 
885 	switch (cmd) {
886 	case VFIO_GROUP_GET_DEVICE_FD:
887 		return vfio_group_ioctl_get_device_fd(group, uarg);
888 	case VFIO_GROUP_GET_STATUS:
889 		return vfio_group_ioctl_get_status(group, uarg);
890 	case VFIO_GROUP_SET_CONTAINER:
891 		return vfio_group_ioctl_set_container(group, uarg);
892 	case VFIO_GROUP_UNSET_CONTAINER:
893 		return vfio_group_ioctl_unset_container(group);
894 	default:
895 		return -ENOTTY;
896 	}
897 }
898 
899 static int vfio_group_fops_open(struct inode *inode, struct file *filep)
900 {
901 	struct vfio_group *group =
902 		container_of(inode->i_cdev, struct vfio_group, cdev);
903 	int ret;
904 
905 	mutex_lock(&group->group_lock);
906 
907 	/*
908 	 * drivers can be zero if this races with vfio_device_remove_group(), it
909 	 * will be stable at 0 under the group rwsem
910 	 */
911 	if (refcount_read(&group->drivers) == 0) {
912 		ret = -ENODEV;
913 		goto out_unlock;
914 	}
915 
916 	if (group->type == VFIO_NO_IOMMU && !capable(CAP_SYS_RAWIO)) {
917 		ret = -EPERM;
918 		goto out_unlock;
919 	}
920 
921 	/*
922 	 * Do we need multiple instances of the group open?  Seems not.
923 	 */
924 	if (group->opened_file) {
925 		ret = -EBUSY;
926 		goto out_unlock;
927 	}
928 	group->opened_file = filep;
929 	filep->private_data = group;
930 	ret = 0;
931 out_unlock:
932 	mutex_unlock(&group->group_lock);
933 	return ret;
934 }
935 
936 static int vfio_group_fops_release(struct inode *inode, struct file *filep)
937 {
938 	struct vfio_group *group = filep->private_data;
939 
940 	filep->private_data = NULL;
941 
942 	mutex_lock(&group->group_lock);
943 	/*
944 	 * Device FDs hold a group file reference, therefore the group release
945 	 * is only called when there are no open devices.
946 	 */
947 	WARN_ON(group->notifier.head);
948 	if (group->container)
949 		vfio_group_detach_container(group);
950 	group->opened_file = NULL;
951 	mutex_unlock(&group->group_lock);
952 	return 0;
953 }
954 
955 static const struct file_operations vfio_group_fops = {
956 	.owner		= THIS_MODULE,
957 	.unlocked_ioctl	= vfio_group_fops_unl_ioctl,
958 	.compat_ioctl	= compat_ptr_ioctl,
959 	.open		= vfio_group_fops_open,
960 	.release	= vfio_group_fops_release,
961 };
962 
963 /*
964  * Wrapper around pm_runtime_resume_and_get().
965  * Return error code on failure or 0 on success.
966  */
967 static inline int vfio_device_pm_runtime_get(struct vfio_device *device)
968 {
969 	struct device *dev = device->dev;
970 
971 	if (dev->driver && dev->driver->pm) {
972 		int ret;
973 
974 		ret = pm_runtime_resume_and_get(dev);
975 		if (ret) {
976 			dev_info_ratelimited(dev,
977 				"vfio: runtime resume failed %d\n", ret);
978 			return -EIO;
979 		}
980 	}
981 
982 	return 0;
983 }
984 
985 /*
986  * Wrapper around pm_runtime_put().
987  */
988 static inline void vfio_device_pm_runtime_put(struct vfio_device *device)
989 {
990 	struct device *dev = device->dev;
991 
992 	if (dev->driver && dev->driver->pm)
993 		pm_runtime_put(dev);
994 }
995 
996 /*
997  * VFIO Device fd
998  */
999 static int vfio_device_fops_release(struct inode *inode, struct file *filep)
1000 {
1001 	struct vfio_device *device = filep->private_data;
1002 
1003 	mutex_lock(&device->dev_set->lock);
1004 	vfio_assert_device_open(device);
1005 	mutex_lock(&device->group->group_lock);
1006 	if (device->open_count == 1 && device->ops->close_device)
1007 		device->ops->close_device(device);
1008 
1009 	vfio_device_container_unregister(device);
1010 	mutex_unlock(&device->group->group_lock);
1011 	device->open_count--;
1012 	if (device->open_count == 0)
1013 		device->kvm = NULL;
1014 	mutex_unlock(&device->dev_set->lock);
1015 
1016 	module_put(device->dev->driver->owner);
1017 
1018 	vfio_device_unassign_container(device);
1019 
1020 	vfio_device_put_registration(device);
1021 
1022 	return 0;
1023 }
1024 
1025 /*
1026  * vfio_mig_get_next_state - Compute the next step in the FSM
1027  * @cur_fsm - The current state the device is in
1028  * @new_fsm - The target state to reach
1029  * @next_fsm - Pointer to the next step to get to new_fsm
1030  *
1031  * Return 0 upon success, otherwise -errno
1032  * Upon success the next step in the state progression between cur_fsm and
1033  * new_fsm will be set in next_fsm.
1034  *
1035  * This breaks down requests for combination transitions into smaller steps and
1036  * returns the next step to get to new_fsm. The function may need to be called
1037  * multiple times before reaching new_fsm.
1038  *
1039  */
1040 int vfio_mig_get_next_state(struct vfio_device *device,
1041 			    enum vfio_device_mig_state cur_fsm,
1042 			    enum vfio_device_mig_state new_fsm,
1043 			    enum vfio_device_mig_state *next_fsm)
1044 {
1045 	enum { VFIO_DEVICE_NUM_STATES = VFIO_DEVICE_STATE_RUNNING_P2P + 1 };
1046 	/*
1047 	 * The coding in this table requires the driver to implement the
1048 	 * following FSM arcs:
1049 	 *         RESUMING -> STOP
1050 	 *         STOP -> RESUMING
1051 	 *         STOP -> STOP_COPY
1052 	 *         STOP_COPY -> STOP
1053 	 *
1054 	 * If P2P is supported then the driver must also implement these FSM
1055 	 * arcs:
1056 	 *         RUNNING -> RUNNING_P2P
1057 	 *         RUNNING_P2P -> RUNNING
1058 	 *         RUNNING_P2P -> STOP
1059 	 *         STOP -> RUNNING_P2P
1060 	 * Without P2P the driver must implement:
1061 	 *         RUNNING -> STOP
1062 	 *         STOP -> RUNNING
1063 	 *
1064 	 * The coding will step through multiple states for some combination
1065 	 * transitions; if all optional features are supported, this means the
1066 	 * following ones:
1067 	 *         RESUMING -> STOP -> RUNNING_P2P
1068 	 *         RESUMING -> STOP -> RUNNING_P2P -> RUNNING
1069 	 *         RESUMING -> STOP -> STOP_COPY
1070 	 *         RUNNING -> RUNNING_P2P -> STOP
1071 	 *         RUNNING -> RUNNING_P2P -> STOP -> RESUMING
1072 	 *         RUNNING -> RUNNING_P2P -> STOP -> STOP_COPY
1073 	 *         RUNNING_P2P -> STOP -> RESUMING
1074 	 *         RUNNING_P2P -> STOP -> STOP_COPY
1075 	 *         STOP -> RUNNING_P2P -> RUNNING
1076 	 *         STOP_COPY -> STOP -> RESUMING
1077 	 *         STOP_COPY -> STOP -> RUNNING_P2P
1078 	 *         STOP_COPY -> STOP -> RUNNING_P2P -> RUNNING
1079 	 */
1080 	static const u8 vfio_from_fsm_table[VFIO_DEVICE_NUM_STATES][VFIO_DEVICE_NUM_STATES] = {
1081 		[VFIO_DEVICE_STATE_STOP] = {
1082 			[VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_STOP,
1083 			[VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_RUNNING_P2P,
1084 			[VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP_COPY,
1085 			[VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_RESUMING,
1086 			[VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_RUNNING_P2P,
1087 			[VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
1088 		},
1089 		[VFIO_DEVICE_STATE_RUNNING] = {
1090 			[VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_RUNNING_P2P,
1091 			[VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_RUNNING,
1092 			[VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_RUNNING_P2P,
1093 			[VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_RUNNING_P2P,
1094 			[VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_RUNNING_P2P,
1095 			[VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
1096 		},
1097 		[VFIO_DEVICE_STATE_STOP_COPY] = {
1098 			[VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_STOP,
1099 			[VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_STOP,
1100 			[VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP_COPY,
1101 			[VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_STOP,
1102 			[VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_STOP,
1103 			[VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
1104 		},
1105 		[VFIO_DEVICE_STATE_RESUMING] = {
1106 			[VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_STOP,
1107 			[VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_STOP,
1108 			[VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP,
1109 			[VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_RESUMING,
1110 			[VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_STOP,
1111 			[VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
1112 		},
1113 		[VFIO_DEVICE_STATE_RUNNING_P2P] = {
1114 			[VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_STOP,
1115 			[VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_RUNNING,
1116 			[VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP,
1117 			[VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_STOP,
1118 			[VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_RUNNING_P2P,
1119 			[VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
1120 		},
1121 		[VFIO_DEVICE_STATE_ERROR] = {
1122 			[VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_ERROR,
1123 			[VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_ERROR,
1124 			[VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_ERROR,
1125 			[VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_ERROR,
1126 			[VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_ERROR,
1127 			[VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
1128 		},
1129 	};
1130 
1131 	static const unsigned int state_flags_table[VFIO_DEVICE_NUM_STATES] = {
1132 		[VFIO_DEVICE_STATE_STOP] = VFIO_MIGRATION_STOP_COPY,
1133 		[VFIO_DEVICE_STATE_RUNNING] = VFIO_MIGRATION_STOP_COPY,
1134 		[VFIO_DEVICE_STATE_STOP_COPY] = VFIO_MIGRATION_STOP_COPY,
1135 		[VFIO_DEVICE_STATE_RESUMING] = VFIO_MIGRATION_STOP_COPY,
1136 		[VFIO_DEVICE_STATE_RUNNING_P2P] =
1137 			VFIO_MIGRATION_STOP_COPY | VFIO_MIGRATION_P2P,
1138 		[VFIO_DEVICE_STATE_ERROR] = ~0U,
1139 	};
1140 
1141 	if (WARN_ON(cur_fsm >= ARRAY_SIZE(vfio_from_fsm_table) ||
1142 		    (state_flags_table[cur_fsm] & device->migration_flags) !=
1143 			state_flags_table[cur_fsm]))
1144 		return -EINVAL;
1145 
1146 	if (new_fsm >= ARRAY_SIZE(vfio_from_fsm_table) ||
1147 	   (state_flags_table[new_fsm] & device->migration_flags) !=
1148 			state_flags_table[new_fsm])
1149 		return -EINVAL;
1150 
1151 	/*
1152 	 * Arcs touching optional and unsupported states are skipped over. The
1153 	 * driver will instead see an arc from the original state to the next
1154 	 * logical state, as per the above comment.
1155 	 */
1156 	*next_fsm = vfio_from_fsm_table[cur_fsm][new_fsm];
1157 	while ((state_flags_table[*next_fsm] & device->migration_flags) !=
1158 			state_flags_table[*next_fsm])
1159 		*next_fsm = vfio_from_fsm_table[*next_fsm][new_fsm];
1160 
1161 	return (*next_fsm != VFIO_DEVICE_STATE_ERROR) ? 0 : -EINVAL;
1162 }
1163 EXPORT_SYMBOL_GPL(vfio_mig_get_next_state);
1164 
1165 /*
1166  * Convert the drivers's struct file into a FD number and return it to userspace
1167  */
1168 static int vfio_ioct_mig_return_fd(struct file *filp, void __user *arg,
1169 				   struct vfio_device_feature_mig_state *mig)
1170 {
1171 	int ret;
1172 	int fd;
1173 
1174 	fd = get_unused_fd_flags(O_CLOEXEC);
1175 	if (fd < 0) {
1176 		ret = fd;
1177 		goto out_fput;
1178 	}
1179 
1180 	mig->data_fd = fd;
1181 	if (copy_to_user(arg, mig, sizeof(*mig))) {
1182 		ret = -EFAULT;
1183 		goto out_put_unused;
1184 	}
1185 	fd_install(fd, filp);
1186 	return 0;
1187 
1188 out_put_unused:
1189 	put_unused_fd(fd);
1190 out_fput:
1191 	fput(filp);
1192 	return ret;
1193 }
1194 
1195 static int
1196 vfio_ioctl_device_feature_mig_device_state(struct vfio_device *device,
1197 					   u32 flags, void __user *arg,
1198 					   size_t argsz)
1199 {
1200 	size_t minsz =
1201 		offsetofend(struct vfio_device_feature_mig_state, data_fd);
1202 	struct vfio_device_feature_mig_state mig;
1203 	struct file *filp = NULL;
1204 	int ret;
1205 
1206 	if (!device->mig_ops)
1207 		return -ENOTTY;
1208 
1209 	ret = vfio_check_feature(flags, argsz,
1210 				 VFIO_DEVICE_FEATURE_SET |
1211 				 VFIO_DEVICE_FEATURE_GET,
1212 				 sizeof(mig));
1213 	if (ret != 1)
1214 		return ret;
1215 
1216 	if (copy_from_user(&mig, arg, minsz))
1217 		return -EFAULT;
1218 
1219 	if (flags & VFIO_DEVICE_FEATURE_GET) {
1220 		enum vfio_device_mig_state curr_state;
1221 
1222 		ret = device->mig_ops->migration_get_state(device,
1223 							   &curr_state);
1224 		if (ret)
1225 			return ret;
1226 		mig.device_state = curr_state;
1227 		goto out_copy;
1228 	}
1229 
1230 	/* Handle the VFIO_DEVICE_FEATURE_SET */
1231 	filp = device->mig_ops->migration_set_state(device, mig.device_state);
1232 	if (IS_ERR(filp) || !filp)
1233 		goto out_copy;
1234 
1235 	return vfio_ioct_mig_return_fd(filp, arg, &mig);
1236 out_copy:
1237 	mig.data_fd = -1;
1238 	if (copy_to_user(arg, &mig, sizeof(mig)))
1239 		return -EFAULT;
1240 	if (IS_ERR(filp))
1241 		return PTR_ERR(filp);
1242 	return 0;
1243 }
1244 
1245 static int vfio_ioctl_device_feature_migration(struct vfio_device *device,
1246 					       u32 flags, void __user *arg,
1247 					       size_t argsz)
1248 {
1249 	struct vfio_device_feature_migration mig = {
1250 		.flags = device->migration_flags,
1251 	};
1252 	int ret;
1253 
1254 	if (!device->mig_ops)
1255 		return -ENOTTY;
1256 
1257 	ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_GET,
1258 				 sizeof(mig));
1259 	if (ret != 1)
1260 		return ret;
1261 	if (copy_to_user(arg, &mig, sizeof(mig)))
1262 		return -EFAULT;
1263 	return 0;
1264 }
1265 
1266 /* Ranges should fit into a single kernel page */
1267 #define LOG_MAX_RANGES \
1268 	(PAGE_SIZE / sizeof(struct vfio_device_feature_dma_logging_range))
1269 
1270 static int
1271 vfio_ioctl_device_feature_logging_start(struct vfio_device *device,
1272 					u32 flags, void __user *arg,
1273 					size_t argsz)
1274 {
1275 	size_t minsz =
1276 		offsetofend(struct vfio_device_feature_dma_logging_control,
1277 			    ranges);
1278 	struct vfio_device_feature_dma_logging_range __user *ranges;
1279 	struct vfio_device_feature_dma_logging_control control;
1280 	struct vfio_device_feature_dma_logging_range range;
1281 	struct rb_root_cached root = RB_ROOT_CACHED;
1282 	struct interval_tree_node *nodes;
1283 	u64 iova_end;
1284 	u32 nnodes;
1285 	int i, ret;
1286 
1287 	if (!device->log_ops)
1288 		return -ENOTTY;
1289 
1290 	ret = vfio_check_feature(flags, argsz,
1291 				 VFIO_DEVICE_FEATURE_SET,
1292 				 sizeof(control));
1293 	if (ret != 1)
1294 		return ret;
1295 
1296 	if (copy_from_user(&control, arg, minsz))
1297 		return -EFAULT;
1298 
1299 	nnodes = control.num_ranges;
1300 	if (!nnodes)
1301 		return -EINVAL;
1302 
1303 	if (nnodes > LOG_MAX_RANGES)
1304 		return -E2BIG;
1305 
1306 	ranges = u64_to_user_ptr(control.ranges);
1307 	nodes = kmalloc_array(nnodes, sizeof(struct interval_tree_node),
1308 			      GFP_KERNEL);
1309 	if (!nodes)
1310 		return -ENOMEM;
1311 
1312 	for (i = 0; i < nnodes; i++) {
1313 		if (copy_from_user(&range, &ranges[i], sizeof(range))) {
1314 			ret = -EFAULT;
1315 			goto end;
1316 		}
1317 		if (!IS_ALIGNED(range.iova, control.page_size) ||
1318 		    !IS_ALIGNED(range.length, control.page_size)) {
1319 			ret = -EINVAL;
1320 			goto end;
1321 		}
1322 
1323 		if (check_add_overflow(range.iova, range.length, &iova_end) ||
1324 		    iova_end > ULONG_MAX) {
1325 			ret = -EOVERFLOW;
1326 			goto end;
1327 		}
1328 
1329 		nodes[i].start = range.iova;
1330 		nodes[i].last = range.iova + range.length - 1;
1331 		if (interval_tree_iter_first(&root, nodes[i].start,
1332 					     nodes[i].last)) {
1333 			/* Range overlapping */
1334 			ret = -EINVAL;
1335 			goto end;
1336 		}
1337 		interval_tree_insert(nodes + i, &root);
1338 	}
1339 
1340 	ret = device->log_ops->log_start(device, &root, nnodes,
1341 					 &control.page_size);
1342 	if (ret)
1343 		goto end;
1344 
1345 	if (copy_to_user(arg, &control, sizeof(control))) {
1346 		ret = -EFAULT;
1347 		device->log_ops->log_stop(device);
1348 	}
1349 
1350 end:
1351 	kfree(nodes);
1352 	return ret;
1353 }
1354 
1355 static int
1356 vfio_ioctl_device_feature_logging_stop(struct vfio_device *device,
1357 				       u32 flags, void __user *arg,
1358 				       size_t argsz)
1359 {
1360 	int ret;
1361 
1362 	if (!device->log_ops)
1363 		return -ENOTTY;
1364 
1365 	ret = vfio_check_feature(flags, argsz,
1366 				 VFIO_DEVICE_FEATURE_SET, 0);
1367 	if (ret != 1)
1368 		return ret;
1369 
1370 	return device->log_ops->log_stop(device);
1371 }
1372 
1373 static int vfio_device_log_read_and_clear(struct iova_bitmap *iter,
1374 					  unsigned long iova, size_t length,
1375 					  void *opaque)
1376 {
1377 	struct vfio_device *device = opaque;
1378 
1379 	return device->log_ops->log_read_and_clear(device, iova, length, iter);
1380 }
1381 
1382 static int
1383 vfio_ioctl_device_feature_logging_report(struct vfio_device *device,
1384 					 u32 flags, void __user *arg,
1385 					 size_t argsz)
1386 {
1387 	size_t minsz =
1388 		offsetofend(struct vfio_device_feature_dma_logging_report,
1389 			    bitmap);
1390 	struct vfio_device_feature_dma_logging_report report;
1391 	struct iova_bitmap *iter;
1392 	u64 iova_end;
1393 	int ret;
1394 
1395 	if (!device->log_ops)
1396 		return -ENOTTY;
1397 
1398 	ret = vfio_check_feature(flags, argsz,
1399 				 VFIO_DEVICE_FEATURE_GET,
1400 				 sizeof(report));
1401 	if (ret != 1)
1402 		return ret;
1403 
1404 	if (copy_from_user(&report, arg, minsz))
1405 		return -EFAULT;
1406 
1407 	if (report.page_size < SZ_4K || !is_power_of_2(report.page_size))
1408 		return -EINVAL;
1409 
1410 	if (check_add_overflow(report.iova, report.length, &iova_end) ||
1411 	    iova_end > ULONG_MAX)
1412 		return -EOVERFLOW;
1413 
1414 	iter = iova_bitmap_alloc(report.iova, report.length,
1415 				 report.page_size,
1416 				 u64_to_user_ptr(report.bitmap));
1417 	if (IS_ERR(iter))
1418 		return PTR_ERR(iter);
1419 
1420 	ret = iova_bitmap_for_each(iter, device,
1421 				   vfio_device_log_read_and_clear);
1422 
1423 	iova_bitmap_free(iter);
1424 	return ret;
1425 }
1426 
1427 static int vfio_ioctl_device_feature(struct vfio_device *device,
1428 				     struct vfio_device_feature __user *arg)
1429 {
1430 	size_t minsz = offsetofend(struct vfio_device_feature, flags);
1431 	struct vfio_device_feature feature;
1432 
1433 	if (copy_from_user(&feature, arg, minsz))
1434 		return -EFAULT;
1435 
1436 	if (feature.argsz < minsz)
1437 		return -EINVAL;
1438 
1439 	/* Check unknown flags */
1440 	if (feature.flags &
1441 	    ~(VFIO_DEVICE_FEATURE_MASK | VFIO_DEVICE_FEATURE_SET |
1442 	      VFIO_DEVICE_FEATURE_GET | VFIO_DEVICE_FEATURE_PROBE))
1443 		return -EINVAL;
1444 
1445 	/* GET & SET are mutually exclusive except with PROBE */
1446 	if (!(feature.flags & VFIO_DEVICE_FEATURE_PROBE) &&
1447 	    (feature.flags & VFIO_DEVICE_FEATURE_SET) &&
1448 	    (feature.flags & VFIO_DEVICE_FEATURE_GET))
1449 		return -EINVAL;
1450 
1451 	switch (feature.flags & VFIO_DEVICE_FEATURE_MASK) {
1452 	case VFIO_DEVICE_FEATURE_MIGRATION:
1453 		return vfio_ioctl_device_feature_migration(
1454 			device, feature.flags, arg->data,
1455 			feature.argsz - minsz);
1456 	case VFIO_DEVICE_FEATURE_MIG_DEVICE_STATE:
1457 		return vfio_ioctl_device_feature_mig_device_state(
1458 			device, feature.flags, arg->data,
1459 			feature.argsz - minsz);
1460 	case VFIO_DEVICE_FEATURE_DMA_LOGGING_START:
1461 		return vfio_ioctl_device_feature_logging_start(
1462 			device, feature.flags, arg->data,
1463 			feature.argsz - minsz);
1464 	case VFIO_DEVICE_FEATURE_DMA_LOGGING_STOP:
1465 		return vfio_ioctl_device_feature_logging_stop(
1466 			device, feature.flags, arg->data,
1467 			feature.argsz - minsz);
1468 	case VFIO_DEVICE_FEATURE_DMA_LOGGING_REPORT:
1469 		return vfio_ioctl_device_feature_logging_report(
1470 			device, feature.flags, arg->data,
1471 			feature.argsz - minsz);
1472 	default:
1473 		if (unlikely(!device->ops->device_feature))
1474 			return -EINVAL;
1475 		return device->ops->device_feature(device, feature.flags,
1476 						   arg->data,
1477 						   feature.argsz - minsz);
1478 	}
1479 }
1480 
1481 static long vfio_device_fops_unl_ioctl(struct file *filep,
1482 				       unsigned int cmd, unsigned long arg)
1483 {
1484 	struct vfio_device *device = filep->private_data;
1485 	int ret;
1486 
1487 	ret = vfio_device_pm_runtime_get(device);
1488 	if (ret)
1489 		return ret;
1490 
1491 	switch (cmd) {
1492 	case VFIO_DEVICE_FEATURE:
1493 		ret = vfio_ioctl_device_feature(device, (void __user *)arg);
1494 		break;
1495 
1496 	default:
1497 		if (unlikely(!device->ops->ioctl))
1498 			ret = -EINVAL;
1499 		else
1500 			ret = device->ops->ioctl(device, cmd, arg);
1501 		break;
1502 	}
1503 
1504 	vfio_device_pm_runtime_put(device);
1505 	return ret;
1506 }
1507 
1508 static ssize_t vfio_device_fops_read(struct file *filep, char __user *buf,
1509 				     size_t count, loff_t *ppos)
1510 {
1511 	struct vfio_device *device = filep->private_data;
1512 
1513 	if (unlikely(!device->ops->read))
1514 		return -EINVAL;
1515 
1516 	return device->ops->read(device, buf, count, ppos);
1517 }
1518 
1519 static ssize_t vfio_device_fops_write(struct file *filep,
1520 				      const char __user *buf,
1521 				      size_t count, loff_t *ppos)
1522 {
1523 	struct vfio_device *device = filep->private_data;
1524 
1525 	if (unlikely(!device->ops->write))
1526 		return -EINVAL;
1527 
1528 	return device->ops->write(device, buf, count, ppos);
1529 }
1530 
1531 static int vfio_device_fops_mmap(struct file *filep, struct vm_area_struct *vma)
1532 {
1533 	struct vfio_device *device = filep->private_data;
1534 
1535 	if (unlikely(!device->ops->mmap))
1536 		return -EINVAL;
1537 
1538 	return device->ops->mmap(device, vma);
1539 }
1540 
1541 static const struct file_operations vfio_device_fops = {
1542 	.owner		= THIS_MODULE,
1543 	.release	= vfio_device_fops_release,
1544 	.read		= vfio_device_fops_read,
1545 	.write		= vfio_device_fops_write,
1546 	.unlocked_ioctl	= vfio_device_fops_unl_ioctl,
1547 	.compat_ioctl	= compat_ptr_ioctl,
1548 	.mmap		= vfio_device_fops_mmap,
1549 };
1550 
1551 /**
1552  * vfio_file_iommu_group - Return the struct iommu_group for the vfio group file
1553  * @file: VFIO group file
1554  *
1555  * The returned iommu_group is valid as long as a ref is held on the file. This
1556  * returns a reference on the group. This function is deprecated, only the SPAPR
1557  * path in kvm should call it.
1558  */
1559 struct iommu_group *vfio_file_iommu_group(struct file *file)
1560 {
1561 	struct vfio_group *group = file->private_data;
1562 	struct iommu_group *iommu_group = NULL;
1563 
1564 	if (!IS_ENABLED(CONFIG_SPAPR_TCE_IOMMU))
1565 		return NULL;
1566 
1567 	if (!vfio_file_is_group(file))
1568 		return NULL;
1569 
1570 	mutex_lock(&group->group_lock);
1571 	if (group->iommu_group) {
1572 		iommu_group = group->iommu_group;
1573 		iommu_group_ref_get(iommu_group);
1574 	}
1575 	mutex_unlock(&group->group_lock);
1576 	return iommu_group;
1577 }
1578 EXPORT_SYMBOL_GPL(vfio_file_iommu_group);
1579 
1580 /**
1581  * vfio_file_is_group - True if the file is usable with VFIO aPIS
1582  * @file: VFIO group file
1583  */
1584 bool vfio_file_is_group(struct file *file)
1585 {
1586 	return file->f_op == &vfio_group_fops;
1587 }
1588 EXPORT_SYMBOL_GPL(vfio_file_is_group);
1589 
1590 /**
1591  * vfio_file_enforced_coherent - True if the DMA associated with the VFIO file
1592  *        is always CPU cache coherent
1593  * @file: VFIO group file
1594  *
1595  * Enforced coherency means that the IOMMU ignores things like the PCIe no-snoop
1596  * bit in DMA transactions. A return of false indicates that the user has
1597  * rights to access additional instructions such as wbinvd on x86.
1598  */
1599 bool vfio_file_enforced_coherent(struct file *file)
1600 {
1601 	struct vfio_group *group = file->private_data;
1602 	bool ret;
1603 
1604 	if (!vfio_file_is_group(file))
1605 		return true;
1606 
1607 	mutex_lock(&group->group_lock);
1608 	if (group->container) {
1609 		ret = vfio_container_ioctl_check_extension(group->container,
1610 							   VFIO_DMA_CC_IOMMU);
1611 	} else {
1612 		/*
1613 		 * Since the coherency state is determined only once a container
1614 		 * is attached the user must do so before they can prove they
1615 		 * have permission.
1616 		 */
1617 		ret = true;
1618 	}
1619 	mutex_unlock(&group->group_lock);
1620 	return ret;
1621 }
1622 EXPORT_SYMBOL_GPL(vfio_file_enforced_coherent);
1623 
1624 /**
1625  * vfio_file_set_kvm - Link a kvm with VFIO drivers
1626  * @file: VFIO group file
1627  * @kvm: KVM to link
1628  *
1629  * When a VFIO device is first opened the KVM will be available in
1630  * device->kvm if one was associated with the group.
1631  */
1632 void vfio_file_set_kvm(struct file *file, struct kvm *kvm)
1633 {
1634 	struct vfio_group *group = file->private_data;
1635 
1636 	if (!vfio_file_is_group(file))
1637 		return;
1638 
1639 	mutex_lock(&group->group_lock);
1640 	group->kvm = kvm;
1641 	mutex_unlock(&group->group_lock);
1642 }
1643 EXPORT_SYMBOL_GPL(vfio_file_set_kvm);
1644 
1645 /**
1646  * vfio_file_has_dev - True if the VFIO file is a handle for device
1647  * @file: VFIO file to check
1648  * @device: Device that must be part of the file
1649  *
1650  * Returns true if given file has permission to manipulate the given device.
1651  */
1652 bool vfio_file_has_dev(struct file *file, struct vfio_device *device)
1653 {
1654 	struct vfio_group *group = file->private_data;
1655 
1656 	if (!vfio_file_is_group(file))
1657 		return false;
1658 
1659 	return group == device->group;
1660 }
1661 EXPORT_SYMBOL_GPL(vfio_file_has_dev);
1662 
1663 /*
1664  * Sub-module support
1665  */
1666 /*
1667  * Helper for managing a buffer of info chain capabilities, allocate or
1668  * reallocate a buffer with additional @size, filling in @id and @version
1669  * of the capability.  A pointer to the new capability is returned.
1670  *
1671  * NB. The chain is based at the head of the buffer, so new entries are
1672  * added to the tail, vfio_info_cap_shift() should be called to fixup the
1673  * next offsets prior to copying to the user buffer.
1674  */
1675 struct vfio_info_cap_header *vfio_info_cap_add(struct vfio_info_cap *caps,
1676 					       size_t size, u16 id, u16 version)
1677 {
1678 	void *buf;
1679 	struct vfio_info_cap_header *header, *tmp;
1680 
1681 	buf = krealloc(caps->buf, caps->size + size, GFP_KERNEL);
1682 	if (!buf) {
1683 		kfree(caps->buf);
1684 		caps->buf = NULL;
1685 		caps->size = 0;
1686 		return ERR_PTR(-ENOMEM);
1687 	}
1688 
1689 	caps->buf = buf;
1690 	header = buf + caps->size;
1691 
1692 	/* Eventually copied to user buffer, zero */
1693 	memset(header, 0, size);
1694 
1695 	header->id = id;
1696 	header->version = version;
1697 
1698 	/* Add to the end of the capability chain */
1699 	for (tmp = buf; tmp->next; tmp = buf + tmp->next)
1700 		; /* nothing */
1701 
1702 	tmp->next = caps->size;
1703 	caps->size += size;
1704 
1705 	return header;
1706 }
1707 EXPORT_SYMBOL_GPL(vfio_info_cap_add);
1708 
1709 void vfio_info_cap_shift(struct vfio_info_cap *caps, size_t offset)
1710 {
1711 	struct vfio_info_cap_header *tmp;
1712 	void *buf = (void *)caps->buf;
1713 
1714 	for (tmp = buf; tmp->next; tmp = buf + tmp->next - offset)
1715 		tmp->next += offset;
1716 }
1717 EXPORT_SYMBOL(vfio_info_cap_shift);
1718 
1719 int vfio_info_add_capability(struct vfio_info_cap *caps,
1720 			     struct vfio_info_cap_header *cap, size_t size)
1721 {
1722 	struct vfio_info_cap_header *header;
1723 
1724 	header = vfio_info_cap_add(caps, size, cap->id, cap->version);
1725 	if (IS_ERR(header))
1726 		return PTR_ERR(header);
1727 
1728 	memcpy(header + 1, cap + 1, size - sizeof(*header));
1729 
1730 	return 0;
1731 }
1732 EXPORT_SYMBOL(vfio_info_add_capability);
1733 
1734 int vfio_set_irqs_validate_and_prepare(struct vfio_irq_set *hdr, int num_irqs,
1735 				       int max_irq_type, size_t *data_size)
1736 {
1737 	unsigned long minsz;
1738 	size_t size;
1739 
1740 	minsz = offsetofend(struct vfio_irq_set, count);
1741 
1742 	if ((hdr->argsz < minsz) || (hdr->index >= max_irq_type) ||
1743 	    (hdr->count >= (U32_MAX - hdr->start)) ||
1744 	    (hdr->flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK |
1745 				VFIO_IRQ_SET_ACTION_TYPE_MASK)))
1746 		return -EINVAL;
1747 
1748 	if (data_size)
1749 		*data_size = 0;
1750 
1751 	if (hdr->start >= num_irqs || hdr->start + hdr->count > num_irqs)
1752 		return -EINVAL;
1753 
1754 	switch (hdr->flags & VFIO_IRQ_SET_DATA_TYPE_MASK) {
1755 	case VFIO_IRQ_SET_DATA_NONE:
1756 		size = 0;
1757 		break;
1758 	case VFIO_IRQ_SET_DATA_BOOL:
1759 		size = sizeof(uint8_t);
1760 		break;
1761 	case VFIO_IRQ_SET_DATA_EVENTFD:
1762 		size = sizeof(int32_t);
1763 		break;
1764 	default:
1765 		return -EINVAL;
1766 	}
1767 
1768 	if (size) {
1769 		if (hdr->argsz - minsz < hdr->count * size)
1770 			return -EINVAL;
1771 
1772 		if (!data_size)
1773 			return -EINVAL;
1774 
1775 		*data_size = hdr->count * size;
1776 	}
1777 
1778 	return 0;
1779 }
1780 EXPORT_SYMBOL(vfio_set_irqs_validate_and_prepare);
1781 
1782 /*
1783  * Module/class support
1784  */
1785 static char *vfio_devnode(struct device *dev, umode_t *mode)
1786 {
1787 	return kasprintf(GFP_KERNEL, "vfio/%s", dev_name(dev));
1788 }
1789 
1790 static int __init vfio_init(void)
1791 {
1792 	int ret;
1793 
1794 	ida_init(&vfio.group_ida);
1795 	ida_init(&vfio.device_ida);
1796 	mutex_init(&vfio.group_lock);
1797 	INIT_LIST_HEAD(&vfio.group_list);
1798 
1799 	ret = vfio_container_init();
1800 	if (ret)
1801 		return ret;
1802 
1803 	/* /dev/vfio/$GROUP */
1804 	vfio.class = class_create(THIS_MODULE, "vfio");
1805 	if (IS_ERR(vfio.class)) {
1806 		ret = PTR_ERR(vfio.class);
1807 		goto err_group_class;
1808 	}
1809 
1810 	vfio.class->devnode = vfio_devnode;
1811 
1812 	/* /sys/class/vfio-dev/vfioX */
1813 	vfio.device_class = class_create(THIS_MODULE, "vfio-dev");
1814 	if (IS_ERR(vfio.device_class)) {
1815 		ret = PTR_ERR(vfio.device_class);
1816 		goto err_dev_class;
1817 	}
1818 
1819 	ret = alloc_chrdev_region(&vfio.group_devt, 0, MINORMASK + 1, "vfio");
1820 	if (ret)
1821 		goto err_alloc_chrdev;
1822 
1823 	pr_info(DRIVER_DESC " version: " DRIVER_VERSION "\n");
1824 	return 0;
1825 
1826 err_alloc_chrdev:
1827 	class_destroy(vfio.device_class);
1828 	vfio.device_class = NULL;
1829 err_dev_class:
1830 	class_destroy(vfio.class);
1831 	vfio.class = NULL;
1832 err_group_class:
1833 	vfio_container_cleanup();
1834 	return ret;
1835 }
1836 
1837 static void __exit vfio_cleanup(void)
1838 {
1839 	WARN_ON(!list_empty(&vfio.group_list));
1840 
1841 	ida_destroy(&vfio.device_ida);
1842 	ida_destroy(&vfio.group_ida);
1843 	unregister_chrdev_region(vfio.group_devt, MINORMASK + 1);
1844 	class_destroy(vfio.device_class);
1845 	vfio.device_class = NULL;
1846 	class_destroy(vfio.class);
1847 	vfio_container_cleanup();
1848 	vfio.class = NULL;
1849 	xa_destroy(&vfio_device_set_xa);
1850 }
1851 
1852 module_init(vfio_init);
1853 module_exit(vfio_cleanup);
1854 
1855 MODULE_VERSION(DRIVER_VERSION);
1856 MODULE_LICENSE("GPL v2");
1857 MODULE_AUTHOR(DRIVER_AUTHOR);
1858 MODULE_DESCRIPTION(DRIVER_DESC);
1859 MODULE_ALIAS_MISCDEV(VFIO_MINOR);
1860 MODULE_ALIAS("devname:vfio/vfio");
1861 MODULE_SOFTDEP("post: vfio_iommu_type1 vfio_iommu_spapr_tce");
1862