]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/vfio/vfio.c
Merge tag 'f2fs-for-3.9' of git://git.kernel.org/pub/scm/linux/kernel/git/jaegeuk...
[karo-tx-linux.git] / drivers / vfio / vfio.c
1 /*
2  * VFIO core
3  *
4  * Copyright (C) 2012 Red Hat, Inc.  All rights reserved.
5  *     Author: Alex Williamson <alex.williamson@redhat.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  *
11  * Derived from original vfio:
12  * Copyright 2010 Cisco Systems, Inc.  All rights reserved.
13  * Author: Tom Lyon, pugs@cisco.com
14  */
15
16 #include <linux/cdev.h>
17 #include <linux/compat.h>
18 #include <linux/device.h>
19 #include <linux/file.h>
20 #include <linux/anon_inodes.h>
21 #include <linux/fs.h>
22 #include <linux/idr.h>
23 #include <linux/iommu.h>
24 #include <linux/list.h>
25 #include <linux/module.h>
26 #include <linux/mutex.h>
27 #include <linux/sched.h>
28 #include <linux/slab.h>
29 #include <linux/string.h>
30 #include <linux/uaccess.h>
31 #include <linux/vfio.h>
32 #include <linux/wait.h>
33
34 #define DRIVER_VERSION  "0.3"
35 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
36 #define DRIVER_DESC     "VFIO - User Level meta-driver"
37
38 static struct vfio {
39         struct class                    *class;
40         struct list_head                iommu_drivers_list;
41         struct mutex                    iommu_drivers_lock;
42         struct list_head                group_list;
43         struct idr                      group_idr;
44         struct mutex                    group_lock;
45         struct cdev                     group_cdev;
46         struct device                   *dev;
47         dev_t                           devt;
48         struct cdev                     cdev;
49         wait_queue_head_t               release_q;
50 } vfio;
51
52 struct vfio_iommu_driver {
53         const struct vfio_iommu_driver_ops      *ops;
54         struct list_head                        vfio_next;
55 };
56
57 struct vfio_container {
58         struct kref                     kref;
59         struct list_head                group_list;
60         struct mutex                    group_lock;
61         struct vfio_iommu_driver        *iommu_driver;
62         void                            *iommu_data;
63 };
64
65 struct vfio_group {
66         struct kref                     kref;
67         int                             minor;
68         atomic_t                        container_users;
69         struct iommu_group              *iommu_group;
70         struct vfio_container           *container;
71         struct list_head                device_list;
72         struct mutex                    device_lock;
73         struct device                   *dev;
74         struct notifier_block           nb;
75         struct list_head                vfio_next;
76         struct list_head                container_next;
77 };
78
79 struct vfio_device {
80         struct kref                     kref;
81         struct device                   *dev;
82         const struct vfio_device_ops    *ops;
83         struct vfio_group               *group;
84         struct list_head                group_next;
85         void                            *device_data;
86 };
87
88 /**
89  * IOMMU driver registration
90  */
91 int vfio_register_iommu_driver(const struct vfio_iommu_driver_ops *ops)
92 {
93         struct vfio_iommu_driver *driver, *tmp;
94
95         driver = kzalloc(sizeof(*driver), GFP_KERNEL);
96         if (!driver)
97                 return -ENOMEM;
98
99         driver->ops = ops;
100
101         mutex_lock(&vfio.iommu_drivers_lock);
102
103         /* Check for duplicates */
104         list_for_each_entry(tmp, &vfio.iommu_drivers_list, vfio_next) {
105                 if (tmp->ops == ops) {
106                         mutex_unlock(&vfio.iommu_drivers_lock);
107                         kfree(driver);
108                         return -EINVAL;
109                 }
110         }
111
112         list_add(&driver->vfio_next, &vfio.iommu_drivers_list);
113
114         mutex_unlock(&vfio.iommu_drivers_lock);
115
116         return 0;
117 }
118 EXPORT_SYMBOL_GPL(vfio_register_iommu_driver);
119
120 void vfio_unregister_iommu_driver(const struct vfio_iommu_driver_ops *ops)
121 {
122         struct vfio_iommu_driver *driver;
123
124         mutex_lock(&vfio.iommu_drivers_lock);
125         list_for_each_entry(driver, &vfio.iommu_drivers_list, vfio_next) {
126                 if (driver->ops == ops) {
127                         list_del(&driver->vfio_next);
128                         mutex_unlock(&vfio.iommu_drivers_lock);
129                         kfree(driver);
130                         return;
131                 }
132         }
133         mutex_unlock(&vfio.iommu_drivers_lock);
134 }
135 EXPORT_SYMBOL_GPL(vfio_unregister_iommu_driver);
136
137 /**
138  * Group minor allocation/free - both called with vfio.group_lock held
139  */
140 static int vfio_alloc_group_minor(struct vfio_group *group)
141 {
142         int ret, minor;
143
144 again:
145         if (unlikely(idr_pre_get(&vfio.group_idr, GFP_KERNEL) == 0))
146                 return -ENOMEM;
147
148         /* index 0 is used by /dev/vfio/vfio */
149         ret = idr_get_new_above(&vfio.group_idr, group, 1, &minor);
150         if (ret == -EAGAIN)
151                 goto again;
152         if (ret || minor > MINORMASK) {
153                 if (minor > MINORMASK)
154                         idr_remove(&vfio.group_idr, minor);
155                 return -ENOSPC;
156         }
157
158         return minor;
159 }
160
161 static void vfio_free_group_minor(int minor)
162 {
163         idr_remove(&vfio.group_idr, minor);
164 }
165
166 static int vfio_iommu_group_notifier(struct notifier_block *nb,
167                                      unsigned long action, void *data);
168 static void vfio_group_get(struct vfio_group *group);
169
170 /**
171  * Container objects - containers are created when /dev/vfio/vfio is
172  * opened, but their lifecycle extends until the last user is done, so
173  * it's freed via kref.  Must support container/group/device being
174  * closed in any order.
175  */
176 static void vfio_container_get(struct vfio_container *container)
177 {
178         kref_get(&container->kref);
179 }
180
181 static void vfio_container_release(struct kref *kref)
182 {
183         struct vfio_container *container;
184         container = container_of(kref, struct vfio_container, kref);
185
186         kfree(container);
187 }
188
189 static void vfio_container_put(struct vfio_container *container)
190 {
191         kref_put(&container->kref, vfio_container_release);
192 }
193
194 static void vfio_group_unlock_and_free(struct vfio_group *group)
195 {
196         mutex_unlock(&vfio.group_lock);
197         /*
198          * Unregister outside of lock.  A spurious callback is harmless now
199          * that the group is no longer in vfio.group_list.
200          */
201         iommu_group_unregister_notifier(group->iommu_group, &group->nb);
202         kfree(group);
203 }
204
205 /**
206  * Group objects - create, release, get, put, search
207  */
208 static struct vfio_group *vfio_create_group(struct iommu_group *iommu_group)
209 {
210         struct vfio_group *group, *tmp;
211         struct device *dev;
212         int ret, minor;
213
214         group = kzalloc(sizeof(*group), GFP_KERNEL);
215         if (!group)
216                 return ERR_PTR(-ENOMEM);
217
218         kref_init(&group->kref);
219         INIT_LIST_HEAD(&group->device_list);
220         mutex_init(&group->device_lock);
221         atomic_set(&group->container_users, 0);
222         group->iommu_group = iommu_group;
223
224         group->nb.notifier_call = vfio_iommu_group_notifier;
225
226         /*
227          * blocking notifiers acquire a rwsem around registering and hold
228          * it around callback.  Therefore, need to register outside of
229          * vfio.group_lock to avoid A-B/B-A contention.  Our callback won't
230          * do anything unless it can find the group in vfio.group_list, so
231          * no harm in registering early.
232          */
233         ret = iommu_group_register_notifier(iommu_group, &group->nb);
234         if (ret) {
235                 kfree(group);
236                 return ERR_PTR(ret);
237         }
238
239         mutex_lock(&vfio.group_lock);
240
241         minor = vfio_alloc_group_minor(group);
242         if (minor < 0) {
243                 vfio_group_unlock_and_free(group);
244                 return ERR_PTR(minor);
245         }
246
247         /* Did we race creating this group? */
248         list_for_each_entry(tmp, &vfio.group_list, vfio_next) {
249                 if (tmp->iommu_group == iommu_group) {
250                         vfio_group_get(tmp);
251                         vfio_free_group_minor(minor);
252                         vfio_group_unlock_and_free(group);
253                         return tmp;
254                 }
255         }
256
257         dev = device_create(vfio.class, NULL, MKDEV(MAJOR(vfio.devt), minor),
258                             group, "%d", iommu_group_id(iommu_group));
259         if (IS_ERR(dev)) {
260                 vfio_free_group_minor(minor);
261                 vfio_group_unlock_and_free(group);
262                 return (struct vfio_group *)dev; /* ERR_PTR */
263         }
264
265         group->minor = minor;
266         group->dev = dev;
267
268         list_add(&group->vfio_next, &vfio.group_list);
269
270         mutex_unlock(&vfio.group_lock);
271
272         return group;
273 }
274
275 /* called with vfio.group_lock held */
276 static void vfio_group_release(struct kref *kref)
277 {
278         struct vfio_group *group = container_of(kref, struct vfio_group, kref);
279
280         WARN_ON(!list_empty(&group->device_list));
281
282         device_destroy(vfio.class, MKDEV(MAJOR(vfio.devt), group->minor));
283         list_del(&group->vfio_next);
284         vfio_free_group_minor(group->minor);
285         vfio_group_unlock_and_free(group);
286 }
287
288 static void vfio_group_put(struct vfio_group *group)
289 {
290         kref_put_mutex(&group->kref, vfio_group_release, &vfio.group_lock);
291 }
292
293 /* Assume group_lock or group reference is held */
294 static void vfio_group_get(struct vfio_group *group)
295 {
296         kref_get(&group->kref);
297 }
298
299 /*
300  * Not really a try as we will sleep for mutex, but we need to make
301  * sure the group pointer is valid under lock and get a reference.
302  */
303 static struct vfio_group *vfio_group_try_get(struct vfio_group *group)
304 {
305         struct vfio_group *target = group;
306
307         mutex_lock(&vfio.group_lock);
308         list_for_each_entry(group, &vfio.group_list, vfio_next) {
309                 if (group == target) {
310                         vfio_group_get(group);
311                         mutex_unlock(&vfio.group_lock);
312                         return group;
313                 }
314         }
315         mutex_unlock(&vfio.group_lock);
316
317         return NULL;
318 }
319
320 static
321 struct vfio_group *vfio_group_get_from_iommu(struct iommu_group *iommu_group)
322 {
323         struct vfio_group *group;
324
325         mutex_lock(&vfio.group_lock);
326         list_for_each_entry(group, &vfio.group_list, vfio_next) {
327                 if (group->iommu_group == iommu_group) {
328                         vfio_group_get(group);
329                         mutex_unlock(&vfio.group_lock);
330                         return group;
331                 }
332         }
333         mutex_unlock(&vfio.group_lock);
334
335         return NULL;
336 }
337
338 static struct vfio_group *vfio_group_get_from_minor(int minor)
339 {
340         struct vfio_group *group;
341
342         mutex_lock(&vfio.group_lock);
343         group = idr_find(&vfio.group_idr, minor);
344         if (!group) {
345                 mutex_unlock(&vfio.group_lock);
346                 return NULL;
347         }
348         vfio_group_get(group);
349         mutex_unlock(&vfio.group_lock);
350
351         return group;
352 }
353
354 /**
355  * Device objects - create, release, get, put, search
356  */
357 static
358 struct vfio_device *vfio_group_create_device(struct vfio_group *group,
359                                              struct device *dev,
360                                              const struct vfio_device_ops *ops,
361                                              void *device_data)
362 {
363         struct vfio_device *device;
364         int ret;
365
366         device = kzalloc(sizeof(*device), GFP_KERNEL);
367         if (!device)
368                 return ERR_PTR(-ENOMEM);
369
370         kref_init(&device->kref);
371         device->dev = dev;
372         device->group = group;
373         device->ops = ops;
374         device->device_data = device_data;
375
376         ret = dev_set_drvdata(dev, device);
377         if (ret) {
378                 kfree(device);
379                 return ERR_PTR(ret);
380         }
381
382         /* No need to get group_lock, caller has group reference */
383         vfio_group_get(group);
384
385         mutex_lock(&group->device_lock);
386         list_add(&device->group_next, &group->device_list);
387         mutex_unlock(&group->device_lock);
388
389         return device;
390 }
391
392 static void vfio_device_release(struct kref *kref)
393 {
394         struct vfio_device *device = container_of(kref,
395                                                   struct vfio_device, kref);
396         struct vfio_group *group = device->group;
397
398         list_del(&device->group_next);
399         mutex_unlock(&group->device_lock);
400
401         dev_set_drvdata(device->dev, NULL);
402
403         kfree(device);
404
405         /* vfio_del_group_dev may be waiting for this device */
406         wake_up(&vfio.release_q);
407 }
408
409 /* Device reference always implies a group reference */
410 static void vfio_device_put(struct vfio_device *device)
411 {
412         struct vfio_group *group = device->group;
413         kref_put_mutex(&device->kref, vfio_device_release, &group->device_lock);
414         vfio_group_put(group);
415 }
416
417 static void vfio_device_get(struct vfio_device *device)
418 {
419         vfio_group_get(device->group);
420         kref_get(&device->kref);
421 }
422
423 static struct vfio_device *vfio_group_get_device(struct vfio_group *group,
424                                                  struct device *dev)
425 {
426         struct vfio_device *device;
427
428         mutex_lock(&group->device_lock);
429         list_for_each_entry(device, &group->device_list, group_next) {
430                 if (device->dev == dev) {
431                         vfio_device_get(device);
432                         mutex_unlock(&group->device_lock);
433                         return device;
434                 }
435         }
436         mutex_unlock(&group->device_lock);
437         return NULL;
438 }
439
440 /*
441  * Whitelist some drivers that we know are safe (no dma) or just sit on
442  * a device.  It's not always practical to leave a device within a group
443  * driverless as it could get re-bound to something unsafe.
444  */
445 static const char * const vfio_driver_whitelist[] = { "pci-stub", "pcieport" };
446
447 static bool vfio_whitelisted_driver(struct device_driver *drv)
448 {
449         int i;
450
451         for (i = 0; i < ARRAY_SIZE(vfio_driver_whitelist); i++) {
452                 if (!strcmp(drv->name, vfio_driver_whitelist[i]))
453                         return true;
454         }
455
456         return false;
457 }
458
459 /*
460  * A vfio group is viable for use by userspace if all devices are either
461  * driver-less or bound to a vfio or whitelisted driver.  We test the
462  * latter by the existence of a struct vfio_device matching the dev.
463  */
464 static int vfio_dev_viable(struct device *dev, void *data)
465 {
466         struct vfio_group *group = data;
467         struct vfio_device *device;
468         struct device_driver *drv = ACCESS_ONCE(dev->driver);
469
470         if (!drv || vfio_whitelisted_driver(drv))
471                 return 0;
472
473         device = vfio_group_get_device(group, dev);
474         if (device) {
475                 vfio_device_put(device);
476                 return 0;
477         }
478
479         return -EINVAL;
480 }
481
482 /**
483  * Async device support
484  */
485 static int vfio_group_nb_add_dev(struct vfio_group *group, struct device *dev)
486 {
487         struct vfio_device *device;
488
489         /* Do we already know about it?  We shouldn't */
490         device = vfio_group_get_device(group, dev);
491         if (WARN_ON_ONCE(device)) {
492                 vfio_device_put(device);
493                 return 0;
494         }
495
496         /* Nothing to do for idle groups */
497         if (!atomic_read(&group->container_users))
498                 return 0;
499
500         /* TODO Prevent device auto probing */
501         WARN("Device %s added to live group %d!\n", dev_name(dev),
502              iommu_group_id(group->iommu_group));
503
504         return 0;
505 }
506
507 static int vfio_group_nb_del_dev(struct vfio_group *group, struct device *dev)
508 {
509         struct vfio_device *device;
510
511         /*
512          * Expect to fall out here.  If a device was in use, it would
513          * have been bound to a vfio sub-driver, which would have blocked
514          * in .remove at vfio_del_group_dev.  Sanity check that we no
515          * longer track the device, so it's safe to remove.
516          */
517         device = vfio_group_get_device(group, dev);
518         if (likely(!device))
519                 return 0;
520
521         WARN("Device %s removed from live group %d!\n", dev_name(dev),
522              iommu_group_id(group->iommu_group));
523
524         vfio_device_put(device);
525         return 0;
526 }
527
528 static int vfio_group_nb_verify(struct vfio_group *group, struct device *dev)
529 {
530         /* We don't care what happens when the group isn't in use */
531         if (!atomic_read(&group->container_users))
532                 return 0;
533
534         return vfio_dev_viable(dev, group);
535 }
536
537 static int vfio_iommu_group_notifier(struct notifier_block *nb,
538                                      unsigned long action, void *data)
539 {
540         struct vfio_group *group = container_of(nb, struct vfio_group, nb);
541         struct device *dev = data;
542
543         /*
544          * Need to go through a group_lock lookup to get a reference or
545          * we risk racing a group being removed.  Leave a WARN_ON for
546          * debuging, but if the group no longer exists, a spurious notify
547          * is harmless.
548          */
549         group = vfio_group_try_get(group);
550         if (WARN_ON(!group))
551                 return NOTIFY_OK;
552
553         switch (action) {
554         case IOMMU_GROUP_NOTIFY_ADD_DEVICE:
555                 vfio_group_nb_add_dev(group, dev);
556                 break;
557         case IOMMU_GROUP_NOTIFY_DEL_DEVICE:
558                 vfio_group_nb_del_dev(group, dev);
559                 break;
560         case IOMMU_GROUP_NOTIFY_BIND_DRIVER:
561                 pr_debug("%s: Device %s, group %d binding to driver\n",
562                          __func__, dev_name(dev),
563                          iommu_group_id(group->iommu_group));
564                 break;
565         case IOMMU_GROUP_NOTIFY_BOUND_DRIVER:
566                 pr_debug("%s: Device %s, group %d bound to driver %s\n",
567                          __func__, dev_name(dev),
568                          iommu_group_id(group->iommu_group), dev->driver->name);
569                 BUG_ON(vfio_group_nb_verify(group, dev));
570                 break;
571         case IOMMU_GROUP_NOTIFY_UNBIND_DRIVER:
572                 pr_debug("%s: Device %s, group %d unbinding from driver %s\n",
573                          __func__, dev_name(dev),
574                          iommu_group_id(group->iommu_group), dev->driver->name);
575                 break;
576         case IOMMU_GROUP_NOTIFY_UNBOUND_DRIVER:
577                 pr_debug("%s: Device %s, group %d unbound from driver\n",
578                          __func__, dev_name(dev),
579                          iommu_group_id(group->iommu_group));
580                 /*
581                  * XXX An unbound device in a live group is ok, but we'd
582                  * really like to avoid the above BUG_ON by preventing other
583                  * drivers from binding to it.  Once that occurs, we have to
584                  * stop the system to maintain isolation.  At a minimum, we'd
585                  * want a toggle to disable driver auto probe for this device.
586                  */
587                 break;
588         }
589
590         vfio_group_put(group);
591         return NOTIFY_OK;
592 }
593
594 /**
595  * VFIO driver API
596  */
597 int vfio_add_group_dev(struct device *dev,
598                        const struct vfio_device_ops *ops, void *device_data)
599 {
600         struct iommu_group *iommu_group;
601         struct vfio_group *group;
602         struct vfio_device *device;
603
604         iommu_group = iommu_group_get(dev);
605         if (!iommu_group)
606                 return -EINVAL;
607
608         group = vfio_group_get_from_iommu(iommu_group);
609         if (!group) {
610                 group = vfio_create_group(iommu_group);
611                 if (IS_ERR(group)) {
612                         iommu_group_put(iommu_group);
613                         return PTR_ERR(group);
614                 }
615         }
616
617         device = vfio_group_get_device(group, dev);
618         if (device) {
619                 WARN(1, "Device %s already exists on group %d\n",
620                      dev_name(dev), iommu_group_id(iommu_group));
621                 vfio_device_put(device);
622                 vfio_group_put(group);
623                 iommu_group_put(iommu_group);
624                 return -EBUSY;
625         }
626
627         device = vfio_group_create_device(group, dev, ops, device_data);
628         if (IS_ERR(device)) {
629                 vfio_group_put(group);
630                 iommu_group_put(iommu_group);
631                 return PTR_ERR(device);
632         }
633
634         /*
635          * Added device holds reference to iommu_group and vfio_device
636          * (which in turn holds reference to vfio_group).  Drop extra
637          * group reference used while acquiring device.
638          */
639         vfio_group_put(group);
640
641         return 0;
642 }
643 EXPORT_SYMBOL_GPL(vfio_add_group_dev);
644
645 /* Given a referenced group, check if it contains the device */
646 static bool vfio_dev_present(struct vfio_group *group, struct device *dev)
647 {
648         struct vfio_device *device;
649
650         device = vfio_group_get_device(group, dev);
651         if (!device)
652                 return false;
653
654         vfio_device_put(device);
655         return true;
656 }
657
658 /*
659  * Decrement the device reference count and wait for the device to be
660  * removed.  Open file descriptors for the device... */
661 void *vfio_del_group_dev(struct device *dev)
662 {
663         struct vfio_device *device = dev_get_drvdata(dev);
664         struct vfio_group *group = device->group;
665         struct iommu_group *iommu_group = group->iommu_group;
666         void *device_data = device->device_data;
667
668         /*
669          * The group exists so long as we have a device reference.  Get
670          * a group reference and use it to scan for the device going away.
671          */
672         vfio_group_get(group);
673
674         vfio_device_put(device);
675
676         /* TODO send a signal to encourage this to be released */
677         wait_event(vfio.release_q, !vfio_dev_present(group, dev));
678
679         vfio_group_put(group);
680
681         iommu_group_put(iommu_group);
682
683         return device_data;
684 }
685 EXPORT_SYMBOL_GPL(vfio_del_group_dev);
686
687 /**
688  * VFIO base fd, /dev/vfio/vfio
689  */
690 static long vfio_ioctl_check_extension(struct vfio_container *container,
691                                        unsigned long arg)
692 {
693         struct vfio_iommu_driver *driver = container->iommu_driver;
694         long ret = 0;
695
696         switch (arg) {
697                 /* No base extensions yet */
698         default:
699                 /*
700                  * If no driver is set, poll all registered drivers for
701                  * extensions and return the first positive result.  If
702                  * a driver is already set, further queries will be passed
703                  * only to that driver.
704                  */
705                 if (!driver) {
706                         mutex_lock(&vfio.iommu_drivers_lock);
707                         list_for_each_entry(driver, &vfio.iommu_drivers_list,
708                                             vfio_next) {
709                                 if (!try_module_get(driver->ops->owner))
710                                         continue;
711
712                                 ret = driver->ops->ioctl(NULL,
713                                                          VFIO_CHECK_EXTENSION,
714                                                          arg);
715                                 module_put(driver->ops->owner);
716                                 if (ret > 0)
717                                         break;
718                         }
719                         mutex_unlock(&vfio.iommu_drivers_lock);
720                 } else
721                         ret = driver->ops->ioctl(container->iommu_data,
722                                                  VFIO_CHECK_EXTENSION, arg);
723         }
724
725         return ret;
726 }
727
728 /* hold container->group_lock */
729 static int __vfio_container_attach_groups(struct vfio_container *container,
730                                           struct vfio_iommu_driver *driver,
731                                           void *data)
732 {
733         struct vfio_group *group;
734         int ret = -ENODEV;
735
736         list_for_each_entry(group, &container->group_list, container_next) {
737                 ret = driver->ops->attach_group(data, group->iommu_group);
738                 if (ret)
739                         goto unwind;
740         }
741
742         return ret;
743
744 unwind:
745         list_for_each_entry_continue_reverse(group, &container->group_list,
746                                              container_next) {
747                 driver->ops->detach_group(data, group->iommu_group);
748         }
749
750         return ret;
751 }
752
753 static long vfio_ioctl_set_iommu(struct vfio_container *container,
754                                  unsigned long arg)
755 {
756         struct vfio_iommu_driver *driver;
757         long ret = -ENODEV;
758
759         mutex_lock(&container->group_lock);
760
761         /*
762          * The container is designed to be an unprivileged interface while
763          * the group can be assigned to specific users.  Therefore, only by
764          * adding a group to a container does the user get the privilege of
765          * enabling the iommu, which may allocate finite resources.  There
766          * is no unset_iommu, but by removing all the groups from a container,
767          * the container is deprivileged and returns to an unset state.
768          */
769         if (list_empty(&container->group_list) || container->iommu_driver) {
770                 mutex_unlock(&container->group_lock);
771                 return -EINVAL;
772         }
773
774         mutex_lock(&vfio.iommu_drivers_lock);
775         list_for_each_entry(driver, &vfio.iommu_drivers_list, vfio_next) {
776                 void *data;
777
778                 if (!try_module_get(driver->ops->owner))
779                         continue;
780
781                 /*
782                  * The arg magic for SET_IOMMU is the same as CHECK_EXTENSION,
783                  * so test which iommu driver reported support for this
784                  * extension and call open on them.  We also pass them the
785                  * magic, allowing a single driver to support multiple
786                  * interfaces if they'd like.
787                  */
788                 if (driver->ops->ioctl(NULL, VFIO_CHECK_EXTENSION, arg) <= 0) {
789                         module_put(driver->ops->owner);
790                         continue;
791                 }
792
793                 /* module reference holds the driver we're working on */
794                 mutex_unlock(&vfio.iommu_drivers_lock);
795
796                 data = driver->ops->open(arg);
797                 if (IS_ERR(data)) {
798                         ret = PTR_ERR(data);
799                         module_put(driver->ops->owner);
800                         goto skip_drivers_unlock;
801                 }
802
803                 ret = __vfio_container_attach_groups(container, driver, data);
804                 if (!ret) {
805                         container->iommu_driver = driver;
806                         container->iommu_data = data;
807                 } else {
808                         driver->ops->release(data);
809                         module_put(driver->ops->owner);
810                 }
811
812                 goto skip_drivers_unlock;
813         }
814
815         mutex_unlock(&vfio.iommu_drivers_lock);
816 skip_drivers_unlock:
817         mutex_unlock(&container->group_lock);
818
819         return ret;
820 }
821
822 static long vfio_fops_unl_ioctl(struct file *filep,
823                                 unsigned int cmd, unsigned long arg)
824 {
825         struct vfio_container *container = filep->private_data;
826         struct vfio_iommu_driver *driver;
827         void *data;
828         long ret = -EINVAL;
829
830         if (!container)
831                 return ret;
832
833         driver = container->iommu_driver;
834         data = container->iommu_data;
835
836         switch (cmd) {
837         case VFIO_GET_API_VERSION:
838                 ret = VFIO_API_VERSION;
839                 break;
840         case VFIO_CHECK_EXTENSION:
841                 ret = vfio_ioctl_check_extension(container, arg);
842                 break;
843         case VFIO_SET_IOMMU:
844                 ret = vfio_ioctl_set_iommu(container, arg);
845                 break;
846         default:
847                 if (driver) /* passthrough all unrecognized ioctls */
848                         ret = driver->ops->ioctl(data, cmd, arg);
849         }
850
851         return ret;
852 }
853
854 #ifdef CONFIG_COMPAT
855 static long vfio_fops_compat_ioctl(struct file *filep,
856                                    unsigned int cmd, unsigned long arg)
857 {
858         arg = (unsigned long)compat_ptr(arg);
859         return vfio_fops_unl_ioctl(filep, cmd, arg);
860 }
861 #endif  /* CONFIG_COMPAT */
862
863 static int vfio_fops_open(struct inode *inode, struct file *filep)
864 {
865         struct vfio_container *container;
866
867         container = kzalloc(sizeof(*container), GFP_KERNEL);
868         if (!container)
869                 return -ENOMEM;
870
871         INIT_LIST_HEAD(&container->group_list);
872         mutex_init(&container->group_lock);
873         kref_init(&container->kref);
874
875         filep->private_data = container;
876
877         return 0;
878 }
879
880 static int vfio_fops_release(struct inode *inode, struct file *filep)
881 {
882         struct vfio_container *container = filep->private_data;
883
884         filep->private_data = NULL;
885
886         vfio_container_put(container);
887
888         return 0;
889 }
890
891 /*
892  * Once an iommu driver is set, we optionally pass read/write/mmap
893  * on to the driver, allowing management interfaces beyond ioctl.
894  */
895 static ssize_t vfio_fops_read(struct file *filep, char __user *buf,
896                               size_t count, loff_t *ppos)
897 {
898         struct vfio_container *container = filep->private_data;
899         struct vfio_iommu_driver *driver = container->iommu_driver;
900
901         if (unlikely(!driver || !driver->ops->read))
902                 return -EINVAL;
903
904         return driver->ops->read(container->iommu_data, buf, count, ppos);
905 }
906
907 static ssize_t vfio_fops_write(struct file *filep, const char __user *buf,
908                                size_t count, loff_t *ppos)
909 {
910         struct vfio_container *container = filep->private_data;
911         struct vfio_iommu_driver *driver = container->iommu_driver;
912
913         if (unlikely(!driver || !driver->ops->write))
914                 return -EINVAL;
915
916         return driver->ops->write(container->iommu_data, buf, count, ppos);
917 }
918
919 static int vfio_fops_mmap(struct file *filep, struct vm_area_struct *vma)
920 {
921         struct vfio_container *container = filep->private_data;
922         struct vfio_iommu_driver *driver = container->iommu_driver;
923
924         if (unlikely(!driver || !driver->ops->mmap))
925                 return -EINVAL;
926
927         return driver->ops->mmap(container->iommu_data, vma);
928 }
929
930 static const struct file_operations vfio_fops = {
931         .owner          = THIS_MODULE,
932         .open           = vfio_fops_open,
933         .release        = vfio_fops_release,
934         .read           = vfio_fops_read,
935         .write          = vfio_fops_write,
936         .unlocked_ioctl = vfio_fops_unl_ioctl,
937 #ifdef CONFIG_COMPAT
938         .compat_ioctl   = vfio_fops_compat_ioctl,
939 #endif
940         .mmap           = vfio_fops_mmap,
941 };
942
943 /**
944  * VFIO Group fd, /dev/vfio/$GROUP
945  */
946 static void __vfio_group_unset_container(struct vfio_group *group)
947 {
948         struct vfio_container *container = group->container;
949         struct vfio_iommu_driver *driver;
950
951         mutex_lock(&container->group_lock);
952
953         driver = container->iommu_driver;
954         if (driver)
955                 driver->ops->detach_group(container->iommu_data,
956                                           group->iommu_group);
957
958         group->container = NULL;
959         list_del(&group->container_next);
960
961         /* Detaching the last group deprivileges a container, remove iommu */
962         if (driver && list_empty(&container->group_list)) {
963                 driver->ops->release(container->iommu_data);
964                 module_put(driver->ops->owner);
965                 container->iommu_driver = NULL;
966                 container->iommu_data = NULL;
967         }
968
969         mutex_unlock(&container->group_lock);
970
971         vfio_container_put(container);
972 }
973
974 /*
975  * VFIO_GROUP_UNSET_CONTAINER should fail if there are other users or
976  * if there was no container to unset.  Since the ioctl is called on
977  * the group, we know that still exists, therefore the only valid
978  * transition here is 1->0.
979  */
980 static int vfio_group_unset_container(struct vfio_group *group)
981 {
982         int users = atomic_cmpxchg(&group->container_users, 1, 0);
983
984         if (!users)
985                 return -EINVAL;
986         if (users != 1)
987                 return -EBUSY;
988
989         __vfio_group_unset_container(group);
990
991         return 0;
992 }
993
994 /*
995  * When removing container users, anything that removes the last user
996  * implicitly removes the group from the container.  That is, if the
997  * group file descriptor is closed, as well as any device file descriptors,
998  * the group is free.
999  */
1000 static void vfio_group_try_dissolve_container(struct vfio_group *group)
1001 {
1002         if (0 == atomic_dec_if_positive(&group->container_users))
1003                 __vfio_group_unset_container(group);
1004 }
1005
1006 static int vfio_group_set_container(struct vfio_group *group, int container_fd)
1007 {
1008         struct fd f;
1009         struct vfio_container *container;
1010         struct vfio_iommu_driver *driver;
1011         int ret = 0;
1012
1013         if (atomic_read(&group->container_users))
1014                 return -EINVAL;
1015
1016         f = fdget(container_fd);
1017         if (!f.file)
1018                 return -EBADF;
1019
1020         /* Sanity check, is this really our fd? */
1021         if (f.file->f_op != &vfio_fops) {
1022                 fdput(f);
1023                 return -EINVAL;
1024         }
1025
1026         container = f.file->private_data;
1027         WARN_ON(!container); /* fget ensures we don't race vfio_release */
1028
1029         mutex_lock(&container->group_lock);
1030
1031         driver = container->iommu_driver;
1032         if (driver) {
1033                 ret = driver->ops->attach_group(container->iommu_data,
1034                                                 group->iommu_group);
1035                 if (ret)
1036                         goto unlock_out;
1037         }
1038
1039         group->container = container;
1040         list_add(&group->container_next, &container->group_list);
1041
1042         /* Get a reference on the container and mark a user within the group */
1043         vfio_container_get(container);
1044         atomic_inc(&group->container_users);
1045
1046 unlock_out:
1047         mutex_unlock(&container->group_lock);
1048         fdput(f);
1049         return ret;
1050 }
1051
1052 static bool vfio_group_viable(struct vfio_group *group)
1053 {
1054         return (iommu_group_for_each_dev(group->iommu_group,
1055                                          group, vfio_dev_viable) == 0);
1056 }
1057
1058 static const struct file_operations vfio_device_fops;
1059
1060 static int vfio_group_get_device_fd(struct vfio_group *group, char *buf)
1061 {
1062         struct vfio_device *device;
1063         struct file *filep;
1064         int ret = -ENODEV;
1065
1066         if (0 == atomic_read(&group->container_users) ||
1067             !group->container->iommu_driver || !vfio_group_viable(group))
1068                 return -EINVAL;
1069
1070         mutex_lock(&group->device_lock);
1071         list_for_each_entry(device, &group->device_list, group_next) {
1072                 if (strcmp(dev_name(device->dev), buf))
1073                         continue;
1074
1075                 ret = device->ops->open(device->device_data);
1076                 if (ret)
1077                         break;
1078                 /*
1079                  * We can't use anon_inode_getfd() because we need to modify
1080                  * the f_mode flags directly to allow more than just ioctls
1081                  */
1082                 ret = get_unused_fd();
1083                 if (ret < 0) {
1084                         device->ops->release(device->device_data);
1085                         break;
1086                 }
1087
1088                 filep = anon_inode_getfile("[vfio-device]", &vfio_device_fops,
1089                                            device, O_RDWR);
1090                 if (IS_ERR(filep)) {
1091                         put_unused_fd(ret);
1092                         ret = PTR_ERR(filep);
1093                         device->ops->release(device->device_data);
1094                         break;
1095                 }
1096
1097                 /*
1098                  * TODO: add an anon_inode interface to do this.
1099                  * Appears to be missing by lack of need rather than
1100                  * explicitly prevented.  Now there's need.
1101                  */
1102                 filep->f_mode |= (FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE);
1103
1104                 vfio_device_get(device);
1105                 atomic_inc(&group->container_users);
1106
1107                 fd_install(ret, filep);
1108                 break;
1109         }
1110         mutex_unlock(&group->device_lock);
1111
1112         return ret;
1113 }
1114
1115 static long vfio_group_fops_unl_ioctl(struct file *filep,
1116                                       unsigned int cmd, unsigned long arg)
1117 {
1118         struct vfio_group *group = filep->private_data;
1119         long ret = -ENOTTY;
1120
1121         switch (cmd) {
1122         case VFIO_GROUP_GET_STATUS:
1123         {
1124                 struct vfio_group_status status;
1125                 unsigned long minsz;
1126
1127                 minsz = offsetofend(struct vfio_group_status, flags);
1128
1129                 if (copy_from_user(&status, (void __user *)arg, minsz))
1130                         return -EFAULT;
1131
1132                 if (status.argsz < minsz)
1133                         return -EINVAL;
1134
1135                 status.flags = 0;
1136
1137                 if (vfio_group_viable(group))
1138                         status.flags |= VFIO_GROUP_FLAGS_VIABLE;
1139
1140                 if (group->container)
1141                         status.flags |= VFIO_GROUP_FLAGS_CONTAINER_SET;
1142
1143                 if (copy_to_user((void __user *)arg, &status, minsz))
1144                         return -EFAULT;
1145
1146                 ret = 0;
1147                 break;
1148         }
1149         case VFIO_GROUP_SET_CONTAINER:
1150         {
1151                 int fd;
1152
1153                 if (get_user(fd, (int __user *)arg))
1154                         return -EFAULT;
1155
1156                 if (fd < 0)
1157                         return -EINVAL;
1158
1159                 ret = vfio_group_set_container(group, fd);
1160                 break;
1161         }
1162         case VFIO_GROUP_UNSET_CONTAINER:
1163                 ret = vfio_group_unset_container(group);
1164                 break;
1165         case VFIO_GROUP_GET_DEVICE_FD:
1166         {
1167                 char *buf;
1168
1169                 buf = strndup_user((const char __user *)arg, PAGE_SIZE);
1170                 if (IS_ERR(buf))
1171                         return PTR_ERR(buf);
1172
1173                 ret = vfio_group_get_device_fd(group, buf);
1174                 kfree(buf);
1175                 break;
1176         }
1177         }
1178
1179         return ret;
1180 }
1181
1182 #ifdef CONFIG_COMPAT
1183 static long vfio_group_fops_compat_ioctl(struct file *filep,
1184                                          unsigned int cmd, unsigned long arg)
1185 {
1186         arg = (unsigned long)compat_ptr(arg);
1187         return vfio_group_fops_unl_ioctl(filep, cmd, arg);
1188 }
1189 #endif  /* CONFIG_COMPAT */
1190
1191 static int vfio_group_fops_open(struct inode *inode, struct file *filep)
1192 {
1193         struct vfio_group *group;
1194
1195         group = vfio_group_get_from_minor(iminor(inode));
1196         if (!group)
1197                 return -ENODEV;
1198
1199         if (group->container) {
1200                 vfio_group_put(group);
1201                 return -EBUSY;
1202         }
1203
1204         filep->private_data = group;
1205
1206         return 0;
1207 }
1208
1209 static int vfio_group_fops_release(struct inode *inode, struct file *filep)
1210 {
1211         struct vfio_group *group = filep->private_data;
1212
1213         filep->private_data = NULL;
1214
1215         vfio_group_try_dissolve_container(group);
1216
1217         vfio_group_put(group);
1218
1219         return 0;
1220 }
1221
1222 static const struct file_operations vfio_group_fops = {
1223         .owner          = THIS_MODULE,
1224         .unlocked_ioctl = vfio_group_fops_unl_ioctl,
1225 #ifdef CONFIG_COMPAT
1226         .compat_ioctl   = vfio_group_fops_compat_ioctl,
1227 #endif
1228         .open           = vfio_group_fops_open,
1229         .release        = vfio_group_fops_release,
1230 };
1231
1232 /**
1233  * VFIO Device fd
1234  */
1235 static int vfio_device_fops_release(struct inode *inode, struct file *filep)
1236 {
1237         struct vfio_device *device = filep->private_data;
1238
1239         device->ops->release(device->device_data);
1240
1241         vfio_group_try_dissolve_container(device->group);
1242
1243         vfio_device_put(device);
1244
1245         return 0;
1246 }
1247
1248 static long vfio_device_fops_unl_ioctl(struct file *filep,
1249                                        unsigned int cmd, unsigned long arg)
1250 {
1251         struct vfio_device *device = filep->private_data;
1252
1253         if (unlikely(!device->ops->ioctl))
1254                 return -EINVAL;
1255
1256         return device->ops->ioctl(device->device_data, cmd, arg);
1257 }
1258
1259 static ssize_t vfio_device_fops_read(struct file *filep, char __user *buf,
1260                                      size_t count, loff_t *ppos)
1261 {
1262         struct vfio_device *device = filep->private_data;
1263
1264         if (unlikely(!device->ops->read))
1265                 return -EINVAL;
1266
1267         return device->ops->read(device->device_data, buf, count, ppos);
1268 }
1269
1270 static ssize_t vfio_device_fops_write(struct file *filep,
1271                                       const char __user *buf,
1272                                       size_t count, loff_t *ppos)
1273 {
1274         struct vfio_device *device = filep->private_data;
1275
1276         if (unlikely(!device->ops->write))
1277                 return -EINVAL;
1278
1279         return device->ops->write(device->device_data, buf, count, ppos);
1280 }
1281
1282 static int vfio_device_fops_mmap(struct file *filep, struct vm_area_struct *vma)
1283 {
1284         struct vfio_device *device = filep->private_data;
1285
1286         if (unlikely(!device->ops->mmap))
1287                 return -EINVAL;
1288
1289         return device->ops->mmap(device->device_data, vma);
1290 }
1291
1292 #ifdef CONFIG_COMPAT
1293 static long vfio_device_fops_compat_ioctl(struct file *filep,
1294                                           unsigned int cmd, unsigned long arg)
1295 {
1296         arg = (unsigned long)compat_ptr(arg);
1297         return vfio_device_fops_unl_ioctl(filep, cmd, arg);
1298 }
1299 #endif  /* CONFIG_COMPAT */
1300
1301 static const struct file_operations vfio_device_fops = {
1302         .owner          = THIS_MODULE,
1303         .release        = vfio_device_fops_release,
1304         .read           = vfio_device_fops_read,
1305         .write          = vfio_device_fops_write,
1306         .unlocked_ioctl = vfio_device_fops_unl_ioctl,
1307 #ifdef CONFIG_COMPAT
1308         .compat_ioctl   = vfio_device_fops_compat_ioctl,
1309 #endif
1310         .mmap           = vfio_device_fops_mmap,
1311 };
1312
1313 /**
1314  * Module/class support
1315  */
1316 static char *vfio_devnode(struct device *dev, umode_t *mode)
1317 {
1318         return kasprintf(GFP_KERNEL, "vfio/%s", dev_name(dev));
1319 }
1320
1321 static int __init vfio_init(void)
1322 {
1323         int ret;
1324
1325         idr_init(&vfio.group_idr);
1326         mutex_init(&vfio.group_lock);
1327         mutex_init(&vfio.iommu_drivers_lock);
1328         INIT_LIST_HEAD(&vfio.group_list);
1329         INIT_LIST_HEAD(&vfio.iommu_drivers_list);
1330         init_waitqueue_head(&vfio.release_q);
1331
1332         vfio.class = class_create(THIS_MODULE, "vfio");
1333         if (IS_ERR(vfio.class)) {
1334                 ret = PTR_ERR(vfio.class);
1335                 goto err_class;
1336         }
1337
1338         vfio.class->devnode = vfio_devnode;
1339
1340         ret = alloc_chrdev_region(&vfio.devt, 0, MINORMASK, "vfio");
1341         if (ret)
1342                 goto err_base_chrdev;
1343
1344         cdev_init(&vfio.cdev, &vfio_fops);
1345         ret = cdev_add(&vfio.cdev, vfio.devt, 1);
1346         if (ret)
1347                 goto err_base_cdev;
1348
1349         vfio.dev = device_create(vfio.class, NULL, vfio.devt, NULL, "vfio");
1350         if (IS_ERR(vfio.dev)) {
1351                 ret = PTR_ERR(vfio.dev);
1352                 goto err_base_dev;
1353         }
1354
1355         /* /dev/vfio/$GROUP */
1356         cdev_init(&vfio.group_cdev, &vfio_group_fops);
1357         ret = cdev_add(&vfio.group_cdev,
1358                        MKDEV(MAJOR(vfio.devt), 1), MINORMASK - 1);
1359         if (ret)
1360                 goto err_groups_cdev;
1361
1362         pr_info(DRIVER_DESC " version: " DRIVER_VERSION "\n");
1363
1364         /*
1365          * Attempt to load known iommu-drivers.  This gives us a working
1366          * environment without the user needing to explicitly load iommu
1367          * drivers.
1368          */
1369         request_module_nowait("vfio_iommu_type1");
1370
1371         return 0;
1372
1373 err_groups_cdev:
1374         device_destroy(vfio.class, vfio.devt);
1375 err_base_dev:
1376         cdev_del(&vfio.cdev);
1377 err_base_cdev:
1378         unregister_chrdev_region(vfio.devt, MINORMASK);
1379 err_base_chrdev:
1380         class_destroy(vfio.class);
1381         vfio.class = NULL;
1382 err_class:
1383         return ret;
1384 }
1385
1386 static void __exit vfio_cleanup(void)
1387 {
1388         WARN_ON(!list_empty(&vfio.group_list));
1389
1390         idr_destroy(&vfio.group_idr);
1391         cdev_del(&vfio.group_cdev);
1392         device_destroy(vfio.class, vfio.devt);
1393         cdev_del(&vfio.cdev);
1394         unregister_chrdev_region(vfio.devt, MINORMASK);
1395         class_destroy(vfio.class);
1396         vfio.class = NULL;
1397 }
1398
1399 module_init(vfio_init);
1400 module_exit(vfio_cleanup);
1401
1402 MODULE_VERSION(DRIVER_VERSION);
1403 MODULE_LICENSE("GPL v2");
1404 MODULE_AUTHOR(DRIVER_AUTHOR);
1405 MODULE_DESCRIPTION(DRIVER_DESC);