83c375fa24212145f97c3ff6db9ab5a57861beff
[linux-2.6-microblaze.git] / drivers / vfio / vfio.c
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 "vfio.h"
36
37 #define DRIVER_VERSION  "0.3"
38 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
39 #define DRIVER_DESC     "VFIO - User Level meta-driver"
40
41 static struct vfio {
42         struct class                    *class;
43         struct list_head                iommu_drivers_list;
44         struct mutex                    iommu_drivers_lock;
45         struct list_head                group_list;
46         struct mutex                    group_lock; /* locks group_list */
47         struct ida                      group_ida;
48         dev_t                           group_devt;
49 } vfio;
50
51 struct vfio_iommu_driver {
52         const struct vfio_iommu_driver_ops      *ops;
53         struct list_head                        vfio_next;
54 };
55
56 struct vfio_container {
57         struct kref                     kref;
58         struct list_head                group_list;
59         struct rw_semaphore             group_lock;
60         struct vfio_iommu_driver        *iommu_driver;
61         void                            *iommu_data;
62         bool                            noiommu;
63 };
64
65 struct vfio_group {
66         struct device                   dev;
67         struct cdev                     cdev;
68         refcount_t                      users;
69         unsigned int                    container_users;
70         struct iommu_group              *iommu_group;
71         struct vfio_container           *container;
72         struct list_head                device_list;
73         struct mutex                    device_lock;
74         struct list_head                vfio_next;
75         struct list_head                container_next;
76         enum vfio_group_type            type;
77         unsigned int                    dev_counter;
78         struct rw_semaphore             group_rwsem;
79         struct kvm                      *kvm;
80         struct file                     *opened_file;
81         struct blocking_notifier_head   notifier;
82 };
83
84 #ifdef CONFIG_VFIO_NOIOMMU
85 static bool noiommu __read_mostly;
86 module_param_named(enable_unsafe_noiommu_mode,
87                    noiommu, bool, S_IRUGO | S_IWUSR);
88 MODULE_PARM_DESC(enable_unsafe_noiommu_mode, "Enable UNSAFE, no-IOMMU mode.  This mode provides no device isolation, no DMA translation, no host kernel protection, cannot be used for device assignment to virtual machines, requires RAWIO permissions, and will taint the kernel.  If you do not know what this is for, step away. (default: false)");
89 #endif
90
91 static DEFINE_XARRAY(vfio_device_set_xa);
92 static const struct file_operations vfio_group_fops;
93
94 int vfio_assign_device_set(struct vfio_device *device, void *set_id)
95 {
96         unsigned long idx = (unsigned long)set_id;
97         struct vfio_device_set *new_dev_set;
98         struct vfio_device_set *dev_set;
99
100         if (WARN_ON(!set_id))
101                 return -EINVAL;
102
103         /*
104          * Atomically acquire a singleton object in the xarray for this set_id
105          */
106         xa_lock(&vfio_device_set_xa);
107         dev_set = xa_load(&vfio_device_set_xa, idx);
108         if (dev_set)
109                 goto found_get_ref;
110         xa_unlock(&vfio_device_set_xa);
111
112         new_dev_set = kzalloc(sizeof(*new_dev_set), GFP_KERNEL);
113         if (!new_dev_set)
114                 return -ENOMEM;
115         mutex_init(&new_dev_set->lock);
116         INIT_LIST_HEAD(&new_dev_set->device_list);
117         new_dev_set->set_id = set_id;
118
119         xa_lock(&vfio_device_set_xa);
120         dev_set = __xa_cmpxchg(&vfio_device_set_xa, idx, NULL, new_dev_set,
121                                GFP_KERNEL);
122         if (!dev_set) {
123                 dev_set = new_dev_set;
124                 goto found_get_ref;
125         }
126
127         kfree(new_dev_set);
128         if (xa_is_err(dev_set)) {
129                 xa_unlock(&vfio_device_set_xa);
130                 return xa_err(dev_set);
131         }
132
133 found_get_ref:
134         dev_set->device_count++;
135         xa_unlock(&vfio_device_set_xa);
136         mutex_lock(&dev_set->lock);
137         device->dev_set = dev_set;
138         list_add_tail(&device->dev_set_list, &dev_set->device_list);
139         mutex_unlock(&dev_set->lock);
140         return 0;
141 }
142 EXPORT_SYMBOL_GPL(vfio_assign_device_set);
143
144 static void vfio_release_device_set(struct vfio_device *device)
145 {
146         struct vfio_device_set *dev_set = device->dev_set;
147
148         if (!dev_set)
149                 return;
150
151         mutex_lock(&dev_set->lock);
152         list_del(&device->dev_set_list);
153         mutex_unlock(&dev_set->lock);
154
155         xa_lock(&vfio_device_set_xa);
156         if (!--dev_set->device_count) {
157                 __xa_erase(&vfio_device_set_xa,
158                            (unsigned long)dev_set->set_id);
159                 mutex_destroy(&dev_set->lock);
160                 kfree(dev_set);
161         }
162         xa_unlock(&vfio_device_set_xa);
163 }
164
165 #ifdef CONFIG_VFIO_NOIOMMU
166 static void *vfio_noiommu_open(unsigned long arg)
167 {
168         if (arg != VFIO_NOIOMMU_IOMMU)
169                 return ERR_PTR(-EINVAL);
170         if (!capable(CAP_SYS_RAWIO))
171                 return ERR_PTR(-EPERM);
172
173         return NULL;
174 }
175
176 static void vfio_noiommu_release(void *iommu_data)
177 {
178 }
179
180 static long vfio_noiommu_ioctl(void *iommu_data,
181                                unsigned int cmd, unsigned long arg)
182 {
183         if (cmd == VFIO_CHECK_EXTENSION)
184                 return noiommu && (arg == VFIO_NOIOMMU_IOMMU) ? 1 : 0;
185
186         return -ENOTTY;
187 }
188
189 static int vfio_noiommu_attach_group(void *iommu_data,
190                 struct iommu_group *iommu_group, enum vfio_group_type type)
191 {
192         return 0;
193 }
194
195 static void vfio_noiommu_detach_group(void *iommu_data,
196                                       struct iommu_group *iommu_group)
197 {
198 }
199
200 static const struct vfio_iommu_driver_ops vfio_noiommu_ops = {
201         .name = "vfio-noiommu",
202         .owner = THIS_MODULE,
203         .open = vfio_noiommu_open,
204         .release = vfio_noiommu_release,
205         .ioctl = vfio_noiommu_ioctl,
206         .attach_group = vfio_noiommu_attach_group,
207         .detach_group = vfio_noiommu_detach_group,
208 };
209
210 /*
211  * Only noiommu containers can use vfio-noiommu and noiommu containers can only
212  * use vfio-noiommu.
213  */
214 static inline bool vfio_iommu_driver_allowed(struct vfio_container *container,
215                 const struct vfio_iommu_driver *driver)
216 {
217         return container->noiommu == (driver->ops == &vfio_noiommu_ops);
218 }
219 #else
220 static inline bool vfio_iommu_driver_allowed(struct vfio_container *container,
221                 const struct vfio_iommu_driver *driver)
222 {
223         return true;
224 }
225 #endif /* CONFIG_VFIO_NOIOMMU */
226
227 /*
228  * IOMMU driver registration
229  */
230 int vfio_register_iommu_driver(const struct vfio_iommu_driver_ops *ops)
231 {
232         struct vfio_iommu_driver *driver, *tmp;
233
234         if (WARN_ON(!ops->register_notifier != !ops->unregister_notifier))
235                 return -EINVAL;
236
237         driver = kzalloc(sizeof(*driver), GFP_KERNEL);
238         if (!driver)
239                 return -ENOMEM;
240
241         driver->ops = ops;
242
243         mutex_lock(&vfio.iommu_drivers_lock);
244
245         /* Check for duplicates */
246         list_for_each_entry(tmp, &vfio.iommu_drivers_list, vfio_next) {
247                 if (tmp->ops == ops) {
248                         mutex_unlock(&vfio.iommu_drivers_lock);
249                         kfree(driver);
250                         return -EINVAL;
251                 }
252         }
253
254         list_add(&driver->vfio_next, &vfio.iommu_drivers_list);
255
256         mutex_unlock(&vfio.iommu_drivers_lock);
257
258         return 0;
259 }
260 EXPORT_SYMBOL_GPL(vfio_register_iommu_driver);
261
262 void vfio_unregister_iommu_driver(const struct vfio_iommu_driver_ops *ops)
263 {
264         struct vfio_iommu_driver *driver;
265
266         mutex_lock(&vfio.iommu_drivers_lock);
267         list_for_each_entry(driver, &vfio.iommu_drivers_list, vfio_next) {
268                 if (driver->ops == ops) {
269                         list_del(&driver->vfio_next);
270                         mutex_unlock(&vfio.iommu_drivers_lock);
271                         kfree(driver);
272                         return;
273                 }
274         }
275         mutex_unlock(&vfio.iommu_drivers_lock);
276 }
277 EXPORT_SYMBOL_GPL(vfio_unregister_iommu_driver);
278
279 static void vfio_group_get(struct vfio_group *group);
280
281 /*
282  * Container objects - containers are created when /dev/vfio/vfio is
283  * opened, but their lifecycle extends until the last user is done, so
284  * it's freed via kref.  Must support container/group/device being
285  * closed in any order.
286  */
287 static void vfio_container_get(struct vfio_container *container)
288 {
289         kref_get(&container->kref);
290 }
291
292 static void vfio_container_release(struct kref *kref)
293 {
294         struct vfio_container *container;
295         container = container_of(kref, struct vfio_container, kref);
296
297         kfree(container);
298 }
299
300 static void vfio_container_put(struct vfio_container *container)
301 {
302         kref_put(&container->kref, vfio_container_release);
303 }
304
305 /*
306  * Group objects - create, release, get, put, search
307  */
308 static struct vfio_group *
309 __vfio_group_get_from_iommu(struct iommu_group *iommu_group)
310 {
311         struct vfio_group *group;
312
313         list_for_each_entry(group, &vfio.group_list, vfio_next) {
314                 if (group->iommu_group == iommu_group) {
315                         vfio_group_get(group);
316                         return group;
317                 }
318         }
319         return NULL;
320 }
321
322 static struct vfio_group *
323 vfio_group_get_from_iommu(struct iommu_group *iommu_group)
324 {
325         struct vfio_group *group;
326
327         mutex_lock(&vfio.group_lock);
328         group = __vfio_group_get_from_iommu(iommu_group);
329         mutex_unlock(&vfio.group_lock);
330         return group;
331 }
332
333 static void vfio_group_release(struct device *dev)
334 {
335         struct vfio_group *group = container_of(dev, struct vfio_group, dev);
336
337         mutex_destroy(&group->device_lock);
338         iommu_group_put(group->iommu_group);
339         ida_free(&vfio.group_ida, MINOR(group->dev.devt));
340         kfree(group);
341 }
342
343 static struct vfio_group *vfio_group_alloc(struct iommu_group *iommu_group,
344                                            enum vfio_group_type type)
345 {
346         struct vfio_group *group;
347         int minor;
348
349         group = kzalloc(sizeof(*group), GFP_KERNEL);
350         if (!group)
351                 return ERR_PTR(-ENOMEM);
352
353         minor = ida_alloc_max(&vfio.group_ida, MINORMASK, GFP_KERNEL);
354         if (minor < 0) {
355                 kfree(group);
356                 return ERR_PTR(minor);
357         }
358
359         device_initialize(&group->dev);
360         group->dev.devt = MKDEV(MAJOR(vfio.group_devt), minor);
361         group->dev.class = vfio.class;
362         group->dev.release = vfio_group_release;
363         cdev_init(&group->cdev, &vfio_group_fops);
364         group->cdev.owner = THIS_MODULE;
365
366         refcount_set(&group->users, 1);
367         init_rwsem(&group->group_rwsem);
368         INIT_LIST_HEAD(&group->device_list);
369         mutex_init(&group->device_lock);
370         group->iommu_group = iommu_group;
371         /* put in vfio_group_release() */
372         iommu_group_ref_get(iommu_group);
373         group->type = type;
374         BLOCKING_INIT_NOTIFIER_HEAD(&group->notifier);
375
376         return group;
377 }
378
379 static struct vfio_group *vfio_create_group(struct iommu_group *iommu_group,
380                 enum vfio_group_type type)
381 {
382         struct vfio_group *group;
383         struct vfio_group *ret;
384         int err;
385
386         group = vfio_group_alloc(iommu_group, type);
387         if (IS_ERR(group))
388                 return group;
389
390         err = dev_set_name(&group->dev, "%s%d",
391                            group->type == VFIO_NO_IOMMU ? "noiommu-" : "",
392                            iommu_group_id(iommu_group));
393         if (err) {
394                 ret = ERR_PTR(err);
395                 goto err_put;
396         }
397
398         mutex_lock(&vfio.group_lock);
399
400         /* Did we race creating this group? */
401         ret = __vfio_group_get_from_iommu(iommu_group);
402         if (ret)
403                 goto err_unlock;
404
405         err = cdev_device_add(&group->cdev, &group->dev);
406         if (err) {
407                 ret = ERR_PTR(err);
408                 goto err_unlock;
409         }
410
411         list_add(&group->vfio_next, &vfio.group_list);
412
413         mutex_unlock(&vfio.group_lock);
414         return group;
415
416 err_unlock:
417         mutex_unlock(&vfio.group_lock);
418 err_put:
419         put_device(&group->dev);
420         return ret;
421 }
422
423 static void vfio_group_put(struct vfio_group *group)
424 {
425         if (!refcount_dec_and_mutex_lock(&group->users, &vfio.group_lock))
426                 return;
427
428         /*
429          * These data structures all have paired operations that can only be
430          * undone when the caller holds a live reference on the group. Since all
431          * pairs must be undone these WARN_ON's indicate some caller did not
432          * properly hold the group reference.
433          */
434         WARN_ON(!list_empty(&group->device_list));
435         WARN_ON(group->container || group->container_users);
436         WARN_ON(group->notifier.head);
437
438         list_del(&group->vfio_next);
439         cdev_device_del(&group->cdev, &group->dev);
440         mutex_unlock(&vfio.group_lock);
441
442         put_device(&group->dev);
443 }
444
445 static void vfio_group_get(struct vfio_group *group)
446 {
447         refcount_inc(&group->users);
448 }
449
450 /*
451  * Device objects - create, release, get, put, search
452  */
453 /* Device reference always implies a group reference */
454 static void vfio_device_put(struct vfio_device *device)
455 {
456         if (refcount_dec_and_test(&device->refcount))
457                 complete(&device->comp);
458 }
459
460 static bool vfio_device_try_get(struct vfio_device *device)
461 {
462         return refcount_inc_not_zero(&device->refcount);
463 }
464
465 static struct vfio_device *vfio_group_get_device(struct vfio_group *group,
466                                                  struct device *dev)
467 {
468         struct vfio_device *device;
469
470         mutex_lock(&group->device_lock);
471         list_for_each_entry(device, &group->device_list, group_next) {
472                 if (device->dev == dev && vfio_device_try_get(device)) {
473                         mutex_unlock(&group->device_lock);
474                         return device;
475                 }
476         }
477         mutex_unlock(&group->device_lock);
478         return NULL;
479 }
480
481 /*
482  * VFIO driver API
483  */
484 void vfio_init_group_dev(struct vfio_device *device, struct device *dev,
485                          const struct vfio_device_ops *ops)
486 {
487         init_completion(&device->comp);
488         device->dev = dev;
489         device->ops = ops;
490 }
491 EXPORT_SYMBOL_GPL(vfio_init_group_dev);
492
493 void vfio_uninit_group_dev(struct vfio_device *device)
494 {
495         vfio_release_device_set(device);
496 }
497 EXPORT_SYMBOL_GPL(vfio_uninit_group_dev);
498
499 static struct vfio_group *vfio_noiommu_group_alloc(struct device *dev,
500                 enum vfio_group_type type)
501 {
502         struct iommu_group *iommu_group;
503         struct vfio_group *group;
504         int ret;
505
506         iommu_group = iommu_group_alloc();
507         if (IS_ERR(iommu_group))
508                 return ERR_CAST(iommu_group);
509
510         ret = iommu_group_set_name(iommu_group, "vfio-noiommu");
511         if (ret)
512                 goto out_put_group;
513         ret = iommu_group_add_device(iommu_group, dev);
514         if (ret)
515                 goto out_put_group;
516
517         group = vfio_create_group(iommu_group, type);
518         if (IS_ERR(group)) {
519                 ret = PTR_ERR(group);
520                 goto out_remove_device;
521         }
522         iommu_group_put(iommu_group);
523         return group;
524
525 out_remove_device:
526         iommu_group_remove_device(dev);
527 out_put_group:
528         iommu_group_put(iommu_group);
529         return ERR_PTR(ret);
530 }
531
532 static struct vfio_group *vfio_group_find_or_alloc(struct device *dev)
533 {
534         struct iommu_group *iommu_group;
535         struct vfio_group *group;
536
537         iommu_group = iommu_group_get(dev);
538 #ifdef CONFIG_VFIO_NOIOMMU
539         if (!iommu_group && noiommu) {
540                 /*
541                  * With noiommu enabled, create an IOMMU group for devices that
542                  * don't already have one, implying no IOMMU hardware/driver
543                  * exists.  Taint the kernel because we're about to give a DMA
544                  * capable device to a user without IOMMU protection.
545                  */
546                 group = vfio_noiommu_group_alloc(dev, VFIO_NO_IOMMU);
547                 if (!IS_ERR(group)) {
548                         add_taint(TAINT_USER, LOCKDEP_STILL_OK);
549                         dev_warn(dev, "Adding kernel taint for vfio-noiommu group on device\n");
550                 }
551                 return group;
552         }
553 #endif
554         if (!iommu_group)
555                 return ERR_PTR(-EINVAL);
556
557         group = vfio_group_get_from_iommu(iommu_group);
558         if (!group)
559                 group = vfio_create_group(iommu_group, VFIO_IOMMU);
560
561         /* The vfio_group holds a reference to the iommu_group */
562         iommu_group_put(iommu_group);
563         return group;
564 }
565
566 static int __vfio_register_dev(struct vfio_device *device,
567                 struct vfio_group *group)
568 {
569         struct vfio_device *existing_device;
570
571         if (IS_ERR(group))
572                 return PTR_ERR(group);
573
574         /*
575          * If the driver doesn't specify a set then the device is added to a
576          * singleton set just for itself.
577          */
578         if (!device->dev_set)
579                 vfio_assign_device_set(device, device);
580
581         existing_device = vfio_group_get_device(group, device->dev);
582         if (existing_device) {
583                 dev_WARN(device->dev, "Device already exists on group %d\n",
584                          iommu_group_id(group->iommu_group));
585                 vfio_device_put(existing_device);
586                 if (group->type == VFIO_NO_IOMMU ||
587                     group->type == VFIO_EMULATED_IOMMU)
588                         iommu_group_remove_device(device->dev);
589                 vfio_group_put(group);
590                 return -EBUSY;
591         }
592
593         /* Our reference on group is moved to the device */
594         device->group = group;
595
596         /* Refcounting can't start until the driver calls register */
597         refcount_set(&device->refcount, 1);
598
599         mutex_lock(&group->device_lock);
600         list_add(&device->group_next, &group->device_list);
601         group->dev_counter++;
602         mutex_unlock(&group->device_lock);
603
604         return 0;
605 }
606
607 int vfio_register_group_dev(struct vfio_device *device)
608 {
609         /*
610          * VFIO always sets IOMMU_CACHE because we offer no way for userspace to
611          * restore cache coherency.
612          */
613         if (!device_iommu_capable(device->dev, IOMMU_CAP_CACHE_COHERENCY))
614                 return -EINVAL;
615
616         return __vfio_register_dev(device,
617                 vfio_group_find_or_alloc(device->dev));
618 }
619 EXPORT_SYMBOL_GPL(vfio_register_group_dev);
620
621 /*
622  * Register a virtual device without IOMMU backing.  The user of this
623  * device must not be able to directly trigger unmediated DMA.
624  */
625 int vfio_register_emulated_iommu_dev(struct vfio_device *device)
626 {
627         return __vfio_register_dev(device,
628                 vfio_noiommu_group_alloc(device->dev, VFIO_EMULATED_IOMMU));
629 }
630 EXPORT_SYMBOL_GPL(vfio_register_emulated_iommu_dev);
631
632 static struct vfio_device *vfio_device_get_from_name(struct vfio_group *group,
633                                                      char *buf)
634 {
635         struct vfio_device *it, *device = ERR_PTR(-ENODEV);
636
637         mutex_lock(&group->device_lock);
638         list_for_each_entry(it, &group->device_list, group_next) {
639                 int ret;
640
641                 if (it->ops->match) {
642                         ret = it->ops->match(it, buf);
643                         if (ret < 0) {
644                                 device = ERR_PTR(ret);
645                                 break;
646                         }
647                 } else {
648                         ret = !strcmp(dev_name(it->dev), buf);
649                 }
650
651                 if (ret && vfio_device_try_get(it)) {
652                         device = it;
653                         break;
654                 }
655         }
656         mutex_unlock(&group->device_lock);
657
658         return device;
659 }
660
661 /*
662  * Decrement the device reference count and wait for the device to be
663  * removed.  Open file descriptors for the device... */
664 void vfio_unregister_group_dev(struct vfio_device *device)
665 {
666         struct vfio_group *group = device->group;
667         unsigned int i = 0;
668         bool interrupted = false;
669         long rc;
670
671         vfio_device_put(device);
672         rc = try_wait_for_completion(&device->comp);
673         while (rc <= 0) {
674                 if (device->ops->request)
675                         device->ops->request(device, i++);
676
677                 if (interrupted) {
678                         rc = wait_for_completion_timeout(&device->comp,
679                                                          HZ * 10);
680                 } else {
681                         rc = wait_for_completion_interruptible_timeout(
682                                 &device->comp, HZ * 10);
683                         if (rc < 0) {
684                                 interrupted = true;
685                                 dev_warn(device->dev,
686                                          "Device is currently in use, task"
687                                          " \"%s\" (%d) "
688                                          "blocked until device is released",
689                                          current->comm, task_pid_nr(current));
690                         }
691                 }
692         }
693
694         mutex_lock(&group->device_lock);
695         list_del(&device->group_next);
696         group->dev_counter--;
697         mutex_unlock(&group->device_lock);
698
699         if (group->type == VFIO_NO_IOMMU || group->type == VFIO_EMULATED_IOMMU)
700                 iommu_group_remove_device(device->dev);
701
702         /* Matches the get in vfio_register_group_dev() */
703         vfio_group_put(group);
704 }
705 EXPORT_SYMBOL_GPL(vfio_unregister_group_dev);
706
707 /*
708  * VFIO base fd, /dev/vfio/vfio
709  */
710 static long vfio_ioctl_check_extension(struct vfio_container *container,
711                                        unsigned long arg)
712 {
713         struct vfio_iommu_driver *driver;
714         long ret = 0;
715
716         down_read(&container->group_lock);
717
718         driver = container->iommu_driver;
719
720         switch (arg) {
721                 /* No base extensions yet */
722         default:
723                 /*
724                  * If no driver is set, poll all registered drivers for
725                  * extensions and return the first positive result.  If
726                  * a driver is already set, further queries will be passed
727                  * only to that driver.
728                  */
729                 if (!driver) {
730                         mutex_lock(&vfio.iommu_drivers_lock);
731                         list_for_each_entry(driver, &vfio.iommu_drivers_list,
732                                             vfio_next) {
733
734                                 if (!list_empty(&container->group_list) &&
735                                     !vfio_iommu_driver_allowed(container,
736                                                                driver))
737                                         continue;
738                                 if (!try_module_get(driver->ops->owner))
739                                         continue;
740
741                                 ret = driver->ops->ioctl(NULL,
742                                                          VFIO_CHECK_EXTENSION,
743                                                          arg);
744                                 module_put(driver->ops->owner);
745                                 if (ret > 0)
746                                         break;
747                         }
748                         mutex_unlock(&vfio.iommu_drivers_lock);
749                 } else
750                         ret = driver->ops->ioctl(container->iommu_data,
751                                                  VFIO_CHECK_EXTENSION, arg);
752         }
753
754         up_read(&container->group_lock);
755
756         return ret;
757 }
758
759 /* hold write lock on container->group_lock */
760 static int __vfio_container_attach_groups(struct vfio_container *container,
761                                           struct vfio_iommu_driver *driver,
762                                           void *data)
763 {
764         struct vfio_group *group;
765         int ret = -ENODEV;
766
767         list_for_each_entry(group, &container->group_list, container_next) {
768                 ret = driver->ops->attach_group(data, group->iommu_group,
769                                                 group->type);
770                 if (ret)
771                         goto unwind;
772         }
773
774         return ret;
775
776 unwind:
777         list_for_each_entry_continue_reverse(group, &container->group_list,
778                                              container_next) {
779                 driver->ops->detach_group(data, group->iommu_group);
780         }
781
782         return ret;
783 }
784
785 static long vfio_ioctl_set_iommu(struct vfio_container *container,
786                                  unsigned long arg)
787 {
788         struct vfio_iommu_driver *driver;
789         long ret = -ENODEV;
790
791         down_write(&container->group_lock);
792
793         /*
794          * The container is designed to be an unprivileged interface while
795          * the group can be assigned to specific users.  Therefore, only by
796          * adding a group to a container does the user get the privilege of
797          * enabling the iommu, which may allocate finite resources.  There
798          * is no unset_iommu, but by removing all the groups from a container,
799          * the container is deprivileged and returns to an unset state.
800          */
801         if (list_empty(&container->group_list) || container->iommu_driver) {
802                 up_write(&container->group_lock);
803                 return -EINVAL;
804         }
805
806         mutex_lock(&vfio.iommu_drivers_lock);
807         list_for_each_entry(driver, &vfio.iommu_drivers_list, vfio_next) {
808                 void *data;
809
810                 if (!vfio_iommu_driver_allowed(container, driver))
811                         continue;
812                 if (!try_module_get(driver->ops->owner))
813                         continue;
814
815                 /*
816                  * The arg magic for SET_IOMMU is the same as CHECK_EXTENSION,
817                  * so test which iommu driver reported support for this
818                  * extension and call open on them.  We also pass them the
819                  * magic, allowing a single driver to support multiple
820                  * interfaces if they'd like.
821                  */
822                 if (driver->ops->ioctl(NULL, VFIO_CHECK_EXTENSION, arg) <= 0) {
823                         module_put(driver->ops->owner);
824                         continue;
825                 }
826
827                 data = driver->ops->open(arg);
828                 if (IS_ERR(data)) {
829                         ret = PTR_ERR(data);
830                         module_put(driver->ops->owner);
831                         continue;
832                 }
833
834                 ret = __vfio_container_attach_groups(container, driver, data);
835                 if (ret) {
836                         driver->ops->release(data);
837                         module_put(driver->ops->owner);
838                         continue;
839                 }
840
841                 container->iommu_driver = driver;
842                 container->iommu_data = data;
843                 break;
844         }
845
846         mutex_unlock(&vfio.iommu_drivers_lock);
847         up_write(&container->group_lock);
848
849         return ret;
850 }
851
852 static long vfio_fops_unl_ioctl(struct file *filep,
853                                 unsigned int cmd, unsigned long arg)
854 {
855         struct vfio_container *container = filep->private_data;
856         struct vfio_iommu_driver *driver;
857         void *data;
858         long ret = -EINVAL;
859
860         if (!container)
861                 return ret;
862
863         switch (cmd) {
864         case VFIO_GET_API_VERSION:
865                 ret = VFIO_API_VERSION;
866                 break;
867         case VFIO_CHECK_EXTENSION:
868                 ret = vfio_ioctl_check_extension(container, arg);
869                 break;
870         case VFIO_SET_IOMMU:
871                 ret = vfio_ioctl_set_iommu(container, arg);
872                 break;
873         default:
874                 driver = container->iommu_driver;
875                 data = container->iommu_data;
876
877                 if (driver) /* passthrough all unrecognized ioctls */
878                         ret = driver->ops->ioctl(data, cmd, arg);
879         }
880
881         return ret;
882 }
883
884 static int vfio_fops_open(struct inode *inode, struct file *filep)
885 {
886         struct vfio_container *container;
887
888         container = kzalloc(sizeof(*container), GFP_KERNEL);
889         if (!container)
890                 return -ENOMEM;
891
892         INIT_LIST_HEAD(&container->group_list);
893         init_rwsem(&container->group_lock);
894         kref_init(&container->kref);
895
896         filep->private_data = container;
897
898         return 0;
899 }
900
901 static int vfio_fops_release(struct inode *inode, struct file *filep)
902 {
903         struct vfio_container *container = filep->private_data;
904         struct vfio_iommu_driver *driver = container->iommu_driver;
905
906         if (driver && driver->ops->notify)
907                 driver->ops->notify(container->iommu_data,
908                                     VFIO_IOMMU_CONTAINER_CLOSE);
909
910         filep->private_data = NULL;
911
912         vfio_container_put(container);
913
914         return 0;
915 }
916
917 static const struct file_operations vfio_fops = {
918         .owner          = THIS_MODULE,
919         .open           = vfio_fops_open,
920         .release        = vfio_fops_release,
921         .unlocked_ioctl = vfio_fops_unl_ioctl,
922         .compat_ioctl   = compat_ptr_ioctl,
923 };
924
925 /*
926  * VFIO Group fd, /dev/vfio/$GROUP
927  */
928 static void __vfio_group_unset_container(struct vfio_group *group)
929 {
930         struct vfio_container *container = group->container;
931         struct vfio_iommu_driver *driver;
932
933         lockdep_assert_held_write(&group->group_rwsem);
934
935         down_write(&container->group_lock);
936
937         driver = container->iommu_driver;
938         if (driver)
939                 driver->ops->detach_group(container->iommu_data,
940                                           group->iommu_group);
941
942         if (group->type == VFIO_IOMMU)
943                 iommu_group_release_dma_owner(group->iommu_group);
944
945         group->container = NULL;
946         group->container_users = 0;
947         list_del(&group->container_next);
948
949         /* Detaching the last group deprivileges a container, remove iommu */
950         if (driver && list_empty(&container->group_list)) {
951                 driver->ops->release(container->iommu_data);
952                 module_put(driver->ops->owner);
953                 container->iommu_driver = NULL;
954                 container->iommu_data = NULL;
955         }
956
957         up_write(&container->group_lock);
958
959         vfio_container_put(container);
960 }
961
962 /*
963  * VFIO_GROUP_UNSET_CONTAINER should fail if there are other users or
964  * if there was no container to unset.  Since the ioctl is called on
965  * the group, we know that still exists, therefore the only valid
966  * transition here is 1->0.
967  */
968 static int vfio_group_unset_container(struct vfio_group *group)
969 {
970         lockdep_assert_held_write(&group->group_rwsem);
971
972         if (!group->container)
973                 return -EINVAL;
974         if (group->container_users != 1)
975                 return -EBUSY;
976         __vfio_group_unset_container(group);
977         return 0;
978 }
979
980 static int vfio_group_set_container(struct vfio_group *group, int container_fd)
981 {
982         struct fd f;
983         struct vfio_container *container;
984         struct vfio_iommu_driver *driver;
985         int ret = 0;
986
987         lockdep_assert_held_write(&group->group_rwsem);
988
989         if (group->container || WARN_ON(group->container_users))
990                 return -EINVAL;
991
992         if (group->type == VFIO_NO_IOMMU && !capable(CAP_SYS_RAWIO))
993                 return -EPERM;
994
995         f = fdget(container_fd);
996         if (!f.file)
997                 return -EBADF;
998
999         /* Sanity check, is this really our fd? */
1000         if (f.file->f_op != &vfio_fops) {
1001                 fdput(f);
1002                 return -EINVAL;
1003         }
1004
1005         container = f.file->private_data;
1006         WARN_ON(!container); /* fget ensures we don't race vfio_release */
1007
1008         down_write(&container->group_lock);
1009
1010         /* Real groups and fake groups cannot mix */
1011         if (!list_empty(&container->group_list) &&
1012             container->noiommu != (group->type == VFIO_NO_IOMMU)) {
1013                 ret = -EPERM;
1014                 goto unlock_out;
1015         }
1016
1017         if (group->type == VFIO_IOMMU) {
1018                 ret = iommu_group_claim_dma_owner(group->iommu_group, f.file);
1019                 if (ret)
1020                         goto unlock_out;
1021         }
1022
1023         driver = container->iommu_driver;
1024         if (driver) {
1025                 ret = driver->ops->attach_group(container->iommu_data,
1026                                                 group->iommu_group,
1027                                                 group->type);
1028                 if (ret) {
1029                         if (group->type == VFIO_IOMMU)
1030                                 iommu_group_release_dma_owner(
1031                                         group->iommu_group);
1032                         goto unlock_out;
1033                 }
1034         }
1035
1036         group->container = container;
1037         group->container_users = 1;
1038         container->noiommu = (group->type == VFIO_NO_IOMMU);
1039         list_add(&group->container_next, &container->group_list);
1040
1041         /* Get a reference on the container and mark a user within the group */
1042         vfio_container_get(container);
1043
1044 unlock_out:
1045         up_write(&container->group_lock);
1046         fdput(f);
1047         return ret;
1048 }
1049
1050 static const struct file_operations vfio_device_fops;
1051
1052 /* true if the vfio_device has open_device() called but not close_device() */
1053 static bool vfio_assert_device_open(struct vfio_device *device)
1054 {
1055         return !WARN_ON_ONCE(!READ_ONCE(device->open_count));
1056 }
1057
1058 static int vfio_device_assign_container(struct vfio_device *device)
1059 {
1060         struct vfio_group *group = device->group;
1061
1062         lockdep_assert_held_write(&group->group_rwsem);
1063
1064         if (!group->container || !group->container->iommu_driver ||
1065             WARN_ON(!group->container_users))
1066                 return -EINVAL;
1067
1068         if (group->type == VFIO_NO_IOMMU && !capable(CAP_SYS_RAWIO))
1069                 return -EPERM;
1070
1071         get_file(group->opened_file);
1072         group->container_users++;
1073         return 0;
1074 }
1075
1076 static void vfio_device_unassign_container(struct vfio_device *device)
1077 {
1078         down_write(&device->group->group_rwsem);
1079         WARN_ON(device->group->container_users <= 1);
1080         device->group->container_users--;
1081         fput(device->group->opened_file);
1082         up_write(&device->group->group_rwsem);
1083 }
1084
1085 static int vfio_iommu_notifier(struct notifier_block *nb, unsigned long action,
1086                                void *data)
1087 {
1088         struct vfio_device *vfio_device =
1089                 container_of(nb, struct vfio_device, iommu_nb);
1090         struct vfio_iommu_type1_dma_unmap *unmap = data;
1091
1092         vfio_device->ops->dma_unmap(vfio_device, unmap->iova, unmap->size);
1093         return NOTIFY_OK;
1094 }
1095
1096 static struct file *vfio_device_open(struct vfio_device *device)
1097 {
1098         struct vfio_iommu_driver *iommu_driver;
1099         struct file *filep;
1100         int ret;
1101
1102         down_write(&device->group->group_rwsem);
1103         ret = vfio_device_assign_container(device);
1104         up_write(&device->group->group_rwsem);
1105         if (ret)
1106                 return ERR_PTR(ret);
1107
1108         if (!try_module_get(device->dev->driver->owner)) {
1109                 ret = -ENODEV;
1110                 goto err_unassign_container;
1111         }
1112
1113         mutex_lock(&device->dev_set->lock);
1114         device->open_count++;
1115         if (device->open_count == 1) {
1116                 /*
1117                  * Here we pass the KVM pointer with the group under the read
1118                  * lock.  If the device driver will use it, it must obtain a
1119                  * reference and release it during close_device.
1120                  */
1121                 down_read(&device->group->group_rwsem);
1122                 device->kvm = device->group->kvm;
1123
1124                 if (device->ops->open_device) {
1125                         ret = device->ops->open_device(device);
1126                         if (ret)
1127                                 goto err_undo_count;
1128                 }
1129
1130                 iommu_driver = device->group->container->iommu_driver;
1131                 if (device->ops->dma_unmap && iommu_driver &&
1132                     iommu_driver->ops->register_notifier) {
1133                         unsigned long events = VFIO_IOMMU_NOTIFY_DMA_UNMAP;
1134
1135                         device->iommu_nb.notifier_call = vfio_iommu_notifier;
1136                         iommu_driver->ops->register_notifier(
1137                                 device->group->container->iommu_data, &events,
1138                                 &device->iommu_nb);
1139                 }
1140
1141                 up_read(&device->group->group_rwsem);
1142         }
1143         mutex_unlock(&device->dev_set->lock);
1144
1145         /*
1146          * We can't use anon_inode_getfd() because we need to modify
1147          * the f_mode flags directly to allow more than just ioctls
1148          */
1149         filep = anon_inode_getfile("[vfio-device]", &vfio_device_fops,
1150                                    device, O_RDWR);
1151         if (IS_ERR(filep)) {
1152                 ret = PTR_ERR(filep);
1153                 goto err_close_device;
1154         }
1155
1156         /*
1157          * TODO: add an anon_inode interface to do this.
1158          * Appears to be missing by lack of need rather than
1159          * explicitly prevented.  Now there's need.
1160          */
1161         filep->f_mode |= (FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE);
1162
1163         if (device->group->type == VFIO_NO_IOMMU)
1164                 dev_warn(device->dev, "vfio-noiommu device opened by user "
1165                          "(%s:%d)\n", current->comm, task_pid_nr(current));
1166         /*
1167          * On success the ref of device is moved to the file and
1168          * put in vfio_device_fops_release()
1169          */
1170         return filep;
1171
1172 err_close_device:
1173         mutex_lock(&device->dev_set->lock);
1174         down_read(&device->group->group_rwsem);
1175         if (device->open_count == 1 && device->ops->close_device) {
1176                 device->ops->close_device(device);
1177
1178                 iommu_driver = device->group->container->iommu_driver;
1179                 if (device->ops->dma_unmap && iommu_driver &&
1180                     iommu_driver->ops->unregister_notifier)
1181                         iommu_driver->ops->unregister_notifier(
1182                                 device->group->container->iommu_data,
1183                                 &device->iommu_nb);
1184         }
1185 err_undo_count:
1186         up_read(&device->group->group_rwsem);
1187         device->open_count--;
1188         if (device->open_count == 0 && device->kvm)
1189                 device->kvm = NULL;
1190         mutex_unlock(&device->dev_set->lock);
1191         module_put(device->dev->driver->owner);
1192 err_unassign_container:
1193         vfio_device_unassign_container(device);
1194         return ERR_PTR(ret);
1195 }
1196
1197 static int vfio_group_get_device_fd(struct vfio_group *group, char *buf)
1198 {
1199         struct vfio_device *device;
1200         struct file *filep;
1201         int fdno;
1202         int ret;
1203
1204         device = vfio_device_get_from_name(group, buf);
1205         if (IS_ERR(device))
1206                 return PTR_ERR(device);
1207
1208         fdno = get_unused_fd_flags(O_CLOEXEC);
1209         if (fdno < 0) {
1210                 ret = fdno;
1211                 goto err_put_device;
1212         }
1213
1214         filep = vfio_device_open(device);
1215         if (IS_ERR(filep)) {
1216                 ret = PTR_ERR(filep);
1217                 goto err_put_fdno;
1218         }
1219
1220         fd_install(fdno, filep);
1221         return fdno;
1222
1223 err_put_fdno:
1224         put_unused_fd(fdno);
1225 err_put_device:
1226         vfio_device_put(device);
1227         return ret;
1228 }
1229
1230 static long vfio_group_fops_unl_ioctl(struct file *filep,
1231                                       unsigned int cmd, unsigned long arg)
1232 {
1233         struct vfio_group *group = filep->private_data;
1234         long ret = -ENOTTY;
1235
1236         switch (cmd) {
1237         case VFIO_GROUP_GET_STATUS:
1238         {
1239                 struct vfio_group_status status;
1240                 unsigned long minsz;
1241
1242                 minsz = offsetofend(struct vfio_group_status, flags);
1243
1244                 if (copy_from_user(&status, (void __user *)arg, minsz))
1245                         return -EFAULT;
1246
1247                 if (status.argsz < minsz)
1248                         return -EINVAL;
1249
1250                 status.flags = 0;
1251
1252                 down_read(&group->group_rwsem);
1253                 if (group->container)
1254                         status.flags |= VFIO_GROUP_FLAGS_CONTAINER_SET |
1255                                         VFIO_GROUP_FLAGS_VIABLE;
1256                 else if (!iommu_group_dma_owner_claimed(group->iommu_group))
1257                         status.flags |= VFIO_GROUP_FLAGS_VIABLE;
1258                 up_read(&group->group_rwsem);
1259
1260                 if (copy_to_user((void __user *)arg, &status, minsz))
1261                         return -EFAULT;
1262
1263                 ret = 0;
1264                 break;
1265         }
1266         case VFIO_GROUP_SET_CONTAINER:
1267         {
1268                 int fd;
1269
1270                 if (get_user(fd, (int __user *)arg))
1271                         return -EFAULT;
1272
1273                 if (fd < 0)
1274                         return -EINVAL;
1275
1276                 down_write(&group->group_rwsem);
1277                 ret = vfio_group_set_container(group, fd);
1278                 up_write(&group->group_rwsem);
1279                 break;
1280         }
1281         case VFIO_GROUP_UNSET_CONTAINER:
1282                 down_write(&group->group_rwsem);
1283                 ret = vfio_group_unset_container(group);
1284                 up_write(&group->group_rwsem);
1285                 break;
1286         case VFIO_GROUP_GET_DEVICE_FD:
1287         {
1288                 char *buf;
1289
1290                 buf = strndup_user((const char __user *)arg, PAGE_SIZE);
1291                 if (IS_ERR(buf))
1292                         return PTR_ERR(buf);
1293
1294                 ret = vfio_group_get_device_fd(group, buf);
1295                 kfree(buf);
1296                 break;
1297         }
1298         }
1299
1300         return ret;
1301 }
1302
1303 static int vfio_group_fops_open(struct inode *inode, struct file *filep)
1304 {
1305         struct vfio_group *group =
1306                 container_of(inode->i_cdev, struct vfio_group, cdev);
1307         int ret;
1308
1309         down_write(&group->group_rwsem);
1310
1311         /* users can be zero if this races with vfio_group_put() */
1312         if (!refcount_inc_not_zero(&group->users)) {
1313                 ret = -ENODEV;
1314                 goto err_unlock;
1315         }
1316
1317         if (group->type == VFIO_NO_IOMMU && !capable(CAP_SYS_RAWIO)) {
1318                 ret = -EPERM;
1319                 goto err_put;
1320         }
1321
1322         /*
1323          * Do we need multiple instances of the group open?  Seems not.
1324          */
1325         if (group->opened_file) {
1326                 ret = -EBUSY;
1327                 goto err_put;
1328         }
1329         group->opened_file = filep;
1330         filep->private_data = group;
1331
1332         up_write(&group->group_rwsem);
1333         return 0;
1334 err_put:
1335         vfio_group_put(group);
1336 err_unlock:
1337         up_write(&group->group_rwsem);
1338         return ret;
1339 }
1340
1341 static int vfio_group_fops_release(struct inode *inode, struct file *filep)
1342 {
1343         struct vfio_group *group = filep->private_data;
1344
1345         filep->private_data = NULL;
1346
1347         down_write(&group->group_rwsem);
1348         /*
1349          * Device FDs hold a group file reference, therefore the group release
1350          * is only called when there are no open devices.
1351          */
1352         WARN_ON(group->notifier.head);
1353         if (group->container) {
1354                 WARN_ON(group->container_users != 1);
1355                 __vfio_group_unset_container(group);
1356         }
1357         group->opened_file = NULL;
1358         up_write(&group->group_rwsem);
1359
1360         vfio_group_put(group);
1361
1362         return 0;
1363 }
1364
1365 static const struct file_operations vfio_group_fops = {
1366         .owner          = THIS_MODULE,
1367         .unlocked_ioctl = vfio_group_fops_unl_ioctl,
1368         .compat_ioctl   = compat_ptr_ioctl,
1369         .open           = vfio_group_fops_open,
1370         .release        = vfio_group_fops_release,
1371 };
1372
1373 /*
1374  * VFIO Device fd
1375  */
1376 static int vfio_device_fops_release(struct inode *inode, struct file *filep)
1377 {
1378         struct vfio_device *device = filep->private_data;
1379         struct vfio_iommu_driver *iommu_driver;
1380
1381         mutex_lock(&device->dev_set->lock);
1382         vfio_assert_device_open(device);
1383         down_read(&device->group->group_rwsem);
1384         if (device->open_count == 1 && device->ops->close_device)
1385                 device->ops->close_device(device);
1386
1387         iommu_driver = device->group->container->iommu_driver;
1388         if (device->ops->dma_unmap && iommu_driver &&
1389             iommu_driver->ops->unregister_notifier)
1390                 iommu_driver->ops->unregister_notifier(
1391                         device->group->container->iommu_data,
1392                         &device->iommu_nb);
1393         up_read(&device->group->group_rwsem);
1394         device->open_count--;
1395         if (device->open_count == 0)
1396                 device->kvm = NULL;
1397         mutex_unlock(&device->dev_set->lock);
1398
1399         module_put(device->dev->driver->owner);
1400
1401         vfio_device_unassign_container(device);
1402
1403         vfio_device_put(device);
1404
1405         return 0;
1406 }
1407
1408 /*
1409  * vfio_mig_get_next_state - Compute the next step in the FSM
1410  * @cur_fsm - The current state the device is in
1411  * @new_fsm - The target state to reach
1412  * @next_fsm - Pointer to the next step to get to new_fsm
1413  *
1414  * Return 0 upon success, otherwise -errno
1415  * Upon success the next step in the state progression between cur_fsm and
1416  * new_fsm will be set in next_fsm.
1417  *
1418  * This breaks down requests for combination transitions into smaller steps and
1419  * returns the next step to get to new_fsm. The function may need to be called
1420  * multiple times before reaching new_fsm.
1421  *
1422  */
1423 int vfio_mig_get_next_state(struct vfio_device *device,
1424                             enum vfio_device_mig_state cur_fsm,
1425                             enum vfio_device_mig_state new_fsm,
1426                             enum vfio_device_mig_state *next_fsm)
1427 {
1428         enum { VFIO_DEVICE_NUM_STATES = VFIO_DEVICE_STATE_RUNNING_P2P + 1 };
1429         /*
1430          * The coding in this table requires the driver to implement the
1431          * following FSM arcs:
1432          *         RESUMING -> STOP
1433          *         STOP -> RESUMING
1434          *         STOP -> STOP_COPY
1435          *         STOP_COPY -> STOP
1436          *
1437          * If P2P is supported then the driver must also implement these FSM
1438          * arcs:
1439          *         RUNNING -> RUNNING_P2P
1440          *         RUNNING_P2P -> RUNNING
1441          *         RUNNING_P2P -> STOP
1442          *         STOP -> RUNNING_P2P
1443          * Without P2P the driver must implement:
1444          *         RUNNING -> STOP
1445          *         STOP -> RUNNING
1446          *
1447          * The coding will step through multiple states for some combination
1448          * transitions; if all optional features are supported, this means the
1449          * following ones:
1450          *         RESUMING -> STOP -> RUNNING_P2P
1451          *         RESUMING -> STOP -> RUNNING_P2P -> RUNNING
1452          *         RESUMING -> STOP -> STOP_COPY
1453          *         RUNNING -> RUNNING_P2P -> STOP
1454          *         RUNNING -> RUNNING_P2P -> STOP -> RESUMING
1455          *         RUNNING -> RUNNING_P2P -> STOP -> STOP_COPY
1456          *         RUNNING_P2P -> STOP -> RESUMING
1457          *         RUNNING_P2P -> STOP -> STOP_COPY
1458          *         STOP -> RUNNING_P2P -> RUNNING
1459          *         STOP_COPY -> STOP -> RESUMING
1460          *         STOP_COPY -> STOP -> RUNNING_P2P
1461          *         STOP_COPY -> STOP -> RUNNING_P2P -> RUNNING
1462          */
1463         static const u8 vfio_from_fsm_table[VFIO_DEVICE_NUM_STATES][VFIO_DEVICE_NUM_STATES] = {
1464                 [VFIO_DEVICE_STATE_STOP] = {
1465                         [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_STOP,
1466                         [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_RUNNING_P2P,
1467                         [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP_COPY,
1468                         [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_RESUMING,
1469                         [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_RUNNING_P2P,
1470                         [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
1471                 },
1472                 [VFIO_DEVICE_STATE_RUNNING] = {
1473                         [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_RUNNING_P2P,
1474                         [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_RUNNING,
1475                         [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_RUNNING_P2P,
1476                         [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_RUNNING_P2P,
1477                         [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_RUNNING_P2P,
1478                         [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
1479                 },
1480                 [VFIO_DEVICE_STATE_STOP_COPY] = {
1481                         [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_STOP,
1482                         [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_STOP,
1483                         [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP_COPY,
1484                         [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_STOP,
1485                         [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_STOP,
1486                         [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
1487                 },
1488                 [VFIO_DEVICE_STATE_RESUMING] = {
1489                         [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_STOP,
1490                         [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_STOP,
1491                         [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP,
1492                         [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_RESUMING,
1493                         [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_STOP,
1494                         [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
1495                 },
1496                 [VFIO_DEVICE_STATE_RUNNING_P2P] = {
1497                         [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_STOP,
1498                         [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_RUNNING,
1499                         [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_STOP,
1500                         [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_STOP,
1501                         [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_RUNNING_P2P,
1502                         [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
1503                 },
1504                 [VFIO_DEVICE_STATE_ERROR] = {
1505                         [VFIO_DEVICE_STATE_STOP] = VFIO_DEVICE_STATE_ERROR,
1506                         [VFIO_DEVICE_STATE_RUNNING] = VFIO_DEVICE_STATE_ERROR,
1507                         [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_DEVICE_STATE_ERROR,
1508                         [VFIO_DEVICE_STATE_RESUMING] = VFIO_DEVICE_STATE_ERROR,
1509                         [VFIO_DEVICE_STATE_RUNNING_P2P] = VFIO_DEVICE_STATE_ERROR,
1510                         [VFIO_DEVICE_STATE_ERROR] = VFIO_DEVICE_STATE_ERROR,
1511                 },
1512         };
1513
1514         static const unsigned int state_flags_table[VFIO_DEVICE_NUM_STATES] = {
1515                 [VFIO_DEVICE_STATE_STOP] = VFIO_MIGRATION_STOP_COPY,
1516                 [VFIO_DEVICE_STATE_RUNNING] = VFIO_MIGRATION_STOP_COPY,
1517                 [VFIO_DEVICE_STATE_STOP_COPY] = VFIO_MIGRATION_STOP_COPY,
1518                 [VFIO_DEVICE_STATE_RESUMING] = VFIO_MIGRATION_STOP_COPY,
1519                 [VFIO_DEVICE_STATE_RUNNING_P2P] =
1520                         VFIO_MIGRATION_STOP_COPY | VFIO_MIGRATION_P2P,
1521                 [VFIO_DEVICE_STATE_ERROR] = ~0U,
1522         };
1523
1524         if (WARN_ON(cur_fsm >= ARRAY_SIZE(vfio_from_fsm_table) ||
1525                     (state_flags_table[cur_fsm] & device->migration_flags) !=
1526                         state_flags_table[cur_fsm]))
1527                 return -EINVAL;
1528
1529         if (new_fsm >= ARRAY_SIZE(vfio_from_fsm_table) ||
1530            (state_flags_table[new_fsm] & device->migration_flags) !=
1531                         state_flags_table[new_fsm])
1532                 return -EINVAL;
1533
1534         /*
1535          * Arcs touching optional and unsupported states are skipped over. The
1536          * driver will instead see an arc from the original state to the next
1537          * logical state, as per the above comment.
1538          */
1539         *next_fsm = vfio_from_fsm_table[cur_fsm][new_fsm];
1540         while ((state_flags_table[*next_fsm] & device->migration_flags) !=
1541                         state_flags_table[*next_fsm])
1542                 *next_fsm = vfio_from_fsm_table[*next_fsm][new_fsm];
1543
1544         return (*next_fsm != VFIO_DEVICE_STATE_ERROR) ? 0 : -EINVAL;
1545 }
1546 EXPORT_SYMBOL_GPL(vfio_mig_get_next_state);
1547
1548 /*
1549  * Convert the drivers's struct file into a FD number and return it to userspace
1550  */
1551 static int vfio_ioct_mig_return_fd(struct file *filp, void __user *arg,
1552                                    struct vfio_device_feature_mig_state *mig)
1553 {
1554         int ret;
1555         int fd;
1556
1557         fd = get_unused_fd_flags(O_CLOEXEC);
1558         if (fd < 0) {
1559                 ret = fd;
1560                 goto out_fput;
1561         }
1562
1563         mig->data_fd = fd;
1564         if (copy_to_user(arg, mig, sizeof(*mig))) {
1565                 ret = -EFAULT;
1566                 goto out_put_unused;
1567         }
1568         fd_install(fd, filp);
1569         return 0;
1570
1571 out_put_unused:
1572         put_unused_fd(fd);
1573 out_fput:
1574         fput(filp);
1575         return ret;
1576 }
1577
1578 static int
1579 vfio_ioctl_device_feature_mig_device_state(struct vfio_device *device,
1580                                            u32 flags, void __user *arg,
1581                                            size_t argsz)
1582 {
1583         size_t minsz =
1584                 offsetofend(struct vfio_device_feature_mig_state, data_fd);
1585         struct vfio_device_feature_mig_state mig;
1586         struct file *filp = NULL;
1587         int ret;
1588
1589         if (!device->mig_ops)
1590                 return -ENOTTY;
1591
1592         ret = vfio_check_feature(flags, argsz,
1593                                  VFIO_DEVICE_FEATURE_SET |
1594                                  VFIO_DEVICE_FEATURE_GET,
1595                                  sizeof(mig));
1596         if (ret != 1)
1597                 return ret;
1598
1599         if (copy_from_user(&mig, arg, minsz))
1600                 return -EFAULT;
1601
1602         if (flags & VFIO_DEVICE_FEATURE_GET) {
1603                 enum vfio_device_mig_state curr_state;
1604
1605                 ret = device->mig_ops->migration_get_state(device,
1606                                                            &curr_state);
1607                 if (ret)
1608                         return ret;
1609                 mig.device_state = curr_state;
1610                 goto out_copy;
1611         }
1612
1613         /* Handle the VFIO_DEVICE_FEATURE_SET */
1614         filp = device->mig_ops->migration_set_state(device, mig.device_state);
1615         if (IS_ERR(filp) || !filp)
1616                 goto out_copy;
1617
1618         return vfio_ioct_mig_return_fd(filp, arg, &mig);
1619 out_copy:
1620         mig.data_fd = -1;
1621         if (copy_to_user(arg, &mig, sizeof(mig)))
1622                 return -EFAULT;
1623         if (IS_ERR(filp))
1624                 return PTR_ERR(filp);
1625         return 0;
1626 }
1627
1628 static int vfio_ioctl_device_feature_migration(struct vfio_device *device,
1629                                                u32 flags, void __user *arg,
1630                                                size_t argsz)
1631 {
1632         struct vfio_device_feature_migration mig = {
1633                 .flags = device->migration_flags,
1634         };
1635         int ret;
1636
1637         if (!device->mig_ops)
1638                 return -ENOTTY;
1639
1640         ret = vfio_check_feature(flags, argsz, VFIO_DEVICE_FEATURE_GET,
1641                                  sizeof(mig));
1642         if (ret != 1)
1643                 return ret;
1644         if (copy_to_user(arg, &mig, sizeof(mig)))
1645                 return -EFAULT;
1646         return 0;
1647 }
1648
1649 static int vfio_ioctl_device_feature(struct vfio_device *device,
1650                                      struct vfio_device_feature __user *arg)
1651 {
1652         size_t minsz = offsetofend(struct vfio_device_feature, flags);
1653         struct vfio_device_feature feature;
1654
1655         if (copy_from_user(&feature, arg, minsz))
1656                 return -EFAULT;
1657
1658         if (feature.argsz < minsz)
1659                 return -EINVAL;
1660
1661         /* Check unknown flags */
1662         if (feature.flags &
1663             ~(VFIO_DEVICE_FEATURE_MASK | VFIO_DEVICE_FEATURE_SET |
1664               VFIO_DEVICE_FEATURE_GET | VFIO_DEVICE_FEATURE_PROBE))
1665                 return -EINVAL;
1666
1667         /* GET & SET are mutually exclusive except with PROBE */
1668         if (!(feature.flags & VFIO_DEVICE_FEATURE_PROBE) &&
1669             (feature.flags & VFIO_DEVICE_FEATURE_SET) &&
1670             (feature.flags & VFIO_DEVICE_FEATURE_GET))
1671                 return -EINVAL;
1672
1673         switch (feature.flags & VFIO_DEVICE_FEATURE_MASK) {
1674         case VFIO_DEVICE_FEATURE_MIGRATION:
1675                 return vfio_ioctl_device_feature_migration(
1676                         device, feature.flags, arg->data,
1677                         feature.argsz - minsz);
1678         case VFIO_DEVICE_FEATURE_MIG_DEVICE_STATE:
1679                 return vfio_ioctl_device_feature_mig_device_state(
1680                         device, feature.flags, arg->data,
1681                         feature.argsz - minsz);
1682         default:
1683                 if (unlikely(!device->ops->device_feature))
1684                         return -EINVAL;
1685                 return device->ops->device_feature(device, feature.flags,
1686                                                    arg->data,
1687                                                    feature.argsz - minsz);
1688         }
1689 }
1690
1691 static long vfio_device_fops_unl_ioctl(struct file *filep,
1692                                        unsigned int cmd, unsigned long arg)
1693 {
1694         struct vfio_device *device = filep->private_data;
1695
1696         switch (cmd) {
1697         case VFIO_DEVICE_FEATURE:
1698                 return vfio_ioctl_device_feature(device, (void __user *)arg);
1699         default:
1700                 if (unlikely(!device->ops->ioctl))
1701                         return -EINVAL;
1702                 return device->ops->ioctl(device, cmd, arg);
1703         }
1704 }
1705
1706 static ssize_t vfio_device_fops_read(struct file *filep, char __user *buf,
1707                                      size_t count, loff_t *ppos)
1708 {
1709         struct vfio_device *device = filep->private_data;
1710
1711         if (unlikely(!device->ops->read))
1712                 return -EINVAL;
1713
1714         return device->ops->read(device, buf, count, ppos);
1715 }
1716
1717 static ssize_t vfio_device_fops_write(struct file *filep,
1718                                       const char __user *buf,
1719                                       size_t count, loff_t *ppos)
1720 {
1721         struct vfio_device *device = filep->private_data;
1722
1723         if (unlikely(!device->ops->write))
1724                 return -EINVAL;
1725
1726         return device->ops->write(device, buf, count, ppos);
1727 }
1728
1729 static int vfio_device_fops_mmap(struct file *filep, struct vm_area_struct *vma)
1730 {
1731         struct vfio_device *device = filep->private_data;
1732
1733         if (unlikely(!device->ops->mmap))
1734                 return -EINVAL;
1735
1736         return device->ops->mmap(device, vma);
1737 }
1738
1739 static const struct file_operations vfio_device_fops = {
1740         .owner          = THIS_MODULE,
1741         .release        = vfio_device_fops_release,
1742         .read           = vfio_device_fops_read,
1743         .write          = vfio_device_fops_write,
1744         .unlocked_ioctl = vfio_device_fops_unl_ioctl,
1745         .compat_ioctl   = compat_ptr_ioctl,
1746         .mmap           = vfio_device_fops_mmap,
1747 };
1748
1749 /**
1750  * vfio_file_iommu_group - Return the struct iommu_group for the vfio group file
1751  * @file: VFIO group file
1752  *
1753  * The returned iommu_group is valid as long as a ref is held on the file.
1754  */
1755 struct iommu_group *vfio_file_iommu_group(struct file *file)
1756 {
1757         struct vfio_group *group = file->private_data;
1758
1759         if (file->f_op != &vfio_group_fops)
1760                 return NULL;
1761         return group->iommu_group;
1762 }
1763 EXPORT_SYMBOL_GPL(vfio_file_iommu_group);
1764
1765 /**
1766  * vfio_file_enforced_coherent - True if the DMA associated with the VFIO file
1767  *        is always CPU cache coherent
1768  * @file: VFIO group file
1769  *
1770  * Enforced coherency means that the IOMMU ignores things like the PCIe no-snoop
1771  * bit in DMA transactions. A return of false indicates that the user has
1772  * rights to access additional instructions such as wbinvd on x86.
1773  */
1774 bool vfio_file_enforced_coherent(struct file *file)
1775 {
1776         struct vfio_group *group = file->private_data;
1777         bool ret;
1778
1779         if (file->f_op != &vfio_group_fops)
1780                 return true;
1781
1782         down_read(&group->group_rwsem);
1783         if (group->container) {
1784                 ret = vfio_ioctl_check_extension(group->container,
1785                                                  VFIO_DMA_CC_IOMMU);
1786         } else {
1787                 /*
1788                  * Since the coherency state is determined only once a container
1789                  * is attached the user must do so before they can prove they
1790                  * have permission.
1791                  */
1792                 ret = true;
1793         }
1794         up_read(&group->group_rwsem);
1795         return ret;
1796 }
1797 EXPORT_SYMBOL_GPL(vfio_file_enforced_coherent);
1798
1799 /**
1800  * vfio_file_set_kvm - Link a kvm with VFIO drivers
1801  * @file: VFIO group file
1802  * @kvm: KVM to link
1803  *
1804  * When a VFIO device is first opened the KVM will be available in
1805  * device->kvm if one was associated with the group.
1806  */
1807 void vfio_file_set_kvm(struct file *file, struct kvm *kvm)
1808 {
1809         struct vfio_group *group = file->private_data;
1810
1811         if (file->f_op != &vfio_group_fops)
1812                 return;
1813
1814         down_write(&group->group_rwsem);
1815         group->kvm = kvm;
1816         up_write(&group->group_rwsem);
1817 }
1818 EXPORT_SYMBOL_GPL(vfio_file_set_kvm);
1819
1820 /**
1821  * vfio_file_has_dev - True if the VFIO file is a handle for device
1822  * @file: VFIO file to check
1823  * @device: Device that must be part of the file
1824  *
1825  * Returns true if given file has permission to manipulate the given device.
1826  */
1827 bool vfio_file_has_dev(struct file *file, struct vfio_device *device)
1828 {
1829         struct vfio_group *group = file->private_data;
1830
1831         if (file->f_op != &vfio_group_fops)
1832                 return false;
1833
1834         return group == device->group;
1835 }
1836 EXPORT_SYMBOL_GPL(vfio_file_has_dev);
1837
1838 /*
1839  * Sub-module support
1840  */
1841 /*
1842  * Helper for managing a buffer of info chain capabilities, allocate or
1843  * reallocate a buffer with additional @size, filling in @id and @version
1844  * of the capability.  A pointer to the new capability is returned.
1845  *
1846  * NB. The chain is based at the head of the buffer, so new entries are
1847  * added to the tail, vfio_info_cap_shift() should be called to fixup the
1848  * next offsets prior to copying to the user buffer.
1849  */
1850 struct vfio_info_cap_header *vfio_info_cap_add(struct vfio_info_cap *caps,
1851                                                size_t size, u16 id, u16 version)
1852 {
1853         void *buf;
1854         struct vfio_info_cap_header *header, *tmp;
1855
1856         buf = krealloc(caps->buf, caps->size + size, GFP_KERNEL);
1857         if (!buf) {
1858                 kfree(caps->buf);
1859                 caps->buf = NULL;
1860                 caps->size = 0;
1861                 return ERR_PTR(-ENOMEM);
1862         }
1863
1864         caps->buf = buf;
1865         header = buf + caps->size;
1866
1867         /* Eventually copied to user buffer, zero */
1868         memset(header, 0, size);
1869
1870         header->id = id;
1871         header->version = version;
1872
1873         /* Add to the end of the capability chain */
1874         for (tmp = buf; tmp->next; tmp = buf + tmp->next)
1875                 ; /* nothing */
1876
1877         tmp->next = caps->size;
1878         caps->size += size;
1879
1880         return header;
1881 }
1882 EXPORT_SYMBOL_GPL(vfio_info_cap_add);
1883
1884 void vfio_info_cap_shift(struct vfio_info_cap *caps, size_t offset)
1885 {
1886         struct vfio_info_cap_header *tmp;
1887         void *buf = (void *)caps->buf;
1888
1889         for (tmp = buf; tmp->next; tmp = buf + tmp->next - offset)
1890                 tmp->next += offset;
1891 }
1892 EXPORT_SYMBOL(vfio_info_cap_shift);
1893
1894 int vfio_info_add_capability(struct vfio_info_cap *caps,
1895                              struct vfio_info_cap_header *cap, size_t size)
1896 {
1897         struct vfio_info_cap_header *header;
1898
1899         header = vfio_info_cap_add(caps, size, cap->id, cap->version);
1900         if (IS_ERR(header))
1901                 return PTR_ERR(header);
1902
1903         memcpy(header + 1, cap + 1, size - sizeof(*header));
1904
1905         return 0;
1906 }
1907 EXPORT_SYMBOL(vfio_info_add_capability);
1908
1909 int vfio_set_irqs_validate_and_prepare(struct vfio_irq_set *hdr, int num_irqs,
1910                                        int max_irq_type, size_t *data_size)
1911 {
1912         unsigned long minsz;
1913         size_t size;
1914
1915         minsz = offsetofend(struct vfio_irq_set, count);
1916
1917         if ((hdr->argsz < minsz) || (hdr->index >= max_irq_type) ||
1918             (hdr->count >= (U32_MAX - hdr->start)) ||
1919             (hdr->flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK |
1920                                 VFIO_IRQ_SET_ACTION_TYPE_MASK)))
1921                 return -EINVAL;
1922
1923         if (data_size)
1924                 *data_size = 0;
1925
1926         if (hdr->start >= num_irqs || hdr->start + hdr->count > num_irqs)
1927                 return -EINVAL;
1928
1929         switch (hdr->flags & VFIO_IRQ_SET_DATA_TYPE_MASK) {
1930         case VFIO_IRQ_SET_DATA_NONE:
1931                 size = 0;
1932                 break;
1933         case VFIO_IRQ_SET_DATA_BOOL:
1934                 size = sizeof(uint8_t);
1935                 break;
1936         case VFIO_IRQ_SET_DATA_EVENTFD:
1937                 size = sizeof(int32_t);
1938                 break;
1939         default:
1940                 return -EINVAL;
1941         }
1942
1943         if (size) {
1944                 if (hdr->argsz - minsz < hdr->count * size)
1945                         return -EINVAL;
1946
1947                 if (!data_size)
1948                         return -EINVAL;
1949
1950                 *data_size = hdr->count * size;
1951         }
1952
1953         return 0;
1954 }
1955 EXPORT_SYMBOL(vfio_set_irqs_validate_and_prepare);
1956
1957 /*
1958  * Pin a set of guest PFNs and return their associated host PFNs for local
1959  * domain only.
1960  * @device [in]  : device
1961  * @user_pfn [in]: array of user/guest PFNs to be pinned.
1962  * @npage [in]   : count of elements in user_pfn array.  This count should not
1963  *                 be greater VFIO_PIN_PAGES_MAX_ENTRIES.
1964  * @prot [in]    : protection flags
1965  * @phys_pfn[out]: array of host PFNs
1966  * Return error or number of pages pinned.
1967  */
1968 int vfio_pin_pages(struct vfio_device *device, unsigned long *user_pfn,
1969                    int npage, int prot, unsigned long *phys_pfn)
1970 {
1971         struct vfio_container *container;
1972         struct vfio_group *group = device->group;
1973         struct vfio_iommu_driver *driver;
1974         int ret;
1975
1976         if (!user_pfn || !phys_pfn || !npage ||
1977             !vfio_assert_device_open(device))
1978                 return -EINVAL;
1979
1980         if (npage > VFIO_PIN_PAGES_MAX_ENTRIES)
1981                 return -E2BIG;
1982
1983         if (group->dev_counter > 1)
1984                 return -EINVAL;
1985
1986         /* group->container cannot change while a vfio device is open */
1987         container = group->container;
1988         driver = container->iommu_driver;
1989         if (likely(driver && driver->ops->pin_pages))
1990                 ret = driver->ops->pin_pages(container->iommu_data,
1991                                              group->iommu_group, user_pfn,
1992                                              npage, prot, phys_pfn);
1993         else
1994                 ret = -ENOTTY;
1995
1996         return ret;
1997 }
1998 EXPORT_SYMBOL(vfio_pin_pages);
1999
2000 /*
2001  * Unpin set of host PFNs for local domain only.
2002  * @device [in]  : device
2003  * @user_pfn [in]: array of user/guest PFNs to be unpinned. Number of user/guest
2004  *                 PFNs should not be greater than VFIO_PIN_PAGES_MAX_ENTRIES.
2005  * @npage [in]   : count of elements in user_pfn array.  This count should not
2006  *                 be greater than VFIO_PIN_PAGES_MAX_ENTRIES.
2007  * Return error or number of pages unpinned.
2008  */
2009 int vfio_unpin_pages(struct vfio_device *device, unsigned long *user_pfn,
2010                      int npage)
2011 {
2012         struct vfio_container *container;
2013         struct vfio_iommu_driver *driver;
2014         int ret;
2015
2016         if (!user_pfn || !npage || !vfio_assert_device_open(device))
2017                 return -EINVAL;
2018
2019         if (npage > VFIO_PIN_PAGES_MAX_ENTRIES)
2020                 return -E2BIG;
2021
2022         /* group->container cannot change while a vfio device is open */
2023         container = device->group->container;
2024         driver = container->iommu_driver;
2025         if (likely(driver && driver->ops->unpin_pages))
2026                 ret = driver->ops->unpin_pages(container->iommu_data, user_pfn,
2027                                                npage);
2028         else
2029                 ret = -ENOTTY;
2030
2031         return ret;
2032 }
2033 EXPORT_SYMBOL(vfio_unpin_pages);
2034
2035 /*
2036  * This interface allows the CPUs to perform some sort of virtual DMA on
2037  * behalf of the device.
2038  *
2039  * CPUs read/write from/into a range of IOVAs pointing to user space memory
2040  * into/from a kernel buffer.
2041  *
2042  * As the read/write of user space memory is conducted via the CPUs and is
2043  * not a real device DMA, it is not necessary to pin the user space memory.
2044  *
2045  * @device [in]         : VFIO device
2046  * @user_iova [in]      : base IOVA of a user space buffer
2047  * @data [in]           : pointer to kernel buffer
2048  * @len [in]            : kernel buffer length
2049  * @write               : indicate read or write
2050  * Return error code on failure or 0 on success.
2051  */
2052 int vfio_dma_rw(struct vfio_device *device, dma_addr_t user_iova, void *data,
2053                 size_t len, bool write)
2054 {
2055         struct vfio_container *container;
2056         struct vfio_iommu_driver *driver;
2057         int ret = 0;
2058
2059         if (!data || len <= 0 || !vfio_assert_device_open(device))
2060                 return -EINVAL;
2061
2062         /* group->container cannot change while a vfio device is open */
2063         container = device->group->container;
2064         driver = container->iommu_driver;
2065
2066         if (likely(driver && driver->ops->dma_rw))
2067                 ret = driver->ops->dma_rw(container->iommu_data,
2068                                           user_iova, data, len, write);
2069         else
2070                 ret = -ENOTTY;
2071         return ret;
2072 }
2073 EXPORT_SYMBOL(vfio_dma_rw);
2074
2075 /*
2076  * Module/class support
2077  */
2078 static char *vfio_devnode(struct device *dev, umode_t *mode)
2079 {
2080         return kasprintf(GFP_KERNEL, "vfio/%s", dev_name(dev));
2081 }
2082
2083 static struct miscdevice vfio_dev = {
2084         .minor = VFIO_MINOR,
2085         .name = "vfio",
2086         .fops = &vfio_fops,
2087         .nodename = "vfio/vfio",
2088         .mode = S_IRUGO | S_IWUGO,
2089 };
2090
2091 static int __init vfio_init(void)
2092 {
2093         int ret;
2094
2095         ida_init(&vfio.group_ida);
2096         mutex_init(&vfio.group_lock);
2097         mutex_init(&vfio.iommu_drivers_lock);
2098         INIT_LIST_HEAD(&vfio.group_list);
2099         INIT_LIST_HEAD(&vfio.iommu_drivers_list);
2100
2101         ret = misc_register(&vfio_dev);
2102         if (ret) {
2103                 pr_err("vfio: misc device register failed\n");
2104                 return ret;
2105         }
2106
2107         /* /dev/vfio/$GROUP */
2108         vfio.class = class_create(THIS_MODULE, "vfio");
2109         if (IS_ERR(vfio.class)) {
2110                 ret = PTR_ERR(vfio.class);
2111                 goto err_class;
2112         }
2113
2114         vfio.class->devnode = vfio_devnode;
2115
2116         ret = alloc_chrdev_region(&vfio.group_devt, 0, MINORMASK + 1, "vfio");
2117         if (ret)
2118                 goto err_alloc_chrdev;
2119
2120 #ifdef CONFIG_VFIO_NOIOMMU
2121         ret = vfio_register_iommu_driver(&vfio_noiommu_ops);
2122 #endif
2123         if (ret)
2124                 goto err_driver_register;
2125
2126         pr_info(DRIVER_DESC " version: " DRIVER_VERSION "\n");
2127         return 0;
2128
2129 err_driver_register:
2130         unregister_chrdev_region(vfio.group_devt, MINORMASK + 1);
2131 err_alloc_chrdev:
2132         class_destroy(vfio.class);
2133         vfio.class = NULL;
2134 err_class:
2135         misc_deregister(&vfio_dev);
2136         return ret;
2137 }
2138
2139 static void __exit vfio_cleanup(void)
2140 {
2141         WARN_ON(!list_empty(&vfio.group_list));
2142
2143 #ifdef CONFIG_VFIO_NOIOMMU
2144         vfio_unregister_iommu_driver(&vfio_noiommu_ops);
2145 #endif
2146         ida_destroy(&vfio.group_ida);
2147         unregister_chrdev_region(vfio.group_devt, MINORMASK + 1);
2148         class_destroy(vfio.class);
2149         vfio.class = NULL;
2150         misc_deregister(&vfio_dev);
2151         xa_destroy(&vfio_device_set_xa);
2152 }
2153
2154 module_init(vfio_init);
2155 module_exit(vfio_cleanup);
2156
2157 MODULE_VERSION(DRIVER_VERSION);
2158 MODULE_LICENSE("GPL v2");
2159 MODULE_AUTHOR(DRIVER_AUTHOR);
2160 MODULE_DESCRIPTION(DRIVER_DESC);
2161 MODULE_ALIAS_MISCDEV(VFIO_MINOR);
2162 MODULE_ALIAS("devname:vfio/vfio");
2163 MODULE_SOFTDEP("post: vfio_iommu_type1 vfio_iommu_spapr_tce");