GNU Linux-libre 4.9.328-gnu1
[releases.git] / drivers / vfio / pci / vfio_pci.c
1 /*
2  * Copyright (C) 2012 Red Hat, Inc.  All rights reserved.
3  *     Author: Alex Williamson <alex.williamson@redhat.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Derived from original vfio:
10  * Copyright 2010 Cisco Systems, Inc.  All rights reserved.
11  * Author: Tom Lyon, pugs@cisco.com
12  */
13
14 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15
16 #include <linux/device.h>
17 #include <linux/eventfd.h>
18 #include <linux/file.h>
19 #include <linux/interrupt.h>
20 #include <linux/iommu.h>
21 #include <linux/module.h>
22 #include <linux/mutex.h>
23 #include <linux/notifier.h>
24 #include <linux/pci.h>
25 #include <linux/pm_runtime.h>
26 #include <linux/slab.h>
27 #include <linux/types.h>
28 #include <linux/uaccess.h>
29 #include <linux/vfio.h>
30 #include <linux/vgaarb.h>
31 #include <linux/nospec.h>
32 #include <linux/mm.h>
33
34 #include "vfio_pci_private.h"
35
36 #define DRIVER_VERSION  "0.2"
37 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
38 #define DRIVER_DESC     "VFIO PCI - User Level meta-driver"
39
40 static char ids[1024] __initdata;
41 module_param_string(ids, ids, sizeof(ids), 0);
42 MODULE_PARM_DESC(ids, "Initial PCI IDs to add to the vfio driver, format is \"vendor:device[:subvendor[:subdevice[:class[:class_mask]]]]\" and multiple comma separated entries can be specified");
43
44 static bool nointxmask;
45 module_param_named(nointxmask, nointxmask, bool, S_IRUGO | S_IWUSR);
46 MODULE_PARM_DESC(nointxmask,
47                   "Disable support for PCI 2.3 style INTx masking.  If this resolves problems for specific devices, report lspci -vvvxxx to linux-pci@vger.kernel.org so the device can be fixed automatically via the broken_intx_masking flag.");
48
49 #ifdef CONFIG_VFIO_PCI_VGA
50 static bool disable_vga;
51 module_param(disable_vga, bool, S_IRUGO);
52 MODULE_PARM_DESC(disable_vga, "Disable VGA resource access through vfio-pci");
53 #endif
54
55 static bool disable_idle_d3;
56 module_param(disable_idle_d3, bool, S_IRUGO | S_IWUSR);
57 MODULE_PARM_DESC(disable_idle_d3,
58                  "Disable using the PCI D3 low power state for idle, unused devices");
59
60 static DEFINE_MUTEX(driver_lock);
61
62 static inline bool vfio_vga_disabled(void)
63 {
64 #ifdef CONFIG_VFIO_PCI_VGA
65         return disable_vga;
66 #else
67         return true;
68 #endif
69 }
70
71 /*
72  * Our VGA arbiter participation is limited since we don't know anything
73  * about the device itself.  However, if the device is the only VGA device
74  * downstream of a bridge and VFIO VGA support is disabled, then we can
75  * safely return legacy VGA IO and memory as not decoded since the user
76  * has no way to get to it and routing can be disabled externally at the
77  * bridge.
78  */
79 static unsigned int vfio_pci_set_vga_decode(void *opaque, bool single_vga)
80 {
81         struct vfio_pci_device *vdev = opaque;
82         struct pci_dev *tmp = NULL, *pdev = vdev->pdev;
83         unsigned char max_busnr;
84         unsigned int decodes;
85
86         if (single_vga || !vfio_vga_disabled() || pci_is_root_bus(pdev->bus))
87                 return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
88                        VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
89
90         max_busnr = pci_bus_max_busnr(pdev->bus);
91         decodes = VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
92
93         while ((tmp = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, tmp)) != NULL) {
94                 if (tmp == pdev ||
95                     pci_domain_nr(tmp->bus) != pci_domain_nr(pdev->bus) ||
96                     pci_is_root_bus(tmp->bus))
97                         continue;
98
99                 if (tmp->bus->number >= pdev->bus->number &&
100                     tmp->bus->number <= max_busnr) {
101                         pci_dev_put(tmp);
102                         decodes |= VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
103                         break;
104                 }
105         }
106
107         return decodes;
108 }
109
110 static inline bool vfio_pci_is_vga(struct pci_dev *pdev)
111 {
112         return (pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA;
113 }
114
115 static void vfio_pci_probe_mmaps(struct vfio_pci_device *vdev)
116 {
117         struct resource *res;
118         int bar;
119         struct vfio_pci_dummy_resource *dummy_res;
120
121         for (bar = PCI_STD_RESOURCES; bar <= PCI_STD_RESOURCE_END; bar++) {
122                 res = vdev->pdev->resource + bar;
123
124                 if (!IS_ENABLED(CONFIG_VFIO_PCI_MMAP))
125                         goto no_mmap;
126
127                 if (!(res->flags & IORESOURCE_MEM))
128                         goto no_mmap;
129
130                 /*
131                  * The PCI core shouldn't set up a resource with a
132                  * type but zero size. But there may be bugs that
133                  * cause us to do that.
134                  */
135                 if (!resource_size(res))
136                         goto no_mmap;
137
138                 if (resource_size(res) >= PAGE_SIZE) {
139                         vdev->bar_mmap_supported[bar] = true;
140                         continue;
141                 }
142
143                 if (!(res->start & ~PAGE_MASK)) {
144                         /*
145                          * Add a dummy resource to reserve the remainder
146                          * of the exclusive page in case that hot-add
147                          * device's bar is assigned into it.
148                          */
149                         dummy_res = kzalloc(sizeof(*dummy_res), GFP_KERNEL);
150                         if (dummy_res == NULL)
151                                 goto no_mmap;
152
153                         dummy_res->resource.name = "vfio sub-page reserved";
154                         dummy_res->resource.start = res->end + 1;
155                         dummy_res->resource.end = res->start + PAGE_SIZE - 1;
156                         dummy_res->resource.flags = res->flags;
157                         if (request_resource(res->parent,
158                                                 &dummy_res->resource)) {
159                                 kfree(dummy_res);
160                                 goto no_mmap;
161                         }
162                         dummy_res->index = bar;
163                         list_add(&dummy_res->res_next,
164                                         &vdev->dummy_resources_list);
165                         vdev->bar_mmap_supported[bar] = true;
166                         continue;
167                 }
168                 /*
169                  * Here we don't handle the case when the BAR is not page
170                  * aligned because we can't expect the BAR will be
171                  * assigned into the same location in a page in guest
172                  * when we passthrough the BAR. And it's hard to access
173                  * this BAR in userspace because we have no way to get
174                  * the BAR's location in a page.
175                  */
176 no_mmap:
177                 vdev->bar_mmap_supported[bar] = false;
178         }
179 }
180
181 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev);
182 static void vfio_pci_disable(struct vfio_pci_device *vdev);
183 static int vfio_pci_try_zap_and_vma_lock_cb(struct pci_dev *pdev, void *data);
184
185 /*
186  * INTx masking requires the ability to disable INTx signaling via PCI_COMMAND
187  * _and_ the ability detect when the device is asserting INTx via PCI_STATUS.
188  * If a device implements the former but not the latter we would typically
189  * expect broken_intx_masking be set and require an exclusive interrupt.
190  * However since we do have control of the device's ability to assert INTx,
191  * we can instead pretend that the device does not implement INTx, virtualizing
192  * the pin register to report zero and maintaining DisINTx set on the host.
193  */
194 static bool vfio_pci_nointx(struct pci_dev *pdev)
195 {
196         switch (pdev->vendor) {
197         case PCI_VENDOR_ID_INTEL:
198                 switch (pdev->device) {
199                 /* All i40e (XL710/X710) 10/20/40GbE NICs */
200                 case 0x1572:
201                 case 0x1574:
202                 case 0x1580 ... 0x1581:
203                 case 0x1583 ... 0x1589:
204                 case 0x37d0 ... 0x37d2:
205                         return true;
206                 default:
207                         return false;
208                 }
209         }
210
211         return false;
212 }
213
214 static int vfio_pci_enable(struct vfio_pci_device *vdev)
215 {
216         struct pci_dev *pdev = vdev->pdev;
217         int ret;
218         u16 cmd;
219         u8 msix_pos;
220
221         pci_set_power_state(pdev, PCI_D0);
222
223         /* Don't allow our initial saved state to include busmaster */
224         pci_clear_master(pdev);
225
226         ret = pci_enable_device(pdev);
227         if (ret)
228                 return ret;
229
230         vdev->reset_works = (pci_reset_function(pdev) == 0);
231         pci_save_state(pdev);
232         vdev->pci_saved_state = pci_store_saved_state(pdev);
233         if (!vdev->pci_saved_state)
234                 pr_debug("%s: Couldn't store %s saved state\n",
235                          __func__, dev_name(&pdev->dev));
236
237         if (likely(!nointxmask)) {
238                 if (vfio_pci_nointx(pdev)) {
239                         dev_info(&pdev->dev, "Masking broken INTx support\n");
240                         vdev->nointx = true;
241                         pci_intx(pdev, 0);
242                 } else
243                         vdev->pci_2_3 = pci_intx_mask_supported(pdev);
244         }
245
246         pci_read_config_word(pdev, PCI_COMMAND, &cmd);
247         if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
248                 cmd &= ~PCI_COMMAND_INTX_DISABLE;
249                 pci_write_config_word(pdev, PCI_COMMAND, cmd);
250         }
251
252         ret = vfio_config_init(vdev);
253         if (ret) {
254                 kfree(vdev->pci_saved_state);
255                 vdev->pci_saved_state = NULL;
256                 pci_disable_device(pdev);
257                 return ret;
258         }
259
260         msix_pos = pdev->msix_cap;
261         if (msix_pos) {
262                 u16 flags;
263                 u32 table;
264
265                 pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
266                 pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
267
268                 vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
269                 vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
270                 vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
271         } else
272                 vdev->msix_bar = 0xFF;
273
274         if (!vfio_vga_disabled() && vfio_pci_is_vga(pdev))
275                 vdev->has_vga = true;
276
277
278         if (vfio_pci_is_vga(pdev) &&
279             pdev->vendor == PCI_VENDOR_ID_INTEL &&
280             IS_ENABLED(CONFIG_VFIO_PCI_IGD)) {
281                 ret = vfio_pci_igd_init(vdev);
282                 if (ret) {
283                         dev_warn(&vdev->pdev->dev,
284                                  "Failed to setup Intel IGD regions\n");
285                         vfio_pci_disable(vdev);
286                         return ret;
287                 }
288         }
289
290         vfio_pci_probe_mmaps(vdev);
291
292         return 0;
293 }
294
295 static void vfio_pci_disable(struct vfio_pci_device *vdev)
296 {
297         struct pci_dev *pdev = vdev->pdev;
298         struct vfio_pci_dummy_resource *dummy_res, *tmp;
299         int i, bar;
300
301         /* Stop the device from further DMA */
302         pci_clear_master(pdev);
303
304         vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
305                                 VFIO_IRQ_SET_ACTION_TRIGGER,
306                                 vdev->irq_type, 0, 0, NULL);
307
308         vdev->virq_disabled = false;
309
310         for (i = 0; i < vdev->num_regions; i++)
311                 vdev->region[i].ops->release(vdev, &vdev->region[i]);
312
313         vdev->num_regions = 0;
314         kfree(vdev->region);
315         vdev->region = NULL; /* don't krealloc a freed pointer */
316
317         vfio_config_free(vdev);
318
319         for (bar = PCI_STD_RESOURCES; bar <= PCI_STD_RESOURCE_END; bar++) {
320                 if (!vdev->barmap[bar])
321                         continue;
322                 pci_iounmap(pdev, vdev->barmap[bar]);
323                 pci_release_selected_regions(pdev, 1 << bar);
324                 vdev->barmap[bar] = NULL;
325         }
326
327         list_for_each_entry_safe(dummy_res, tmp,
328                                  &vdev->dummy_resources_list, res_next) {
329                 list_del(&dummy_res->res_next);
330                 release_resource(&dummy_res->resource);
331                 kfree(dummy_res);
332         }
333
334         vdev->needs_reset = true;
335
336         /*
337          * If we have saved state, restore it.  If we can reset the device,
338          * even better.  Resetting with current state seems better than
339          * nothing, but saving and restoring current state without reset
340          * is just busy work.
341          */
342         if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
343                 pr_info("%s: Couldn't reload %s saved state\n",
344                         __func__, dev_name(&pdev->dev));
345
346                 if (!vdev->reset_works)
347                         goto out;
348
349                 pci_save_state(pdev);
350         }
351
352         /*
353          * Disable INTx and MSI, presumably to avoid spurious interrupts
354          * during reset.  Stolen from pci_reset_function()
355          */
356         pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
357
358         /*
359          * Try to get the locks ourselves to prevent a deadlock. The
360          * success of this is dependent on being able to lock the device,
361          * which is not always possible.
362          * We can not use the "try" reset interface here, which will
363          * overwrite the previously restored configuration information.
364          */
365         if (vdev->reset_works && pci_cfg_access_trylock(pdev)) {
366                 if (device_trylock(&pdev->dev)) {
367                         if (!__pci_reset_function_locked(pdev))
368                                 vdev->needs_reset = false;
369                         device_unlock(&pdev->dev);
370                 }
371                 pci_cfg_access_unlock(pdev);
372         }
373
374         pci_restore_state(pdev);
375 out:
376         pci_disable_device(pdev);
377
378         vfio_pci_try_bus_reset(vdev);
379
380         if (!disable_idle_d3)
381                 pci_set_power_state(pdev, PCI_D3hot);
382 }
383
384 static void vfio_pci_release(void *device_data)
385 {
386         struct vfio_pci_device *vdev = device_data;
387
388         mutex_lock(&driver_lock);
389
390         if (!(--vdev->refcnt)) {
391                 vfio_spapr_pci_eeh_release(vdev->pdev);
392                 vfio_pci_disable(vdev);
393                 mutex_lock(&vdev->igate);
394                 if (vdev->err_trigger) {
395                         eventfd_ctx_put(vdev->err_trigger);
396                         vdev->err_trigger = NULL;
397                 }
398                 mutex_unlock(&vdev->igate);
399
400                 mutex_lock(&vdev->igate);
401                 if (vdev->req_trigger) {
402                         eventfd_ctx_put(vdev->req_trigger);
403                         vdev->req_trigger = NULL;
404                 }
405                 mutex_unlock(&vdev->igate);
406         }
407
408         mutex_unlock(&driver_lock);
409
410         module_put(THIS_MODULE);
411 }
412
413 static int vfio_pci_open(void *device_data)
414 {
415         struct vfio_pci_device *vdev = device_data;
416         int ret = 0;
417
418         if (!try_module_get(THIS_MODULE))
419                 return -ENODEV;
420
421         mutex_lock(&driver_lock);
422
423         if (!vdev->refcnt) {
424                 ret = vfio_pci_enable(vdev);
425                 if (ret)
426                         goto error;
427
428                 vfio_spapr_pci_eeh_open(vdev->pdev);
429         }
430         vdev->refcnt++;
431 error:
432         mutex_unlock(&driver_lock);
433         if (ret)
434                 module_put(THIS_MODULE);
435         return ret;
436 }
437
438 static int vfio_pci_get_irq_count(struct vfio_pci_device *vdev, int irq_type)
439 {
440         if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
441                 u8 pin;
442
443                 if (!IS_ENABLED(CONFIG_VFIO_PCI_INTX) ||
444                     vdev->nointx || vdev->pdev->is_virtfn)
445                         return 0;
446
447                 pci_read_config_byte(vdev->pdev, PCI_INTERRUPT_PIN, &pin);
448
449                 return pin ? 1 : 0;
450         } else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
451                 u8 pos;
452                 u16 flags;
453
454                 pos = vdev->pdev->msi_cap;
455                 if (pos) {
456                         pci_read_config_word(vdev->pdev,
457                                              pos + PCI_MSI_FLAGS, &flags);
458                         return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
459                 }
460         } else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
461                 u8 pos;
462                 u16 flags;
463
464                 pos = vdev->pdev->msix_cap;
465                 if (pos) {
466                         pci_read_config_word(vdev->pdev,
467                                              pos + PCI_MSIX_FLAGS, &flags);
468
469                         return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
470                 }
471         } else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX) {
472                 if (pci_is_pcie(vdev->pdev))
473                         return 1;
474         } else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
475                 return 1;
476         }
477
478         return 0;
479 }
480
481 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
482 {
483         (*(int *)data)++;
484         return 0;
485 }
486
487 struct vfio_pci_fill_info {
488         int max;
489         int cur;
490         struct vfio_pci_dependent_device *devices;
491 };
492
493 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
494 {
495         struct vfio_pci_fill_info *fill = data;
496         struct iommu_group *iommu_group;
497
498         if (fill->cur == fill->max)
499                 return -EAGAIN; /* Something changed, try again */
500
501         iommu_group = iommu_group_get(&pdev->dev);
502         if (!iommu_group)
503                 return -EPERM; /* Cannot reset non-isolated devices */
504
505         fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
506         fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
507         fill->devices[fill->cur].bus = pdev->bus->number;
508         fill->devices[fill->cur].devfn = pdev->devfn;
509         fill->cur++;
510         iommu_group_put(iommu_group);
511         return 0;
512 }
513
514 struct vfio_pci_group_entry {
515         struct vfio_group *group;
516         int id;
517 };
518
519 struct vfio_pci_group_info {
520         int count;
521         struct vfio_pci_group_entry *groups;
522 };
523
524 static int vfio_pci_validate_devs(struct pci_dev *pdev, void *data)
525 {
526         struct vfio_pci_group_info *info = data;
527         struct iommu_group *group;
528         int id, i;
529
530         group = iommu_group_get(&pdev->dev);
531         if (!group)
532                 return -EPERM;
533
534         id = iommu_group_id(group);
535
536         for (i = 0; i < info->count; i++)
537                 if (info->groups[i].id == id)
538                         break;
539
540         iommu_group_put(group);
541
542         return (i == info->count) ? -EINVAL : 0;
543 }
544
545 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
546 {
547         for (; pdev; pdev = pdev->bus->self)
548                 if (pdev->bus == slot->bus)
549                         return (pdev->slot == slot);
550         return false;
551 }
552
553 struct vfio_pci_walk_info {
554         int (*fn)(struct pci_dev *, void *data);
555         void *data;
556         struct pci_dev *pdev;
557         bool slot;
558         int ret;
559 };
560
561 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
562 {
563         struct vfio_pci_walk_info *walk = data;
564
565         if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
566                 walk->ret = walk->fn(pdev, walk->data);
567
568         return walk->ret;
569 }
570
571 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
572                                          int (*fn)(struct pci_dev *,
573                                                    void *data), void *data,
574                                          bool slot)
575 {
576         struct vfio_pci_walk_info walk = {
577                 .fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
578         };
579
580         pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
581
582         return walk.ret;
583 }
584
585 static int msix_sparse_mmap_cap(struct vfio_pci_device *vdev,
586                                 struct vfio_info_cap *caps)
587 {
588         struct vfio_info_cap_header *header;
589         struct vfio_region_info_cap_sparse_mmap *sparse;
590         size_t end, size;
591         int nr_areas = 2, i = 0;
592
593         end = pci_resource_len(vdev->pdev, vdev->msix_bar);
594
595         /* If MSI-X table is aligned to the start or end, only one area */
596         if (((vdev->msix_offset & PAGE_MASK) == 0) ||
597             (PAGE_ALIGN(vdev->msix_offset + vdev->msix_size) >= end))
598                 nr_areas = 1;
599
600         size = sizeof(*sparse) + (nr_areas * sizeof(*sparse->areas));
601
602         header = vfio_info_cap_add(caps, size,
603                                    VFIO_REGION_INFO_CAP_SPARSE_MMAP, 1);
604         if (IS_ERR(header))
605                 return PTR_ERR(header);
606
607         sparse = container_of(header,
608                               struct vfio_region_info_cap_sparse_mmap, header);
609         sparse->nr_areas = nr_areas;
610
611         if (vdev->msix_offset & PAGE_MASK) {
612                 sparse->areas[i].offset = 0;
613                 sparse->areas[i].size = vdev->msix_offset & PAGE_MASK;
614                 i++;
615         }
616
617         if (PAGE_ALIGN(vdev->msix_offset + vdev->msix_size) < end) {
618                 sparse->areas[i].offset = PAGE_ALIGN(vdev->msix_offset +
619                                                      vdev->msix_size);
620                 sparse->areas[i].size = end - sparse->areas[i].offset;
621                 i++;
622         }
623
624         return 0;
625 }
626
627 static int region_type_cap(struct vfio_pci_device *vdev,
628                            struct vfio_info_cap *caps,
629                            unsigned int type, unsigned int subtype)
630 {
631         struct vfio_info_cap_header *header;
632         struct vfio_region_info_cap_type *cap;
633
634         header = vfio_info_cap_add(caps, sizeof(*cap),
635                                    VFIO_REGION_INFO_CAP_TYPE, 1);
636         if (IS_ERR(header))
637                 return PTR_ERR(header);
638
639         cap = container_of(header, struct vfio_region_info_cap_type, header);
640         cap->type = type;
641         cap->subtype = subtype;
642
643         return 0;
644 }
645
646 int vfio_pci_register_dev_region(struct vfio_pci_device *vdev,
647                                  unsigned int type, unsigned int subtype,
648                                  const struct vfio_pci_regops *ops,
649                                  size_t size, u32 flags, void *data)
650 {
651         struct vfio_pci_region *region;
652
653         region = krealloc(vdev->region,
654                           (vdev->num_regions + 1) * sizeof(*region),
655                           GFP_KERNEL);
656         if (!region)
657                 return -ENOMEM;
658
659         vdev->region = region;
660         vdev->region[vdev->num_regions].type = type;
661         vdev->region[vdev->num_regions].subtype = subtype;
662         vdev->region[vdev->num_regions].ops = ops;
663         vdev->region[vdev->num_regions].size = size;
664         vdev->region[vdev->num_regions].flags = flags;
665         vdev->region[vdev->num_regions].data = data;
666
667         vdev->num_regions++;
668
669         return 0;
670 }
671
672 struct vfio_devices {
673         struct vfio_device **devices;
674         int cur_index;
675         int max_index;
676 };
677
678 static long vfio_pci_ioctl(void *device_data,
679                            unsigned int cmd, unsigned long arg)
680 {
681         struct vfio_pci_device *vdev = device_data;
682         unsigned long minsz;
683
684         if (cmd == VFIO_DEVICE_GET_INFO) {
685                 struct vfio_device_info info;
686
687                 minsz = offsetofend(struct vfio_device_info, num_irqs);
688
689                 if (copy_from_user(&info, (void __user *)arg, minsz))
690                         return -EFAULT;
691
692                 if (info.argsz < minsz)
693                         return -EINVAL;
694
695                 info.flags = VFIO_DEVICE_FLAGS_PCI;
696
697                 if (vdev->reset_works)
698                         info.flags |= VFIO_DEVICE_FLAGS_RESET;
699
700                 info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions;
701                 info.num_irqs = VFIO_PCI_NUM_IRQS;
702
703                 return copy_to_user((void __user *)arg, &info, minsz) ?
704                         -EFAULT : 0;
705
706         } else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
707                 struct pci_dev *pdev = vdev->pdev;
708                 struct vfio_region_info info;
709                 struct vfio_info_cap caps = { .buf = NULL, .size = 0 };
710                 int i, ret;
711
712                 minsz = offsetofend(struct vfio_region_info, offset);
713
714                 if (copy_from_user(&info, (void __user *)arg, minsz))
715                         return -EFAULT;
716
717                 if (info.argsz < minsz)
718                         return -EINVAL;
719
720                 switch (info.index) {
721                 case VFIO_PCI_CONFIG_REGION_INDEX:
722                         info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
723                         info.size = pdev->cfg_size;
724                         info.flags = VFIO_REGION_INFO_FLAG_READ |
725                                      VFIO_REGION_INFO_FLAG_WRITE;
726                         break;
727                 case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
728                         info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
729                         info.size = pci_resource_len(pdev, info.index);
730                         if (!info.size) {
731                                 info.flags = 0;
732                                 break;
733                         }
734
735                         info.flags = VFIO_REGION_INFO_FLAG_READ |
736                                      VFIO_REGION_INFO_FLAG_WRITE;
737                         if (vdev->bar_mmap_supported[info.index]) {
738                                 info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
739                                 if (info.index == vdev->msix_bar) {
740                                         ret = msix_sparse_mmap_cap(vdev, &caps);
741                                         if (ret)
742                                                 return ret;
743                                 }
744                         }
745
746                         break;
747                 case VFIO_PCI_ROM_REGION_INDEX:
748                 {
749                         void __iomem *io;
750                         size_t size;
751                         u16 cmd;
752
753                         info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
754                         info.flags = 0;
755
756                         /* Report the BAR size, not the ROM size */
757                         info.size = pci_resource_len(pdev, info.index);
758                         if (!info.size) {
759                                 /* Shadow ROMs appear as PCI option ROMs */
760                                 if (pdev->resource[PCI_ROM_RESOURCE].flags &
761                                                         IORESOURCE_ROM_SHADOW)
762                                         info.size = 0x20000;
763                                 else
764                                         break;
765                         }
766
767                         /*
768                          * Is it really there?  Enable memory decode for
769                          * implicit access in pci_map_rom().
770                          */
771                         cmd = vfio_pci_memory_lock_and_enable(vdev);
772                         io = pci_map_rom(pdev, &size);
773                         if (io) {
774                                 info.flags = VFIO_REGION_INFO_FLAG_READ;
775                                 pci_unmap_rom(pdev, io);
776                         } else {
777                                 info.size = 0;
778                         }
779                         vfio_pci_memory_unlock_and_restore(vdev, cmd);
780
781                         break;
782                 }
783                 case VFIO_PCI_VGA_REGION_INDEX:
784                         if (!vdev->has_vga)
785                                 return -EINVAL;
786
787                         info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
788                         info.size = 0xc0000;
789                         info.flags = VFIO_REGION_INFO_FLAG_READ |
790                                      VFIO_REGION_INFO_FLAG_WRITE;
791
792                         break;
793                 default:
794                         if (info.index >=
795                             VFIO_PCI_NUM_REGIONS + vdev->num_regions)
796                                 return -EINVAL;
797                         info.index = array_index_nospec(info.index,
798                                                         VFIO_PCI_NUM_REGIONS +
799                                                         vdev->num_regions);
800
801                         i = info.index - VFIO_PCI_NUM_REGIONS;
802
803                         info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
804                         info.size = vdev->region[i].size;
805                         info.flags = vdev->region[i].flags;
806
807                         ret = region_type_cap(vdev, &caps,
808                                               vdev->region[i].type,
809                                               vdev->region[i].subtype);
810                         if (ret)
811                                 return ret;
812                 }
813
814                 if (caps.size) {
815                         info.flags |= VFIO_REGION_INFO_FLAG_CAPS;
816                         if (info.argsz < sizeof(info) + caps.size) {
817                                 info.argsz = sizeof(info) + caps.size;
818                                 info.cap_offset = 0;
819                         } else {
820                                 vfio_info_cap_shift(&caps, sizeof(info));
821                                 if (copy_to_user((void __user *)arg +
822                                                   sizeof(info), caps.buf,
823                                                   caps.size)) {
824                                         kfree(caps.buf);
825                                         return -EFAULT;
826                                 }
827                                 info.cap_offset = sizeof(info);
828                         }
829
830                         kfree(caps.buf);
831                 }
832
833                 return copy_to_user((void __user *)arg, &info, minsz) ?
834                         -EFAULT : 0;
835
836         } else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
837                 struct vfio_irq_info info;
838
839                 minsz = offsetofend(struct vfio_irq_info, count);
840
841                 if (copy_from_user(&info, (void __user *)arg, minsz))
842                         return -EFAULT;
843
844                 if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
845                         return -EINVAL;
846
847                 switch (info.index) {
848                 case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
849                 case VFIO_PCI_REQ_IRQ_INDEX:
850                         break;
851                 case VFIO_PCI_ERR_IRQ_INDEX:
852                         if (pci_is_pcie(vdev->pdev))
853                                 break;
854                 /* pass thru to return error */
855                 default:
856                         return -EINVAL;
857                 }
858
859                 info.flags = VFIO_IRQ_INFO_EVENTFD;
860
861                 info.count = vfio_pci_get_irq_count(vdev, info.index);
862
863                 if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
864                         info.flags |= (VFIO_IRQ_INFO_MASKABLE |
865                                        VFIO_IRQ_INFO_AUTOMASKED);
866                 else
867                         info.flags |= VFIO_IRQ_INFO_NORESIZE;
868
869                 return copy_to_user((void __user *)arg, &info, minsz) ?
870                         -EFAULT : 0;
871
872         } else if (cmd == VFIO_DEVICE_SET_IRQS) {
873                 struct vfio_irq_set hdr;
874                 size_t size;
875                 u8 *data = NULL;
876                 int max, ret = 0;
877
878                 minsz = offsetofend(struct vfio_irq_set, count);
879
880                 if (copy_from_user(&hdr, (void __user *)arg, minsz))
881                         return -EFAULT;
882
883                 if (hdr.argsz < minsz || hdr.index >= VFIO_PCI_NUM_IRQS ||
884                     hdr.count >= (U32_MAX - hdr.start) ||
885                     hdr.flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK |
886                                   VFIO_IRQ_SET_ACTION_TYPE_MASK))
887                         return -EINVAL;
888
889                 max = vfio_pci_get_irq_count(vdev, hdr.index);
890                 if (hdr.start >= max || hdr.start + hdr.count > max)
891                         return -EINVAL;
892
893                 switch (hdr.flags & VFIO_IRQ_SET_DATA_TYPE_MASK) {
894                 case VFIO_IRQ_SET_DATA_NONE:
895                         size = 0;
896                         break;
897                 case VFIO_IRQ_SET_DATA_BOOL:
898                         size = sizeof(uint8_t);
899                         break;
900                 case VFIO_IRQ_SET_DATA_EVENTFD:
901                         size = sizeof(int32_t);
902                         break;
903                 default:
904                         return -EINVAL;
905                 }
906
907                 if (size) {
908                         if (hdr.argsz - minsz < hdr.count * size)
909                                 return -EINVAL;
910
911                         data = memdup_user((void __user *)(arg + minsz),
912                                            hdr.count * size);
913                         if (IS_ERR(data))
914                                 return PTR_ERR(data);
915                 }
916
917                 mutex_lock(&vdev->igate);
918
919                 ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
920                                               hdr.start, hdr.count, data);
921
922                 mutex_unlock(&vdev->igate);
923                 kfree(data);
924
925                 return ret;
926
927         } else if (cmd == VFIO_DEVICE_RESET) {
928                 int ret;
929
930                 if (!vdev->reset_works)
931                         return -EINVAL;
932
933                 vfio_pci_zap_and_down_write_memory_lock(vdev);
934                 ret = pci_try_reset_function(vdev->pdev);
935                 up_write(&vdev->memory_lock);
936
937                 return ret;
938
939         } else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
940                 struct vfio_pci_hot_reset_info hdr;
941                 struct vfio_pci_fill_info fill = { 0 };
942                 struct vfio_pci_dependent_device *devices = NULL;
943                 bool slot = false;
944                 int ret = 0;
945
946                 minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
947
948                 if (copy_from_user(&hdr, (void __user *)arg, minsz))
949                         return -EFAULT;
950
951                 if (hdr.argsz < minsz)
952                         return -EINVAL;
953
954                 hdr.flags = 0;
955
956                 /* Can we do a slot or bus reset or neither? */
957                 if (!pci_probe_reset_slot(vdev->pdev->slot))
958                         slot = true;
959                 else if (pci_probe_reset_bus(vdev->pdev->bus))
960                         return -ENODEV;
961
962                 /* How many devices are affected? */
963                 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
964                                                     vfio_pci_count_devs,
965                                                     &fill.max, slot);
966                 if (ret)
967                         return ret;
968
969                 WARN_ON(!fill.max); /* Should always be at least one */
970
971                 /*
972                  * If there's enough space, fill it now, otherwise return
973                  * -ENOSPC and the number of devices affected.
974                  */
975                 if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
976                         ret = -ENOSPC;
977                         hdr.count = fill.max;
978                         goto reset_info_exit;
979                 }
980
981                 devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
982                 if (!devices)
983                         return -ENOMEM;
984
985                 fill.devices = devices;
986
987                 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
988                                                     vfio_pci_fill_devs,
989                                                     &fill, slot);
990
991                 /*
992                  * If a device was removed between counting and filling,
993                  * we may come up short of fill.max.  If a device was
994                  * added, we'll have a return of -EAGAIN above.
995                  */
996                 if (!ret)
997                         hdr.count = fill.cur;
998
999 reset_info_exit:
1000                 if (copy_to_user((void __user *)arg, &hdr, minsz))
1001                         ret = -EFAULT;
1002
1003                 if (!ret) {
1004                         if (copy_to_user((void __user *)(arg + minsz), devices,
1005                                          hdr.count * sizeof(*devices)))
1006                                 ret = -EFAULT;
1007                 }
1008
1009                 kfree(devices);
1010                 return ret;
1011
1012         } else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
1013                 struct vfio_pci_hot_reset hdr;
1014                 int32_t *group_fds;
1015                 struct vfio_pci_group_entry *groups;
1016                 struct vfio_pci_group_info info;
1017                 struct vfio_devices devs = { .cur_index = 0 };
1018                 bool slot = false;
1019                 int i, group_idx, mem_idx = 0, count = 0, ret = 0;
1020
1021                 minsz = offsetofend(struct vfio_pci_hot_reset, count);
1022
1023                 if (copy_from_user(&hdr, (void __user *)arg, minsz))
1024                         return -EFAULT;
1025
1026                 if (hdr.argsz < minsz || hdr.flags)
1027                         return -EINVAL;
1028
1029                 /* Can we do a slot or bus reset or neither? */
1030                 if (!pci_probe_reset_slot(vdev->pdev->slot))
1031                         slot = true;
1032                 else if (pci_probe_reset_bus(vdev->pdev->bus))
1033                         return -ENODEV;
1034
1035                 /*
1036                  * We can't let userspace give us an arbitrarily large
1037                  * buffer to copy, so verify how many we think there
1038                  * could be.  Note groups can have multiple devices so
1039                  * one group per device is the max.
1040                  */
1041                 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1042                                                     vfio_pci_count_devs,
1043                                                     &count, slot);
1044                 if (ret)
1045                         return ret;
1046
1047                 /* Somewhere between 1 and count is OK */
1048                 if (!hdr.count || hdr.count > count)
1049                         return -EINVAL;
1050
1051                 group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
1052                 groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);
1053                 if (!group_fds || !groups) {
1054                         kfree(group_fds);
1055                         kfree(groups);
1056                         return -ENOMEM;
1057                 }
1058
1059                 if (copy_from_user(group_fds, (void __user *)(arg + minsz),
1060                                    hdr.count * sizeof(*group_fds))) {
1061                         kfree(group_fds);
1062                         kfree(groups);
1063                         return -EFAULT;
1064                 }
1065
1066                 /*
1067                  * For each group_fd, get the group through the vfio external
1068                  * user interface and store the group and iommu ID.  This
1069                  * ensures the group is held across the reset.
1070                  */
1071                 for (group_idx = 0; group_idx < hdr.count; group_idx++) {
1072                         struct vfio_group *group;
1073                         struct fd f = fdget(group_fds[group_idx]);
1074                         if (!f.file) {
1075                                 ret = -EBADF;
1076                                 break;
1077                         }
1078
1079                         group = vfio_group_get_external_user(f.file);
1080                         fdput(f);
1081                         if (IS_ERR(group)) {
1082                                 ret = PTR_ERR(group);
1083                                 break;
1084                         }
1085
1086                         groups[group_idx].group = group;
1087                         groups[group_idx].id =
1088                                         vfio_external_user_iommu_id(group);
1089                 }
1090
1091                 kfree(group_fds);
1092
1093                 /* release reference to groups on error */
1094                 if (ret)
1095                         goto hot_reset_release;
1096
1097                 info.count = hdr.count;
1098                 info.groups = groups;
1099
1100                 /*
1101                  * Test whether all the affected devices are contained
1102                  * by the set of groups provided by the user.
1103                  */
1104                 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1105                                                     vfio_pci_validate_devs,
1106                                                     &info, slot);
1107
1108                 if (ret)
1109                         goto hot_reset_release;
1110
1111                 devs.max_index = count;
1112                 devs.devices = kcalloc(count, sizeof(struct vfio_device *),
1113                                        GFP_KERNEL);
1114                 if (!devs.devices) {
1115                         ret = -ENOMEM;
1116                         goto hot_reset_release;
1117                 }
1118
1119                 /*
1120                  * We need to get memory_lock for each device, but devices
1121                  * can share mmap_sem, therefore we need to zap and hold
1122                  * the vma_lock for each device, and only then get each
1123                  * memory_lock.
1124                  */
1125                 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
1126                                             vfio_pci_try_zap_and_vma_lock_cb,
1127                                             &devs, slot);
1128                 if (ret)
1129                         goto hot_reset_release;
1130
1131                 for (; mem_idx < devs.cur_index; mem_idx++) {
1132                         struct vfio_pci_device *tmp;
1133
1134                         tmp = vfio_device_data(devs.devices[mem_idx]);
1135
1136                         ret = down_write_trylock(&tmp->memory_lock);
1137                         if (!ret) {
1138                                 ret = -EBUSY;
1139                                 goto hot_reset_release;
1140                         }
1141                         mutex_unlock(&tmp->vma_lock);
1142                 }
1143
1144                 /* User has access, do the reset */
1145                 ret = slot ? pci_try_reset_slot(vdev->pdev->slot) :
1146                                 pci_try_reset_bus(vdev->pdev->bus);
1147
1148 hot_reset_release:
1149                 for (i = 0; i < devs.cur_index; i++) {
1150                         struct vfio_device *device;
1151                         struct vfio_pci_device *tmp;
1152
1153                         device = devs.devices[i];
1154                         tmp = vfio_device_data(device);
1155
1156                         if (i < mem_idx)
1157                                 up_write(&tmp->memory_lock);
1158                         else
1159                                 mutex_unlock(&tmp->vma_lock);
1160                         vfio_device_put(device);
1161                 }
1162                 kfree(devs.devices);
1163
1164                 for (group_idx--; group_idx >= 0; group_idx--)
1165                         vfio_group_put_external_user(groups[group_idx].group);
1166
1167                 kfree(groups);
1168                 return ret;
1169         }
1170
1171         return -ENOTTY;
1172 }
1173
1174 static ssize_t vfio_pci_rw(void *device_data, char __user *buf,
1175                            size_t count, loff_t *ppos, bool iswrite)
1176 {
1177         unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
1178         struct vfio_pci_device *vdev = device_data;
1179
1180         if (index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions)
1181                 return -EINVAL;
1182
1183         switch (index) {
1184         case VFIO_PCI_CONFIG_REGION_INDEX:
1185                 return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
1186
1187         case VFIO_PCI_ROM_REGION_INDEX:
1188                 if (iswrite)
1189                         return -EINVAL;
1190                 return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
1191
1192         case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
1193                 return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
1194
1195         case VFIO_PCI_VGA_REGION_INDEX:
1196                 return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
1197         default:
1198                 index -= VFIO_PCI_NUM_REGIONS;
1199                 return vdev->region[index].ops->rw(vdev, buf,
1200                                                    count, ppos, iswrite);
1201         }
1202
1203         return -EINVAL;
1204 }
1205
1206 static ssize_t vfio_pci_read(void *device_data, char __user *buf,
1207                              size_t count, loff_t *ppos)
1208 {
1209         if (!count)
1210                 return 0;
1211
1212         return vfio_pci_rw(device_data, buf, count, ppos, false);
1213 }
1214
1215 static ssize_t vfio_pci_write(void *device_data, const char __user *buf,
1216                               size_t count, loff_t *ppos)
1217 {
1218         if (!count)
1219                 return 0;
1220
1221         return vfio_pci_rw(device_data, (char __user *)buf, count, ppos, true);
1222 }
1223
1224 /* Return 1 on zap and vma_lock acquired, 0 on contention (only with @try) */
1225 static int vfio_pci_zap_and_vma_lock(struct vfio_pci_device *vdev, bool try)
1226 {
1227         struct vfio_pci_mmap_vma *mmap_vma, *tmp;
1228
1229         /*
1230          * Lock ordering:
1231          * vma_lock is nested under mmap_sem for vm_ops callback paths.
1232          * The memory_lock semaphore is used by both code paths calling
1233          * into this function to zap vmas and the vm_ops.fault callback
1234          * to protect the memory enable state of the device.
1235          *
1236          * When zapping vmas we need to maintain the mmap_sem => vma_lock
1237          * ordering, which requires using vma_lock to walk vma_list to
1238          * acquire an mm, then dropping vma_lock to get the mmap_sem and
1239          * reacquiring vma_lock.  This logic is derived from similar
1240          * requirements in uverbs_user_mmap_disassociate().
1241          *
1242          * mmap_sem must always be the top-level lock when it is taken.
1243          * Therefore we can only hold the memory_lock write lock when
1244          * vma_list is empty, as we'd need to take mmap_sem to clear
1245          * entries.  vma_list can only be guaranteed empty when holding
1246          * vma_lock, thus memory_lock is nested under vma_lock.
1247          *
1248          * This enables the vm_ops.fault callback to acquire vma_lock,
1249          * followed by memory_lock read lock, while already holding
1250          * mmap_sem without risk of deadlock.
1251          */
1252         while (1) {
1253                 struct mm_struct *mm = NULL;
1254
1255                 if (try) {
1256                         if (!mutex_trylock(&vdev->vma_lock))
1257                                 return 0;
1258                 } else {
1259                         mutex_lock(&vdev->vma_lock);
1260                 }
1261                 while (!list_empty(&vdev->vma_list)) {
1262                         mmap_vma = list_first_entry(&vdev->vma_list,
1263                                                     struct vfio_pci_mmap_vma,
1264                                                     vma_next);
1265                         mm = mmap_vma->vma->vm_mm;
1266                         if (mmget_not_zero(mm))
1267                                 break;
1268
1269                         list_del(&mmap_vma->vma_next);
1270                         kfree(mmap_vma);
1271                         mm = NULL;
1272                 }
1273                 if (!mm)
1274                         return 1;
1275                 mutex_unlock(&vdev->vma_lock);
1276
1277                 if (try) {
1278                         if (!down_read_trylock(&mm->mmap_sem)) {
1279                                 mmput(mm);
1280                                 return 0;
1281                         }
1282                 } else {
1283                         down_read(&mm->mmap_sem);
1284                 }
1285                 if (mmget_still_valid(mm)) {
1286                         if (try) {
1287                                 if (!mutex_trylock(&vdev->vma_lock)) {
1288                                         up_read(&mm->mmap_sem);
1289                                         mmput(mm);
1290                                         return 0;
1291                                 }
1292                         } else {
1293                                 mutex_lock(&vdev->vma_lock);
1294                         }
1295                         list_for_each_entry_safe(mmap_vma, tmp,
1296                                                  &vdev->vma_list, vma_next) {
1297                                 struct vm_area_struct *vma = mmap_vma->vma;
1298
1299                                 if (vma->vm_mm != mm)
1300                                         continue;
1301
1302                                 list_del(&mmap_vma->vma_next);
1303                                 kfree(mmap_vma);
1304
1305                                 zap_vma_ptes(vma, vma->vm_start,
1306                                              vma->vm_end - vma->vm_start);
1307                         }
1308                         mutex_unlock(&vdev->vma_lock);
1309                 }
1310                 up_read(&mm->mmap_sem);
1311                 mmput(mm);
1312         }
1313 }
1314
1315 void vfio_pci_zap_and_down_write_memory_lock(struct vfio_pci_device *vdev)
1316 {
1317         vfio_pci_zap_and_vma_lock(vdev, false);
1318         down_write(&vdev->memory_lock);
1319         mutex_unlock(&vdev->vma_lock);
1320 }
1321
1322 u16 vfio_pci_memory_lock_and_enable(struct vfio_pci_device *vdev)
1323 {
1324         u16 cmd;
1325
1326         down_write(&vdev->memory_lock);
1327         pci_read_config_word(vdev->pdev, PCI_COMMAND, &cmd);
1328         if (!(cmd & PCI_COMMAND_MEMORY))
1329                 pci_write_config_word(vdev->pdev, PCI_COMMAND,
1330                                       cmd | PCI_COMMAND_MEMORY);
1331
1332         return cmd;
1333 }
1334
1335 void vfio_pci_memory_unlock_and_restore(struct vfio_pci_device *vdev, u16 cmd)
1336 {
1337         pci_write_config_word(vdev->pdev, PCI_COMMAND, cmd);
1338         up_write(&vdev->memory_lock);
1339 }
1340
1341 /* Caller holds vma_lock */
1342 static int __vfio_pci_add_vma(struct vfio_pci_device *vdev,
1343                               struct vm_area_struct *vma)
1344 {
1345         struct vfio_pci_mmap_vma *mmap_vma;
1346
1347         mmap_vma = kmalloc(sizeof(*mmap_vma), GFP_KERNEL);
1348         if (!mmap_vma)
1349                 return -ENOMEM;
1350
1351         mmap_vma->vma = vma;
1352         list_add(&mmap_vma->vma_next, &vdev->vma_list);
1353
1354         return 0;
1355 }
1356
1357 /*
1358  * Zap mmaps on open so that we can fault them in on access and therefore
1359  * our vma_list only tracks mappings accessed since last zap.
1360  */
1361 static void vfio_pci_mmap_open(struct vm_area_struct *vma)
1362 {
1363         zap_vma_ptes(vma, vma->vm_start, vma->vm_end - vma->vm_start);
1364 }
1365
1366 static void vfio_pci_mmap_close(struct vm_area_struct *vma)
1367 {
1368         struct vfio_pci_device *vdev = vma->vm_private_data;
1369         struct vfio_pci_mmap_vma *mmap_vma;
1370
1371         mutex_lock(&vdev->vma_lock);
1372         list_for_each_entry(mmap_vma, &vdev->vma_list, vma_next) {
1373                 if (mmap_vma->vma == vma) {
1374                         list_del(&mmap_vma->vma_next);
1375                         kfree(mmap_vma);
1376                         break;
1377                 }
1378         }
1379         mutex_unlock(&vdev->vma_lock);
1380 }
1381
1382 static int vfio_pci_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1383 {
1384         struct vfio_pci_device *vdev = vma->vm_private_data;
1385         int ret = VM_FAULT_NOPAGE;
1386
1387         mutex_lock(&vdev->vma_lock);
1388         down_read(&vdev->memory_lock);
1389
1390         if (!__vfio_pci_memory_enabled(vdev)) {
1391                 ret = VM_FAULT_SIGBUS;
1392                 mutex_unlock(&vdev->vma_lock);
1393                 goto up_out;
1394         }
1395
1396         if (__vfio_pci_add_vma(vdev, vma)) {
1397                 ret = VM_FAULT_OOM;
1398                 mutex_unlock(&vdev->vma_lock);
1399                 goto up_out;
1400         }
1401
1402         mutex_unlock(&vdev->vma_lock);
1403
1404         if (io_remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
1405                                vma->vm_end - vma->vm_start, vma->vm_page_prot))
1406                 ret = VM_FAULT_SIGBUS;
1407
1408 up_out:
1409         up_read(&vdev->memory_lock);
1410         return ret;
1411 }
1412
1413 static const struct vm_operations_struct vfio_pci_mmap_ops = {
1414         .open = vfio_pci_mmap_open,
1415         .close = vfio_pci_mmap_close,
1416         .fault = vfio_pci_mmap_fault,
1417 };
1418
1419 static int vfio_pci_mmap(void *device_data, struct vm_area_struct *vma)
1420 {
1421         struct vfio_pci_device *vdev = device_data;
1422         struct pci_dev *pdev = vdev->pdev;
1423         unsigned int index;
1424         u64 phys_len, req_len, pgoff, req_start;
1425         int ret;
1426
1427         index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
1428
1429         if (vma->vm_end < vma->vm_start)
1430                 return -EINVAL;
1431         if ((vma->vm_flags & VM_SHARED) == 0)
1432                 return -EINVAL;
1433         if (index >= VFIO_PCI_ROM_REGION_INDEX)
1434                 return -EINVAL;
1435         if (!vdev->bar_mmap_supported[index])
1436                 return -EINVAL;
1437
1438         phys_len = PAGE_ALIGN(pci_resource_len(pdev, index));
1439         req_len = vma->vm_end - vma->vm_start;
1440         pgoff = vma->vm_pgoff &
1441                 ((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
1442         req_start = pgoff << PAGE_SHIFT;
1443
1444         if (req_start + req_len > phys_len)
1445                 return -EINVAL;
1446
1447         if (index == vdev->msix_bar) {
1448                 /*
1449                  * Disallow mmaps overlapping the MSI-X table; users don't
1450                  * get to touch this directly.  We could find somewhere
1451                  * else to map the overlap, but page granularity is only
1452                  * a recommendation, not a requirement, so the user needs
1453                  * to know which bits are real.  Requiring them to mmap
1454                  * around the table makes that clear.
1455                  */
1456
1457                 /* If neither entirely above nor below, then it overlaps */
1458                 if (!(req_start >= vdev->msix_offset + vdev->msix_size ||
1459                       req_start + req_len <= vdev->msix_offset))
1460                         return -EINVAL;
1461         }
1462
1463         /*
1464          * Even though we don't make use of the barmap for the mmap,
1465          * we need to request the region and the barmap tracks that.
1466          */
1467         if (!vdev->barmap[index]) {
1468                 ret = pci_request_selected_regions(pdev,
1469                                                    1 << index, "vfio-pci");
1470                 if (ret)
1471                         return ret;
1472
1473                 vdev->barmap[index] = pci_iomap(pdev, index, 0);
1474                 if (!vdev->barmap[index]) {
1475                         pci_release_selected_regions(pdev, 1 << index);
1476                         return -ENOMEM;
1477                 }
1478         }
1479
1480         vma->vm_private_data = vdev;
1481         vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1482         vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
1483
1484         /*
1485          * See remap_pfn_range(), called from vfio_pci_fault() but we can't
1486          * change vm_flags within the fault handler.  Set them now.
1487          */
1488         vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
1489         vma->vm_ops = &vfio_pci_mmap_ops;
1490
1491         return 0;
1492 }
1493
1494 static void vfio_pci_request(void *device_data, unsigned int count)
1495 {
1496         struct vfio_pci_device *vdev = device_data;
1497
1498         mutex_lock(&vdev->igate);
1499
1500         if (vdev->req_trigger) {
1501                 if (!(count % 10))
1502                         dev_notice_ratelimited(&vdev->pdev->dev,
1503                                 "Relaying device request to user (#%u)\n",
1504                                 count);
1505                 eventfd_signal(vdev->req_trigger, 1);
1506         } else if (count == 0) {
1507                 dev_warn(&vdev->pdev->dev,
1508                         "No device request channel registered, blocked until released by user\n");
1509         }
1510
1511         mutex_unlock(&vdev->igate);
1512 }
1513
1514 static const struct vfio_device_ops vfio_pci_ops = {
1515         .name           = "vfio-pci",
1516         .open           = vfio_pci_open,
1517         .release        = vfio_pci_release,
1518         .ioctl          = vfio_pci_ioctl,
1519         .read           = vfio_pci_read,
1520         .write          = vfio_pci_write,
1521         .mmap           = vfio_pci_mmap,
1522         .request        = vfio_pci_request,
1523 };
1524
1525 static int vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1526 {
1527         struct vfio_pci_device *vdev;
1528         struct iommu_group *group;
1529         int ret;
1530
1531         if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
1532                 return -EINVAL;
1533
1534         group = vfio_iommu_group_get(&pdev->dev);
1535         if (!group)
1536                 return -EINVAL;
1537
1538         vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
1539         if (!vdev) {
1540                 vfio_iommu_group_put(group, &pdev->dev);
1541                 return -ENOMEM;
1542         }
1543
1544         vdev->pdev = pdev;
1545         vdev->irq_type = VFIO_PCI_NUM_IRQS;
1546         mutex_init(&vdev->igate);
1547         spin_lock_init(&vdev->irqlock);
1548         INIT_LIST_HEAD(&vdev->dummy_resources_list);
1549         mutex_init(&vdev->vma_lock);
1550         INIT_LIST_HEAD(&vdev->vma_list);
1551         init_rwsem(&vdev->memory_lock);
1552         ret = vfio_add_group_dev(&pdev->dev, &vfio_pci_ops, vdev);
1553         if (ret) {
1554                 vfio_iommu_group_put(group, &pdev->dev);
1555                 kfree(vdev);
1556                 return ret;
1557         }
1558
1559         if (vfio_pci_is_vga(pdev)) {
1560                 vga_client_register(pdev, vdev, NULL, vfio_pci_set_vga_decode);
1561                 vga_set_legacy_decoding(pdev,
1562                                         vfio_pci_set_vga_decode(vdev, false));
1563         }
1564
1565         if (!disable_idle_d3) {
1566                 /*
1567                  * pci-core sets the device power state to an unknown value at
1568                  * bootup and after being removed from a driver.  The only
1569                  * transition it allows from this unknown state is to D0, which
1570                  * typically happens when a driver calls pci_enable_device().
1571                  * We're not ready to enable the device yet, but we do want to
1572                  * be able to get to D3.  Therefore first do a D0 transition
1573                  * before going to D3.
1574                  */
1575                 pci_set_power_state(pdev, PCI_D0);
1576                 pci_set_power_state(pdev, PCI_D3hot);
1577         }
1578
1579         return ret;
1580 }
1581
1582 static void vfio_pci_remove(struct pci_dev *pdev)
1583 {
1584         struct vfio_pci_device *vdev;
1585
1586         vdev = vfio_del_group_dev(&pdev->dev);
1587         if (!vdev)
1588                 return;
1589
1590         vfio_iommu_group_put(pdev->dev.iommu_group, &pdev->dev);
1591         kfree(vdev->region);
1592         kfree(vdev);
1593
1594         if (vfio_pci_is_vga(pdev)) {
1595                 vga_client_register(pdev, NULL, NULL, NULL);
1596                 vga_set_legacy_decoding(pdev,
1597                                 VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
1598                                 VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM);
1599         }
1600
1601         if (!disable_idle_d3)
1602                 pci_set_power_state(pdev, PCI_D0);
1603 }
1604
1605 static pci_ers_result_t vfio_pci_aer_err_detected(struct pci_dev *pdev,
1606                                                   pci_channel_state_t state)
1607 {
1608         struct vfio_pci_device *vdev;
1609         struct vfio_device *device;
1610
1611         device = vfio_device_get_from_dev(&pdev->dev);
1612         if (device == NULL)
1613                 return PCI_ERS_RESULT_DISCONNECT;
1614
1615         vdev = vfio_device_data(device);
1616         if (vdev == NULL) {
1617                 vfio_device_put(device);
1618                 return PCI_ERS_RESULT_DISCONNECT;
1619         }
1620
1621         mutex_lock(&vdev->igate);
1622
1623         if (vdev->err_trigger)
1624                 eventfd_signal(vdev->err_trigger, 1);
1625
1626         mutex_unlock(&vdev->igate);
1627
1628         vfio_device_put(device);
1629
1630         return PCI_ERS_RESULT_CAN_RECOVER;
1631 }
1632
1633 static const struct pci_error_handlers vfio_err_handlers = {
1634         .error_detected = vfio_pci_aer_err_detected,
1635 };
1636
1637 static struct pci_driver vfio_pci_driver = {
1638         .name           = "vfio-pci",
1639         .id_table       = NULL, /* only dynamic ids */
1640         .probe          = vfio_pci_probe,
1641         .remove         = vfio_pci_remove,
1642         .err_handler    = &vfio_err_handlers,
1643 };
1644
1645 static int vfio_pci_get_devs(struct pci_dev *pdev, void *data)
1646 {
1647         struct vfio_devices *devs = data;
1648         struct vfio_device *device;
1649
1650         if (devs->cur_index == devs->max_index)
1651                 return -ENOSPC;
1652
1653         device = vfio_device_get_from_dev(&pdev->dev);
1654         if (!device)
1655                 return -EINVAL;
1656
1657         if (pci_dev_driver(pdev) != &vfio_pci_driver) {
1658                 vfio_device_put(device);
1659                 return -EBUSY;
1660         }
1661
1662         devs->devices[devs->cur_index++] = device;
1663         return 0;
1664 }
1665
1666 static int vfio_pci_try_zap_and_vma_lock_cb(struct pci_dev *pdev, void *data)
1667 {
1668         struct vfio_devices *devs = data;
1669         struct vfio_device *device;
1670         struct vfio_pci_device *vdev;
1671
1672         if (devs->cur_index == devs->max_index)
1673                 return -ENOSPC;
1674
1675         device = vfio_device_get_from_dev(&pdev->dev);
1676         if (!device)
1677                 return -EINVAL;
1678
1679         if (pci_dev_driver(pdev) != &vfio_pci_driver) {
1680                 vfio_device_put(device);
1681                 return -EBUSY;
1682         }
1683
1684         vdev = vfio_device_data(device);
1685
1686         /*
1687          * Locking multiple devices is prone to deadlock, runaway and
1688          * unwind if we hit contention.
1689          */
1690         if (!vfio_pci_zap_and_vma_lock(vdev, true)) {
1691                 vfio_device_put(device);
1692                 return -EBUSY;
1693         }
1694
1695         devs->devices[devs->cur_index++] = device;
1696         return 0;
1697 }
1698
1699 /*
1700  * Attempt to do a bus/slot reset if there are devices affected by a reset for
1701  * this device that are needs_reset and all of the affected devices are unused
1702  * (!refcnt).  Callers are required to hold driver_lock when calling this to
1703  * prevent device opens and concurrent bus reset attempts.  We prevent device
1704  * unbinds by acquiring and holding a reference to the vfio_device.
1705  *
1706  * NB: vfio-core considers a group to be viable even if some devices are
1707  * bound to drivers like pci-stub or pcieport.  Here we require all devices
1708  * to be bound to vfio_pci since that's the only way we can be sure they
1709  * stay put.
1710  */
1711 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev)
1712 {
1713         struct vfio_devices devs = { .cur_index = 0 };
1714         int i = 0, ret = -EINVAL;
1715         bool needs_reset = false, slot = false;
1716         struct vfio_pci_device *tmp;
1717
1718         if (!pci_probe_reset_slot(vdev->pdev->slot))
1719                 slot = true;
1720         else if (pci_probe_reset_bus(vdev->pdev->bus))
1721                 return;
1722
1723         if (vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
1724                                           &i, slot) || !i)
1725                 return;
1726
1727         devs.max_index = i;
1728         devs.devices = kcalloc(i, sizeof(struct vfio_device *), GFP_KERNEL);
1729         if (!devs.devices)
1730                 return;
1731
1732         if (vfio_pci_for_each_slot_or_bus(vdev->pdev,
1733                                           vfio_pci_get_devs, &devs, slot))
1734                 goto put_devs;
1735
1736         for (i = 0; i < devs.cur_index; i++) {
1737                 tmp = vfio_device_data(devs.devices[i]);
1738                 if (tmp->needs_reset)
1739                         needs_reset = true;
1740                 if (tmp->refcnt)
1741                         goto put_devs;
1742         }
1743
1744         if (needs_reset)
1745                 ret = slot ? pci_try_reset_slot(vdev->pdev->slot) :
1746                              pci_try_reset_bus(vdev->pdev->bus);
1747
1748 put_devs:
1749         for (i = 0; i < devs.cur_index; i++) {
1750                 tmp = vfio_device_data(devs.devices[i]);
1751                 if (!ret)
1752                         tmp->needs_reset = false;
1753
1754                 if (!tmp->refcnt && !disable_idle_d3)
1755                         pci_set_power_state(tmp->pdev, PCI_D3hot);
1756
1757                 vfio_device_put(devs.devices[i]);
1758         }
1759
1760         kfree(devs.devices);
1761 }
1762
1763 static void __exit vfio_pci_cleanup(void)
1764 {
1765         pci_unregister_driver(&vfio_pci_driver);
1766         vfio_pci_uninit_perm_bits();
1767 }
1768
1769 static void __init vfio_pci_fill_ids(void)
1770 {
1771         char *p, *id;
1772         int rc;
1773
1774         /* no ids passed actually */
1775         if (ids[0] == '\0')
1776                 return;
1777
1778         /* add ids specified in the module parameter */
1779         p = ids;
1780         while ((id = strsep(&p, ","))) {
1781                 unsigned int vendor, device, subvendor = PCI_ANY_ID,
1782                         subdevice = PCI_ANY_ID, class = 0, class_mask = 0;
1783                 int fields;
1784
1785                 if (!strlen(id))
1786                         continue;
1787
1788                 fields = sscanf(id, "%x:%x:%x:%x:%x:%x",
1789                                 &vendor, &device, &subvendor, &subdevice,
1790                                 &class, &class_mask);
1791
1792                 if (fields < 2) {
1793                         pr_warn("invalid id string \"%s\"\n", id);
1794                         continue;
1795                 }
1796
1797                 rc = pci_add_dynid(&vfio_pci_driver, vendor, device,
1798                                    subvendor, subdevice, class, class_mask, 0);
1799                 if (rc)
1800                         pr_warn("failed to add dynamic id [%04x:%04x[%04x:%04x]] class %#08x/%08x (%d)\n",
1801                                 vendor, device, subvendor, subdevice,
1802                                 class, class_mask, rc);
1803                 else
1804                         pr_info("add [%04x:%04x[%04x:%04x]] class %#08x/%08x\n",
1805                                 vendor, device, subvendor, subdevice,
1806                                 class, class_mask);
1807         }
1808 }
1809
1810 static int __init vfio_pci_init(void)
1811 {
1812         int ret;
1813
1814         /* Allocate shared config space permision data used by all devices */
1815         ret = vfio_pci_init_perm_bits();
1816         if (ret)
1817                 return ret;
1818
1819         /* Register and scan for devices */
1820         ret = pci_register_driver(&vfio_pci_driver);
1821         if (ret)
1822                 goto out_driver;
1823
1824         vfio_pci_fill_ids();
1825
1826         return 0;
1827
1828 out_driver:
1829         vfio_pci_uninit_perm_bits();
1830         return ret;
1831 }
1832
1833 module_init(vfio_pci_init);
1834 module_exit(vfio_pci_cleanup);
1835
1836 MODULE_VERSION(DRIVER_VERSION);
1837 MODULE_LICENSE("GPL v2");
1838 MODULE_AUTHOR(DRIVER_AUTHOR);
1839 MODULE_DESCRIPTION(DRIVER_DESC);