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