Linux-libre 4.4.228-gnu
[librecmc/linux-libre.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
32 #include "vfio_pci_private.h"
33
34 #define DRIVER_VERSION  "0.2"
35 #define DRIVER_AUTHOR   "Alex Williamson <alex.williamson@redhat.com>"
36 #define DRIVER_DESC     "VFIO PCI - User Level meta-driver"
37
38 static char ids[1024] __initdata;
39 module_param_string(ids, ids, sizeof(ids), 0);
40 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");
41
42 static bool nointxmask;
43 module_param_named(nointxmask, nointxmask, bool, S_IRUGO | S_IWUSR);
44 MODULE_PARM_DESC(nointxmask,
45                   "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.");
46
47 #ifdef CONFIG_VFIO_PCI_VGA
48 static bool disable_vga;
49 module_param(disable_vga, bool, S_IRUGO);
50 MODULE_PARM_DESC(disable_vga, "Disable VGA resource access through vfio-pci");
51 #endif
52
53 static bool disable_idle_d3;
54 module_param(disable_idle_d3, bool, S_IRUGO | S_IWUSR);
55 MODULE_PARM_DESC(disable_idle_d3,
56                  "Disable using the PCI D3 low power state for idle, unused devices");
57
58 static DEFINE_MUTEX(driver_lock);
59
60 static inline bool vfio_vga_disabled(void)
61 {
62 #ifdef CONFIG_VFIO_PCI_VGA
63         return disable_vga;
64 #else
65         return true;
66 #endif
67 }
68
69 /*
70  * Our VGA arbiter participation is limited since we don't know anything
71  * about the device itself.  However, if the device is the only VGA device
72  * downstream of a bridge and VFIO VGA support is disabled, then we can
73  * safely return legacy VGA IO and memory as not decoded since the user
74  * has no way to get to it and routing can be disabled externally at the
75  * bridge.
76  */
77 static unsigned int vfio_pci_set_vga_decode(void *opaque, bool single_vga)
78 {
79         struct vfio_pci_device *vdev = opaque;
80         struct pci_dev *tmp = NULL, *pdev = vdev->pdev;
81         unsigned char max_busnr;
82         unsigned int decodes;
83
84         if (single_vga || !vfio_vga_disabled() || pci_is_root_bus(pdev->bus))
85                 return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
86                        VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
87
88         max_busnr = pci_bus_max_busnr(pdev->bus);
89         decodes = VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
90
91         while ((tmp = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, tmp)) != NULL) {
92                 if (tmp == pdev ||
93                     pci_domain_nr(tmp->bus) != pci_domain_nr(pdev->bus) ||
94                     pci_is_root_bus(tmp->bus))
95                         continue;
96
97                 if (tmp->bus->number >= pdev->bus->number &&
98                     tmp->bus->number <= max_busnr) {
99                         pci_dev_put(tmp);
100                         decodes |= VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
101                         break;
102                 }
103         }
104
105         return decodes;
106 }
107
108 static inline bool vfio_pci_is_vga(struct pci_dev *pdev)
109 {
110         return (pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA;
111 }
112
113 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev);
114
115 static int vfio_pci_enable(struct vfio_pci_device *vdev)
116 {
117         struct pci_dev *pdev = vdev->pdev;
118         int ret;
119         u16 cmd;
120         u8 msix_pos;
121
122         pci_set_power_state(pdev, PCI_D0);
123
124         /* Don't allow our initial saved state to include busmaster */
125         pci_clear_master(pdev);
126
127         ret = pci_enable_device(pdev);
128         if (ret)
129                 return ret;
130
131         vdev->reset_works = (pci_reset_function(pdev) == 0);
132         pci_save_state(pdev);
133         vdev->pci_saved_state = pci_store_saved_state(pdev);
134         if (!vdev->pci_saved_state)
135                 pr_debug("%s: Couldn't store %s saved state\n",
136                          __func__, dev_name(&pdev->dev));
137
138         ret = vfio_config_init(vdev);
139         if (ret) {
140                 kfree(vdev->pci_saved_state);
141                 vdev->pci_saved_state = NULL;
142                 pci_disable_device(pdev);
143                 return ret;
144         }
145
146         if (likely(!nointxmask))
147                 vdev->pci_2_3 = pci_intx_mask_supported(pdev);
148
149         pci_read_config_word(pdev, PCI_COMMAND, &cmd);
150         if (vdev->pci_2_3 && (cmd & PCI_COMMAND_INTX_DISABLE)) {
151                 cmd &= ~PCI_COMMAND_INTX_DISABLE;
152                 pci_write_config_word(pdev, PCI_COMMAND, cmd);
153         }
154
155         msix_pos = pdev->msix_cap;
156         if (msix_pos) {
157                 u16 flags;
158                 u32 table;
159
160                 pci_read_config_word(pdev, msix_pos + PCI_MSIX_FLAGS, &flags);
161                 pci_read_config_dword(pdev, msix_pos + PCI_MSIX_TABLE, &table);
162
163                 vdev->msix_bar = table & PCI_MSIX_TABLE_BIR;
164                 vdev->msix_offset = table & PCI_MSIX_TABLE_OFFSET;
165                 vdev->msix_size = ((flags & PCI_MSIX_FLAGS_QSIZE) + 1) * 16;
166         } else
167                 vdev->msix_bar = 0xFF;
168
169         if (!vfio_vga_disabled() && vfio_pci_is_vga(pdev))
170                 vdev->has_vga = true;
171
172         return 0;
173 }
174
175 static void vfio_pci_disable(struct vfio_pci_device *vdev)
176 {
177         struct pci_dev *pdev = vdev->pdev;
178         int bar;
179
180         /* Stop the device from further DMA */
181         pci_clear_master(pdev);
182
183         vfio_pci_set_irqs_ioctl(vdev, VFIO_IRQ_SET_DATA_NONE |
184                                 VFIO_IRQ_SET_ACTION_TRIGGER,
185                                 vdev->irq_type, 0, 0, NULL);
186
187         vdev->virq_disabled = false;
188
189         vfio_config_free(vdev);
190
191         for (bar = PCI_STD_RESOURCES; bar <= PCI_STD_RESOURCE_END; bar++) {
192                 if (!vdev->barmap[bar])
193                         continue;
194                 pci_iounmap(pdev, vdev->barmap[bar]);
195                 pci_release_selected_regions(pdev, 1 << bar);
196                 vdev->barmap[bar] = NULL;
197         }
198
199         vdev->needs_reset = true;
200
201         /*
202          * If we have saved state, restore it.  If we can reset the device,
203          * even better.  Resetting with current state seems better than
204          * nothing, but saving and restoring current state without reset
205          * is just busy work.
206          */
207         if (pci_load_and_free_saved_state(pdev, &vdev->pci_saved_state)) {
208                 pr_info("%s: Couldn't reload %s saved state\n",
209                         __func__, dev_name(&pdev->dev));
210
211                 if (!vdev->reset_works)
212                         goto out;
213
214                 pci_save_state(pdev);
215         }
216
217         /*
218          * Disable INTx and MSI, presumably to avoid spurious interrupts
219          * during reset.  Stolen from pci_reset_function()
220          */
221         pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
222
223         /*
224          * Try to get the locks ourselves to prevent a deadlock. The
225          * success of this is dependent on being able to lock the device,
226          * which is not always possible.
227          * We can not use the "try" reset interface here, which will
228          * overwrite the previously restored configuration information.
229          */
230         if (vdev->reset_works && pci_cfg_access_trylock(pdev)) {
231                 if (device_trylock(&pdev->dev)) {
232                         if (!__pci_reset_function_locked(pdev))
233                                 vdev->needs_reset = false;
234                         device_unlock(&pdev->dev);
235                 }
236                 pci_cfg_access_unlock(pdev);
237         }
238
239         pci_restore_state(pdev);
240 out:
241         pci_disable_device(pdev);
242
243         vfio_pci_try_bus_reset(vdev);
244
245         if (!disable_idle_d3)
246                 pci_set_power_state(pdev, PCI_D3hot);
247 }
248
249 static void vfio_pci_release(void *device_data)
250 {
251         struct vfio_pci_device *vdev = device_data;
252
253         mutex_lock(&driver_lock);
254
255         if (!(--vdev->refcnt)) {
256                 vfio_spapr_pci_eeh_release(vdev->pdev);
257                 vfio_pci_disable(vdev);
258         }
259
260         mutex_unlock(&driver_lock);
261
262         module_put(THIS_MODULE);
263 }
264
265 static int vfio_pci_open(void *device_data)
266 {
267         struct vfio_pci_device *vdev = device_data;
268         int ret = 0;
269
270         if (!try_module_get(THIS_MODULE))
271                 return -ENODEV;
272
273         mutex_lock(&driver_lock);
274
275         if (!vdev->refcnt) {
276                 ret = vfio_pci_enable(vdev);
277                 if (ret)
278                         goto error;
279
280                 vfio_spapr_pci_eeh_open(vdev->pdev);
281         }
282         vdev->refcnt++;
283 error:
284         mutex_unlock(&driver_lock);
285         if (ret)
286                 module_put(THIS_MODULE);
287         return ret;
288 }
289
290 static int vfio_pci_get_irq_count(struct vfio_pci_device *vdev, int irq_type)
291 {
292         if (irq_type == VFIO_PCI_INTX_IRQ_INDEX) {
293                 u8 pin;
294                 pci_read_config_byte(vdev->pdev, PCI_INTERRUPT_PIN, &pin);
295                 if (IS_ENABLED(CONFIG_VFIO_PCI_INTX) && pin)
296                         return 1;
297
298         } else if (irq_type == VFIO_PCI_MSI_IRQ_INDEX) {
299                 u8 pos;
300                 u16 flags;
301
302                 pos = vdev->pdev->msi_cap;
303                 if (pos) {
304                         pci_read_config_word(vdev->pdev,
305                                              pos + PCI_MSI_FLAGS, &flags);
306                         return 1 << ((flags & PCI_MSI_FLAGS_QMASK) >> 1);
307                 }
308         } else if (irq_type == VFIO_PCI_MSIX_IRQ_INDEX) {
309                 u8 pos;
310                 u16 flags;
311
312                 pos = vdev->pdev->msix_cap;
313                 if (pos) {
314                         pci_read_config_word(vdev->pdev,
315                                              pos + PCI_MSIX_FLAGS, &flags);
316
317                         return (flags & PCI_MSIX_FLAGS_QSIZE) + 1;
318                 }
319         } else if (irq_type == VFIO_PCI_ERR_IRQ_INDEX) {
320                 if (pci_is_pcie(vdev->pdev))
321                         return 1;
322         } else if (irq_type == VFIO_PCI_REQ_IRQ_INDEX) {
323                 return 1;
324         }
325
326         return 0;
327 }
328
329 static int vfio_pci_count_devs(struct pci_dev *pdev, void *data)
330 {
331         (*(int *)data)++;
332         return 0;
333 }
334
335 struct vfio_pci_fill_info {
336         int max;
337         int cur;
338         struct vfio_pci_dependent_device *devices;
339 };
340
341 static int vfio_pci_fill_devs(struct pci_dev *pdev, void *data)
342 {
343         struct vfio_pci_fill_info *fill = data;
344         struct iommu_group *iommu_group;
345
346         if (fill->cur == fill->max)
347                 return -EAGAIN; /* Something changed, try again */
348
349         iommu_group = iommu_group_get(&pdev->dev);
350         if (!iommu_group)
351                 return -EPERM; /* Cannot reset non-isolated devices */
352
353         fill->devices[fill->cur].group_id = iommu_group_id(iommu_group);
354         fill->devices[fill->cur].segment = pci_domain_nr(pdev->bus);
355         fill->devices[fill->cur].bus = pdev->bus->number;
356         fill->devices[fill->cur].devfn = pdev->devfn;
357         fill->cur++;
358         iommu_group_put(iommu_group);
359         return 0;
360 }
361
362 struct vfio_pci_group_entry {
363         struct vfio_group *group;
364         int id;
365 };
366
367 struct vfio_pci_group_info {
368         int count;
369         struct vfio_pci_group_entry *groups;
370 };
371
372 static int vfio_pci_validate_devs(struct pci_dev *pdev, void *data)
373 {
374         struct vfio_pci_group_info *info = data;
375         struct iommu_group *group;
376         int id, i;
377
378         group = iommu_group_get(&pdev->dev);
379         if (!group)
380                 return -EPERM;
381
382         id = iommu_group_id(group);
383
384         for (i = 0; i < info->count; i++)
385                 if (info->groups[i].id == id)
386                         break;
387
388         iommu_group_put(group);
389
390         return (i == info->count) ? -EINVAL : 0;
391 }
392
393 static bool vfio_pci_dev_below_slot(struct pci_dev *pdev, struct pci_slot *slot)
394 {
395         for (; pdev; pdev = pdev->bus->self)
396                 if (pdev->bus == slot->bus)
397                         return (pdev->slot == slot);
398         return false;
399 }
400
401 struct vfio_pci_walk_info {
402         int (*fn)(struct pci_dev *, void *data);
403         void *data;
404         struct pci_dev *pdev;
405         bool slot;
406         int ret;
407 };
408
409 static int vfio_pci_walk_wrapper(struct pci_dev *pdev, void *data)
410 {
411         struct vfio_pci_walk_info *walk = data;
412
413         if (!walk->slot || vfio_pci_dev_below_slot(pdev, walk->pdev->slot))
414                 walk->ret = walk->fn(pdev, walk->data);
415
416         return walk->ret;
417 }
418
419 static int vfio_pci_for_each_slot_or_bus(struct pci_dev *pdev,
420                                          int (*fn)(struct pci_dev *,
421                                                    void *data), void *data,
422                                          bool slot)
423 {
424         struct vfio_pci_walk_info walk = {
425                 .fn = fn, .data = data, .pdev = pdev, .slot = slot, .ret = 0,
426         };
427
428         pci_walk_bus(pdev->bus, vfio_pci_walk_wrapper, &walk);
429
430         return walk.ret;
431 }
432
433 static long vfio_pci_ioctl(void *device_data,
434                            unsigned int cmd, unsigned long arg)
435 {
436         struct vfio_pci_device *vdev = device_data;
437         unsigned long minsz;
438
439         if (cmd == VFIO_DEVICE_GET_INFO) {
440                 struct vfio_device_info info;
441
442                 minsz = offsetofend(struct vfio_device_info, num_irqs);
443
444                 if (copy_from_user(&info, (void __user *)arg, minsz))
445                         return -EFAULT;
446
447                 if (info.argsz < minsz)
448                         return -EINVAL;
449
450                 info.flags = VFIO_DEVICE_FLAGS_PCI;
451
452                 if (vdev->reset_works)
453                         info.flags |= VFIO_DEVICE_FLAGS_RESET;
454
455                 info.num_regions = VFIO_PCI_NUM_REGIONS;
456                 info.num_irqs = VFIO_PCI_NUM_IRQS;
457
458                 return copy_to_user((void __user *)arg, &info, minsz) ?
459                         -EFAULT : 0;
460
461         } else if (cmd == VFIO_DEVICE_GET_REGION_INFO) {
462                 struct pci_dev *pdev = vdev->pdev;
463                 struct vfio_region_info info;
464
465                 minsz = offsetofend(struct vfio_region_info, offset);
466
467                 if (copy_from_user(&info, (void __user *)arg, minsz))
468                         return -EFAULT;
469
470                 if (info.argsz < minsz)
471                         return -EINVAL;
472
473                 switch (info.index) {
474                 case VFIO_PCI_CONFIG_REGION_INDEX:
475                         info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
476                         info.size = pdev->cfg_size;
477                         info.flags = VFIO_REGION_INFO_FLAG_READ |
478                                      VFIO_REGION_INFO_FLAG_WRITE;
479                         break;
480                 case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
481                         info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
482                         info.size = pci_resource_len(pdev, info.index);
483                         if (!info.size) {
484                                 info.flags = 0;
485                                 break;
486                         }
487
488                         info.flags = VFIO_REGION_INFO_FLAG_READ |
489                                      VFIO_REGION_INFO_FLAG_WRITE;
490                         if (IS_ENABLED(CONFIG_VFIO_PCI_MMAP) &&
491                             pci_resource_flags(pdev, info.index) &
492                             IORESOURCE_MEM && info.size >= PAGE_SIZE)
493                                 info.flags |= VFIO_REGION_INFO_FLAG_MMAP;
494                         break;
495                 case VFIO_PCI_ROM_REGION_INDEX:
496                 {
497                         void __iomem *io;
498                         size_t size;
499                         u16 orig_cmd;
500
501                         info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
502                         info.flags = 0;
503
504                         /* Report the BAR size, not the ROM size */
505                         info.size = pci_resource_len(pdev, info.index);
506                         if (!info.size)
507                                 break;
508
509                         /*
510                          * Is it really there?  Enable memory decode for
511                          * implicit access in pci_map_rom().
512                          */
513                         pci_read_config_word(pdev, PCI_COMMAND, &orig_cmd);
514                         pci_write_config_word(pdev, PCI_COMMAND,
515                                               orig_cmd | PCI_COMMAND_MEMORY);
516
517                         io = pci_map_rom(pdev, &size);
518                         if (io) {
519                                 info.flags = VFIO_REGION_INFO_FLAG_READ;
520                                 pci_unmap_rom(pdev, io);
521                         } else {
522                                 info.size = 0;
523                         }
524
525                         pci_write_config_word(pdev, PCI_COMMAND, orig_cmd);
526                         break;
527                 }
528                 case VFIO_PCI_VGA_REGION_INDEX:
529                         if (!vdev->has_vga)
530                                 return -EINVAL;
531
532                         info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index);
533                         info.size = 0xc0000;
534                         info.flags = VFIO_REGION_INFO_FLAG_READ |
535                                      VFIO_REGION_INFO_FLAG_WRITE;
536
537                         break;
538                 default:
539                         return -EINVAL;
540                 }
541
542                 return copy_to_user((void __user *)arg, &info, minsz) ?
543                         -EFAULT : 0;
544
545         } else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) {
546                 struct vfio_irq_info info;
547
548                 minsz = offsetofend(struct vfio_irq_info, count);
549
550                 if (copy_from_user(&info, (void __user *)arg, minsz))
551                         return -EFAULT;
552
553                 if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS)
554                         return -EINVAL;
555
556                 switch (info.index) {
557                 case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX:
558                 case VFIO_PCI_REQ_IRQ_INDEX:
559                         break;
560                 case VFIO_PCI_ERR_IRQ_INDEX:
561                         if (pci_is_pcie(vdev->pdev))
562                                 break;
563                 /* pass thru to return error */
564                 default:
565                         return -EINVAL;
566                 }
567
568                 info.flags = VFIO_IRQ_INFO_EVENTFD;
569
570                 info.count = vfio_pci_get_irq_count(vdev, info.index);
571
572                 if (info.index == VFIO_PCI_INTX_IRQ_INDEX)
573                         info.flags |= (VFIO_IRQ_INFO_MASKABLE |
574                                        VFIO_IRQ_INFO_AUTOMASKED);
575                 else
576                         info.flags |= VFIO_IRQ_INFO_NORESIZE;
577
578                 return copy_to_user((void __user *)arg, &info, minsz) ?
579                         -EFAULT : 0;
580
581         } else if (cmd == VFIO_DEVICE_SET_IRQS) {
582                 struct vfio_irq_set hdr;
583                 size_t size;
584                 u8 *data = NULL;
585                 int max, ret = 0;
586
587                 minsz = offsetofend(struct vfio_irq_set, count);
588
589                 if (copy_from_user(&hdr, (void __user *)arg, minsz))
590                         return -EFAULT;
591
592                 if (hdr.argsz < minsz || hdr.index >= VFIO_PCI_NUM_IRQS ||
593                     hdr.count >= (U32_MAX - hdr.start) ||
594                     hdr.flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK |
595                                   VFIO_IRQ_SET_ACTION_TYPE_MASK))
596                         return -EINVAL;
597
598                 max = vfio_pci_get_irq_count(vdev, hdr.index);
599                 if (hdr.start >= max || hdr.start + hdr.count > max)
600                         return -EINVAL;
601
602                 switch (hdr.flags & VFIO_IRQ_SET_DATA_TYPE_MASK) {
603                 case VFIO_IRQ_SET_DATA_NONE:
604                         size = 0;
605                         break;
606                 case VFIO_IRQ_SET_DATA_BOOL:
607                         size = sizeof(uint8_t);
608                         break;
609                 case VFIO_IRQ_SET_DATA_EVENTFD:
610                         size = sizeof(int32_t);
611                         break;
612                 default:
613                         return -EINVAL;
614                 }
615
616                 if (size) {
617                         if (hdr.argsz - minsz < hdr.count * size)
618                                 return -EINVAL;
619
620                         data = memdup_user((void __user *)(arg + minsz),
621                                            hdr.count * size);
622                         if (IS_ERR(data))
623                                 return PTR_ERR(data);
624                 }
625
626                 mutex_lock(&vdev->igate);
627
628                 ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index,
629                                               hdr.start, hdr.count, data);
630
631                 mutex_unlock(&vdev->igate);
632                 kfree(data);
633
634                 return ret;
635
636         } else if (cmd == VFIO_DEVICE_RESET) {
637                 return vdev->reset_works ?
638                         pci_try_reset_function(vdev->pdev) : -EINVAL;
639
640         } else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) {
641                 struct vfio_pci_hot_reset_info hdr;
642                 struct vfio_pci_fill_info fill = { 0 };
643                 struct vfio_pci_dependent_device *devices = NULL;
644                 bool slot = false;
645                 int ret = 0;
646
647                 minsz = offsetofend(struct vfio_pci_hot_reset_info, count);
648
649                 if (copy_from_user(&hdr, (void __user *)arg, minsz))
650                         return -EFAULT;
651
652                 if (hdr.argsz < minsz)
653                         return -EINVAL;
654
655                 hdr.flags = 0;
656
657                 /* Can we do a slot or bus reset or neither? */
658                 if (!pci_probe_reset_slot(vdev->pdev->slot))
659                         slot = true;
660                 else if (pci_probe_reset_bus(vdev->pdev->bus))
661                         return -ENODEV;
662
663                 /* How many devices are affected? */
664                 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
665                                                     vfio_pci_count_devs,
666                                                     &fill.max, slot);
667                 if (ret)
668                         return ret;
669
670                 WARN_ON(!fill.max); /* Should always be at least one */
671
672                 /*
673                  * If there's enough space, fill it now, otherwise return
674                  * -ENOSPC and the number of devices affected.
675                  */
676                 if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) {
677                         ret = -ENOSPC;
678                         hdr.count = fill.max;
679                         goto reset_info_exit;
680                 }
681
682                 devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL);
683                 if (!devices)
684                         return -ENOMEM;
685
686                 fill.devices = devices;
687
688                 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
689                                                     vfio_pci_fill_devs,
690                                                     &fill, slot);
691
692                 /*
693                  * If a device was removed between counting and filling,
694                  * we may come up short of fill.max.  If a device was
695                  * added, we'll have a return of -EAGAIN above.
696                  */
697                 if (!ret)
698                         hdr.count = fill.cur;
699
700 reset_info_exit:
701                 if (copy_to_user((void __user *)arg, &hdr, minsz))
702                         ret = -EFAULT;
703
704                 if (!ret) {
705                         if (copy_to_user((void __user *)(arg + minsz), devices,
706                                          hdr.count * sizeof(*devices)))
707                                 ret = -EFAULT;
708                 }
709
710                 kfree(devices);
711                 return ret;
712
713         } else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) {
714                 struct vfio_pci_hot_reset hdr;
715                 int32_t *group_fds;
716                 struct vfio_pci_group_entry *groups;
717                 struct vfio_pci_group_info info;
718                 bool slot = false;
719                 int i, count = 0, ret = 0;
720
721                 minsz = offsetofend(struct vfio_pci_hot_reset, count);
722
723                 if (copy_from_user(&hdr, (void __user *)arg, minsz))
724                         return -EFAULT;
725
726                 if (hdr.argsz < minsz || hdr.flags)
727                         return -EINVAL;
728
729                 /* Can we do a slot or bus reset or neither? */
730                 if (!pci_probe_reset_slot(vdev->pdev->slot))
731                         slot = true;
732                 else if (pci_probe_reset_bus(vdev->pdev->bus))
733                         return -ENODEV;
734
735                 /*
736                  * We can't let userspace give us an arbitrarily large
737                  * buffer to copy, so verify how many we think there
738                  * could be.  Note groups can have multiple devices so
739                  * one group per device is the max.
740                  */
741                 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
742                                                     vfio_pci_count_devs,
743                                                     &count, slot);
744                 if (ret)
745                         return ret;
746
747                 /* Somewhere between 1 and count is OK */
748                 if (!hdr.count || hdr.count > count)
749                         return -EINVAL;
750
751                 group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL);
752                 groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL);
753                 if (!group_fds || !groups) {
754                         kfree(group_fds);
755                         kfree(groups);
756                         return -ENOMEM;
757                 }
758
759                 if (copy_from_user(group_fds, (void __user *)(arg + minsz),
760                                    hdr.count * sizeof(*group_fds))) {
761                         kfree(group_fds);
762                         kfree(groups);
763                         return -EFAULT;
764                 }
765
766                 /*
767                  * For each group_fd, get the group through the vfio external
768                  * user interface and store the group and iommu ID.  This
769                  * ensures the group is held across the reset.
770                  */
771                 for (i = 0; i < hdr.count; i++) {
772                         struct vfio_group *group;
773                         struct fd f = fdget(group_fds[i]);
774                         if (!f.file) {
775                                 ret = -EBADF;
776                                 break;
777                         }
778
779                         group = vfio_group_get_external_user(f.file);
780                         fdput(f);
781                         if (IS_ERR(group)) {
782                                 ret = PTR_ERR(group);
783                                 break;
784                         }
785
786                         groups[i].group = group;
787                         groups[i].id = vfio_external_user_iommu_id(group);
788                 }
789
790                 kfree(group_fds);
791
792                 /* release reference to groups on error */
793                 if (ret)
794                         goto hot_reset_release;
795
796                 info.count = hdr.count;
797                 info.groups = groups;
798
799                 /*
800                  * Test whether all the affected devices are contained
801                  * by the set of groups provided by the user.
802                  */
803                 ret = vfio_pci_for_each_slot_or_bus(vdev->pdev,
804                                                     vfio_pci_validate_devs,
805                                                     &info, slot);
806                 if (!ret)
807                         /* User has access, do the reset */
808                         ret = slot ? pci_try_reset_slot(vdev->pdev->slot) :
809                                      pci_try_reset_bus(vdev->pdev->bus);
810
811 hot_reset_release:
812                 for (i--; i >= 0; i--)
813                         vfio_group_put_external_user(groups[i].group);
814
815                 kfree(groups);
816                 return ret;
817         }
818
819         return -ENOTTY;
820 }
821
822 static ssize_t vfio_pci_rw(void *device_data, char __user *buf,
823                            size_t count, loff_t *ppos, bool iswrite)
824 {
825         unsigned int index = VFIO_PCI_OFFSET_TO_INDEX(*ppos);
826         struct vfio_pci_device *vdev = device_data;
827
828         if (index >= VFIO_PCI_NUM_REGIONS)
829                 return -EINVAL;
830
831         switch (index) {
832         case VFIO_PCI_CONFIG_REGION_INDEX:
833                 return vfio_pci_config_rw(vdev, buf, count, ppos, iswrite);
834
835         case VFIO_PCI_ROM_REGION_INDEX:
836                 if (iswrite)
837                         return -EINVAL;
838                 return vfio_pci_bar_rw(vdev, buf, count, ppos, false);
839
840         case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX:
841                 return vfio_pci_bar_rw(vdev, buf, count, ppos, iswrite);
842
843         case VFIO_PCI_VGA_REGION_INDEX:
844                 return vfio_pci_vga_rw(vdev, buf, count, ppos, iswrite);
845         }
846
847         return -EINVAL;
848 }
849
850 static ssize_t vfio_pci_read(void *device_data, char __user *buf,
851                              size_t count, loff_t *ppos)
852 {
853         if (!count)
854                 return 0;
855
856         return vfio_pci_rw(device_data, buf, count, ppos, false);
857 }
858
859 static ssize_t vfio_pci_write(void *device_data, const char __user *buf,
860                               size_t count, loff_t *ppos)
861 {
862         if (!count)
863                 return 0;
864
865         return vfio_pci_rw(device_data, (char __user *)buf, count, ppos, true);
866 }
867
868 static int vfio_pci_mmap(void *device_data, struct vm_area_struct *vma)
869 {
870         struct vfio_pci_device *vdev = device_data;
871         struct pci_dev *pdev = vdev->pdev;
872         unsigned int index;
873         u64 phys_len, req_len, pgoff, req_start;
874         int ret;
875
876         index = vma->vm_pgoff >> (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT);
877
878         if (vma->vm_end < vma->vm_start)
879                 return -EINVAL;
880         if ((vma->vm_flags & VM_SHARED) == 0)
881                 return -EINVAL;
882         if (index >= VFIO_PCI_ROM_REGION_INDEX)
883                 return -EINVAL;
884         if (!(pci_resource_flags(pdev, index) & IORESOURCE_MEM))
885                 return -EINVAL;
886
887         phys_len = pci_resource_len(pdev, index);
888         req_len = vma->vm_end - vma->vm_start;
889         pgoff = vma->vm_pgoff &
890                 ((1U << (VFIO_PCI_OFFSET_SHIFT - PAGE_SHIFT)) - 1);
891         req_start = pgoff << PAGE_SHIFT;
892
893         if (phys_len < PAGE_SIZE || req_start + req_len > phys_len)
894                 return -EINVAL;
895
896         if (index == vdev->msix_bar) {
897                 /*
898                  * Disallow mmaps overlapping the MSI-X table; users don't
899                  * get to touch this directly.  We could find somewhere
900                  * else to map the overlap, but page granularity is only
901                  * a recommendation, not a requirement, so the user needs
902                  * to know which bits are real.  Requiring them to mmap
903                  * around the table makes that clear.
904                  */
905
906                 /* If neither entirely above nor below, then it overlaps */
907                 if (!(req_start >= vdev->msix_offset + vdev->msix_size ||
908                       req_start + req_len <= vdev->msix_offset))
909                         return -EINVAL;
910         }
911
912         /*
913          * Even though we don't make use of the barmap for the mmap,
914          * we need to request the region and the barmap tracks that.
915          */
916         if (!vdev->barmap[index]) {
917                 ret = pci_request_selected_regions(pdev,
918                                                    1 << index, "vfio-pci");
919                 if (ret)
920                         return ret;
921
922                 vdev->barmap[index] = pci_iomap(pdev, index, 0);
923                 if (!vdev->barmap[index]) {
924                         pci_release_selected_regions(pdev, 1 << index);
925                         return -ENOMEM;
926                 }
927         }
928
929         vma->vm_private_data = vdev;
930         vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
931         vma->vm_pgoff = (pci_resource_start(pdev, index) >> PAGE_SHIFT) + pgoff;
932
933         return remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
934                                req_len, vma->vm_page_prot);
935 }
936
937 static void vfio_pci_request(void *device_data, unsigned int count)
938 {
939         struct vfio_pci_device *vdev = device_data;
940
941         mutex_lock(&vdev->igate);
942
943         if (vdev->req_trigger) {
944                 if (!(count % 10))
945                         dev_notice_ratelimited(&vdev->pdev->dev,
946                                 "Relaying device request to user (#%u)\n",
947                                 count);
948                 eventfd_signal(vdev->req_trigger, 1);
949         } else if (count == 0) {
950                 dev_warn(&vdev->pdev->dev,
951                         "No device request channel registered, blocked until released by user\n");
952         }
953
954         mutex_unlock(&vdev->igate);
955 }
956
957 static const struct vfio_device_ops vfio_pci_ops = {
958         .name           = "vfio-pci",
959         .open           = vfio_pci_open,
960         .release        = vfio_pci_release,
961         .ioctl          = vfio_pci_ioctl,
962         .read           = vfio_pci_read,
963         .write          = vfio_pci_write,
964         .mmap           = vfio_pci_mmap,
965         .request        = vfio_pci_request,
966 };
967
968 static int vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
969 {
970         struct vfio_pci_device *vdev;
971         struct iommu_group *group;
972         int ret;
973
974         if (pdev->hdr_type != PCI_HEADER_TYPE_NORMAL)
975                 return -EINVAL;
976
977         group = iommu_group_get(&pdev->dev);
978         if (!group)
979                 return -EINVAL;
980
981         vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
982         if (!vdev) {
983                 iommu_group_put(group);
984                 return -ENOMEM;
985         }
986
987         vdev->pdev = pdev;
988         vdev->irq_type = VFIO_PCI_NUM_IRQS;
989         mutex_init(&vdev->igate);
990         spin_lock_init(&vdev->irqlock);
991
992         ret = vfio_add_group_dev(&pdev->dev, &vfio_pci_ops, vdev);
993         if (ret) {
994                 iommu_group_put(group);
995                 kfree(vdev);
996                 return ret;
997         }
998
999         if (vfio_pci_is_vga(pdev)) {
1000                 vga_client_register(pdev, vdev, NULL, vfio_pci_set_vga_decode);
1001                 vga_set_legacy_decoding(pdev,
1002                                         vfio_pci_set_vga_decode(vdev, false));
1003         }
1004
1005         if (!disable_idle_d3) {
1006                 /*
1007                  * pci-core sets the device power state to an unknown value at
1008                  * bootup and after being removed from a driver.  The only
1009                  * transition it allows from this unknown state is to D0, which
1010                  * typically happens when a driver calls pci_enable_device().
1011                  * We're not ready to enable the device yet, but we do want to
1012                  * be able to get to D3.  Therefore first do a D0 transition
1013                  * before going to D3.
1014                  */
1015                 pci_set_power_state(pdev, PCI_D0);
1016                 pci_set_power_state(pdev, PCI_D3hot);
1017         }
1018
1019         return ret;
1020 }
1021
1022 static void vfio_pci_remove(struct pci_dev *pdev)
1023 {
1024         struct vfio_pci_device *vdev;
1025
1026         vdev = vfio_del_group_dev(&pdev->dev);
1027         if (!vdev)
1028                 return;
1029
1030         iommu_group_put(pdev->dev.iommu_group);
1031         kfree(vdev);
1032
1033         if (vfio_pci_is_vga(pdev)) {
1034                 vga_client_register(pdev, NULL, NULL, NULL);
1035                 vga_set_legacy_decoding(pdev,
1036                                 VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM |
1037                                 VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM);
1038         }
1039
1040         if (!disable_idle_d3)
1041                 pci_set_power_state(pdev, PCI_D0);
1042 }
1043
1044 static pci_ers_result_t vfio_pci_aer_err_detected(struct pci_dev *pdev,
1045                                                   pci_channel_state_t state)
1046 {
1047         struct vfio_pci_device *vdev;
1048         struct vfio_device *device;
1049
1050         device = vfio_device_get_from_dev(&pdev->dev);
1051         if (device == NULL)
1052                 return PCI_ERS_RESULT_DISCONNECT;
1053
1054         vdev = vfio_device_data(device);
1055         if (vdev == NULL) {
1056                 vfio_device_put(device);
1057                 return PCI_ERS_RESULT_DISCONNECT;
1058         }
1059
1060         mutex_lock(&vdev->igate);
1061
1062         if (vdev->err_trigger)
1063                 eventfd_signal(vdev->err_trigger, 1);
1064
1065         mutex_unlock(&vdev->igate);
1066
1067         vfio_device_put(device);
1068
1069         return PCI_ERS_RESULT_CAN_RECOVER;
1070 }
1071
1072 static const struct pci_error_handlers vfio_err_handlers = {
1073         .error_detected = vfio_pci_aer_err_detected,
1074 };
1075
1076 static struct pci_driver vfio_pci_driver = {
1077         .name           = "vfio-pci",
1078         .id_table       = NULL, /* only dynamic ids */
1079         .probe          = vfio_pci_probe,
1080         .remove         = vfio_pci_remove,
1081         .err_handler    = &vfio_err_handlers,
1082 };
1083
1084 struct vfio_devices {
1085         struct vfio_device **devices;
1086         int cur_index;
1087         int max_index;
1088 };
1089
1090 static int vfio_pci_get_devs(struct pci_dev *pdev, void *data)
1091 {
1092         struct vfio_devices *devs = data;
1093         struct vfio_device *device;
1094
1095         if (devs->cur_index == devs->max_index)
1096                 return -ENOSPC;
1097
1098         device = vfio_device_get_from_dev(&pdev->dev);
1099         if (!device)
1100                 return -EINVAL;
1101
1102         if (pci_dev_driver(pdev) != &vfio_pci_driver) {
1103                 vfio_device_put(device);
1104                 return -EBUSY;
1105         }
1106
1107         devs->devices[devs->cur_index++] = device;
1108         return 0;
1109 }
1110
1111 /*
1112  * Attempt to do a bus/slot reset if there are devices affected by a reset for
1113  * this device that are needs_reset and all of the affected devices are unused
1114  * (!refcnt).  Callers are required to hold driver_lock when calling this to
1115  * prevent device opens and concurrent bus reset attempts.  We prevent device
1116  * unbinds by acquiring and holding a reference to the vfio_device.
1117  *
1118  * NB: vfio-core considers a group to be viable even if some devices are
1119  * bound to drivers like pci-stub or pcieport.  Here we require all devices
1120  * to be bound to vfio_pci since that's the only way we can be sure they
1121  * stay put.
1122  */
1123 static void vfio_pci_try_bus_reset(struct vfio_pci_device *vdev)
1124 {
1125         struct vfio_devices devs = { .cur_index = 0 };
1126         int i = 0, ret = -EINVAL;
1127         bool needs_reset = false, slot = false;
1128         struct vfio_pci_device *tmp;
1129
1130         if (!pci_probe_reset_slot(vdev->pdev->slot))
1131                 slot = true;
1132         else if (pci_probe_reset_bus(vdev->pdev->bus))
1133                 return;
1134
1135         if (vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs,
1136                                           &i, slot) || !i)
1137                 return;
1138
1139         devs.max_index = i;
1140         devs.devices = kcalloc(i, sizeof(struct vfio_device *), GFP_KERNEL);
1141         if (!devs.devices)
1142                 return;
1143
1144         if (vfio_pci_for_each_slot_or_bus(vdev->pdev,
1145                                           vfio_pci_get_devs, &devs, slot))
1146                 goto put_devs;
1147
1148         for (i = 0; i < devs.cur_index; i++) {
1149                 tmp = vfio_device_data(devs.devices[i]);
1150                 if (tmp->needs_reset)
1151                         needs_reset = true;
1152                 if (tmp->refcnt)
1153                         goto put_devs;
1154         }
1155
1156         if (needs_reset)
1157                 ret = slot ? pci_try_reset_slot(vdev->pdev->slot) :
1158                              pci_try_reset_bus(vdev->pdev->bus);
1159
1160 put_devs:
1161         for (i = 0; i < devs.cur_index; i++) {
1162                 tmp = vfio_device_data(devs.devices[i]);
1163                 if (!ret)
1164                         tmp->needs_reset = false;
1165
1166                 if (!tmp->refcnt && !disable_idle_d3)
1167                         pci_set_power_state(tmp->pdev, PCI_D3hot);
1168
1169                 vfio_device_put(devs.devices[i]);
1170         }
1171
1172         kfree(devs.devices);
1173 }
1174
1175 static void __exit vfio_pci_cleanup(void)
1176 {
1177         pci_unregister_driver(&vfio_pci_driver);
1178         vfio_pci_uninit_perm_bits();
1179 }
1180
1181 static void __init vfio_pci_fill_ids(void)
1182 {
1183         char *p, *id;
1184         int rc;
1185
1186         /* no ids passed actually */
1187         if (ids[0] == '\0')
1188                 return;
1189
1190         /* add ids specified in the module parameter */
1191         p = ids;
1192         while ((id = strsep(&p, ","))) {
1193                 unsigned int vendor, device, subvendor = PCI_ANY_ID,
1194                         subdevice = PCI_ANY_ID, class = 0, class_mask = 0;
1195                 int fields;
1196
1197                 if (!strlen(id))
1198                         continue;
1199
1200                 fields = sscanf(id, "%x:%x:%x:%x:%x:%x",
1201                                 &vendor, &device, &subvendor, &subdevice,
1202                                 &class, &class_mask);
1203
1204                 if (fields < 2) {
1205                         pr_warn("invalid id string \"%s\"\n", id);
1206                         continue;
1207                 }
1208
1209                 rc = pci_add_dynid(&vfio_pci_driver, vendor, device,
1210                                    subvendor, subdevice, class, class_mask, 0);
1211                 if (rc)
1212                         pr_warn("failed to add dynamic id [%04x:%04x[%04x:%04x]] class %#08x/%08x (%d)\n",
1213                                 vendor, device, subvendor, subdevice,
1214                                 class, class_mask, rc);
1215                 else
1216                         pr_info("add [%04x:%04x[%04x:%04x]] class %#08x/%08x\n",
1217                                 vendor, device, subvendor, subdevice,
1218                                 class, class_mask);
1219         }
1220 }
1221
1222 static int __init vfio_pci_init(void)
1223 {
1224         int ret;
1225
1226         /* Allocate shared config space permision data used by all devices */
1227         ret = vfio_pci_init_perm_bits();
1228         if (ret)
1229                 return ret;
1230
1231         /* Register and scan for devices */
1232         ret = pci_register_driver(&vfio_pci_driver);
1233         if (ret)
1234                 goto out_driver;
1235
1236         vfio_pci_fill_ids();
1237
1238         return 0;
1239
1240 out_driver:
1241         vfio_pci_uninit_perm_bits();
1242         return ret;
1243 }
1244
1245 module_init(vfio_pci_init);
1246 module_exit(vfio_pci_cleanup);
1247
1248 MODULE_VERSION(DRIVER_VERSION);
1249 MODULE_LICENSE("GPL v2");
1250 MODULE_AUTHOR(DRIVER_AUTHOR);
1251 MODULE_DESCRIPTION(DRIVER_DESC);