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