vfio: VFIO Driver core framework
Subsystems (5)
Quoted 11 lines · Scott Wood
Documentation/vfio.txt
Quoted 5 lines · Alex Williamson
Documentation/vfio.txt new file +5
-0+Many modern system now provide DMA and interrupt remapping facilities +to help ensure I/O devices behave within the boundaries they've been +allotted. This includes x86 hardware with AMD-Vi and Intel VT-d as +well as POWER systems with Partitionable Endpoints (PEs) and even +embedded powerpc systems (technology name unknown).Maybe replace "(technology name unknown)" with "(such as Freescale chips with PAMU)" or similar?
Or just leave out the parenthetical.
I was hoping that comment would lead to an answer. Thanks for the info ;)
Quoted 6 lines
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+As documented in linux/vfio.h, several ioctls are provided on the +group chardev: + +#define VFIO_GROUP_GET_FLAGS _IOR(';', 100, __u64) + #define VFIO_GROUP_FLAGS_VIABLE (1 << 0) + #define VFIO_GROUP_FLAGS_MM_LOCKED (1 << 1)
Quoted 8 lines
Documentation/vfio.txt line 72
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+#define VFIO_GROUP_MERGE _IOW(';', 101, int) +#define VFIO_GROUP_UNMERGE _IOW(';', 102, int) +#define VFIO_GROUP_GET_IOMMU_FD _IO(';', 103) +#define VFIO_GROUP_GET_DEVICE_FD _IOW(';', 104, char *)This suggests the argument to
VFIO_GROUP_GET_DEVICE_FDis a pointer to a pointer to char rather than a pointer to an array of char (just as e.g.VFIO_GROUP_MERGEtakes a pointer to an int, not just an int).
I believe I was following the UI_SET_PHYS ioctl as an example, which is defined as a char *. I'll change to char and verify.
Quoted 10 lines
Documentation/vfio.txt line 110
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+The IOMMU file descriptor provides this set of ioctls: + +#define VFIO_IOMMU_GET_FLAGS _IOR(';', 105, __u64) + #define VFIO_IOMMU_FLAGS_MAP_ANY (1 << 0) +#define VFIO_IOMMU_MAP_DMA _IOWR(';', 106, struct vfio_dma_map) +#define VFIO_IOMMU_UNMAP_DMA _IOWR(';', 107, struct vfio_dma_map)What is the implication if
VFIO_IOMMU_FLAGS_MAP_ANYis clear? Is such an implementation supposed to add a new flag that describes its restrictions?
If MAP_ANY is clear then I would expect a new flag is set defining a new mapping paradigm, probably with an ioctl to describe the restrictions/parameters. MAP_ANY effectively means there are no restrictions.
Quoted 2 lines
Can we get a way to turn DMA access off and on, short of unmapping everything, and then mapping it again?
iommu_ops doesn't support such an interface, so no, not currently.
Quoted 9 lines
Quoted 9 lines
Documentation/vfio.txt new file +9
-0+The GET_FLAGS ioctl returns basic information about the IOMMU domain. +We currently only support IOMMU domains that are able to map any +virtual address to any IOVA. This is indicated by the MAP_ANY flag. + +The (UN)MAP_DMA commands make use of struct vfio_dma_map for mapping +and unmapping IOVAs to process virtual addresses: + +struct vfio_dma_map { + __u64 len; /* length of structure */
Quoted 8 lines
Documentation/vfio.txt line 126
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+ __u64 vaddr; /* process virtual addr */ + __u64 dmaaddr; /* desired and/or returned dma address */ + __u64 size; /* size in bytes */ + __u64 flags; +#define VFIO_DMA_MAP_FLAG_WRITE (1 << 0) /* req writeable DMA mem */ +};What are the semantics of "desired and/or returned dma address"?
I believe the original intention was that a user could leave dmaaddr clear and let the iommu layer provide an iova address. The iommu api has since evolved and that mapping scheme really isn't present anymore. We'll currently fail if we can map the requested address. I'll update the docs to make that be the definition.
Quoted 3 lines
Are we always supposed to provide a desired address, but it may be different on return? Or are there cases where we want to say "give me whatever you want" or "give me this or fail"?
Exactly, that's what it used to be, but we don't really implement that any more.
Quoted 1 line
How much of this needs to be filled out for unmap?
dmaaddr & size, will update docs.
Quoted 3 lines
Note that the "length of structure" approach means that ioctl numbers will change whenever this grows -- perhaps we should avoid encoding the struct size into these ioctls?
How so? What's described here is effectively the base size. If we later add feature foo requiring additional fields, we set a flag, change the size, and tack those fields onto the end. The kernel side should balk if the size doesn't match what it expects from the flags it understands (which I think I probably need to be more strict about).
Quoted 11 lines
Documentation/vfio.txt line 165
Quoted 11 lines
Documentation/vfio.txt new file +11
-0+struct vfio_region_info { + __u32 len; /* length of structure */ + __u32 index; /* region number */ + __u64 size; /* size in bytes of region */ + __u64 offset; /* start offset of region */ + __u64 flags; +#define VFIO_REGION_INFO_FLAG_MMAP (1 << 0) +#define VFIO_REGION_INFO_FLAG_RO (1 << 1) +#define VFIO_REGION_INFO_FLAG_PHYS_VALID (1 << 2) + __u64 phys; /* physical address of region */ +};
In light of the above, this struct should not include phys. In fact, I should probably remove the PHYS_VALID flag as well until we have a bus driver implementation that actually makes use of it.
Quoted 15 lines
Quoted 15 lines
Documentation/vfio.txt new file +15
-0+ +#define VFIO_DEVICE_GET_REGION_INFO _IOWR(';', 110, struct vfio_region_info) + +The offset indicates the offset into the device file descriptor which +accesses the given range (for read/write/mmap/seek). Flags indicate the +available access types and validity of optional fields. For instance +the phys field may only be valid for certain devices types. + +Interrupts are described using a similar interface. GET_NUM_IRQS +reports the number or IRQ indexes for the device. + +#define VFIO_DEVICE_GET_NUM_IRQS _IOR(';', 111, int) + +struct vfio_irq_info { + __u32 len; /* length of structure */
Quoted 8 lines
Documentation/vfio.txt line 184
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+ __u32 index; /* IRQ number */ + __u32 count; /* number of individual IRQs */ + __u64 flags; +#define VFIO_IRQ_INFO_FLAG_LEVEL (1 << 0)Make sure flags is 64-bit aligned -- some 32-bit ABIs, such as x86, will not do this, causing problems if the kernel is 64-bit and thus assumes a different layout.
Shoot, I'll push flags up above count to get it aligned.
Quoted 14 lines
Quoted 14 lines
Documentation/vfio.txt new file +14
-0+Information about each index can be retrieved using the GET_IRQ_INFO +ioctl, used much like GET_REGION_INFO. + +#define VFIO_DEVICE_GET_IRQ_INFO _IOWR(';', 112, struct vfio_irq_info) + +Individual indexes can describe single or sets of IRQs. This provides the +flexibility to describe PCI INTx, MSI, and MSI-X using a single interface. + +All VFIO interrupts are signaled to userspace via eventfds. Integer arrays, +as shown below, are used to pass the IRQ info index, the number of eventfds, +and each eventfd to be signaled. Using a count of 0 disables the interrupt. + +/* Set IRQ eventfds, arg[0] = index, arg[1] = count, arg[2-n] = eventfds */ +#define VFIO_DEVICE_SET_IRQ_EVENTFDS _IOW(';', 113, int)
Quoted 8 lines
Documentation/vfio.txt
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+ +When a level triggered interrupt is signaled, the interrupt is masked +on the host. This prevents an unresponsive userspace driver from +continuing to interrupt the host system.It's usually necessary even in the case of responsive userspace, just to get to the point where userspace can execute (ignoring cases where userspace runs on one core while the interrupt storms another).
Right, I'll try to clarify.
Quoted 4 lines
For edge interrupts, will me mask if an interrupt comes in and the previous interrupt hasn't been read out yet (and then unmask when the last interrupt gets read out), to isolate us from a rapidly firing interrupt source that userspace can't keep up with?
We don't do that currently and I haven't seen a need to. Seems like there'd be no API change in doing that if we want at some point.
Quoted 6 lines
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+Device tree devices also invlude ioctls for further defining the +device tree properties of the device: + +struct vfio_dtpath { + __u32 len; /* length of structure */ + __u32 index;
Quoted 8 lines
Documentation/vfio.txt line 235
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+ __u64 flags; +#define VFIO_DTPATH_FLAGS_REGION (1 << 0) +#define VFIO_DTPATH_FLAGS_IRQ (1 << 1) + char *path; +}; +#define VFIO_DEVICE_GET_DTPATH _IOWR(';', 117, struct vfio_dtpath)Where is length of buffer (and description of associated semantics)?
I think I should probably take the same approach as the phys field above, leave it to the dt bus driver to add these ioctls and fields as I'm almost certain to get it wrong trying to predict what it's going to need. Likewise, VFIO_DEVICE_FLAGS_PCI should be defined as part of the pci bus driver patch, even though it doesn't need any extra ioctls/fields.
Quoted 4 lines
Review
Quoted 2 lines
(quoted diff) +2
-0+struct vfio_device_ops { + bool (*match)(struct device *, char *);const char *?
will fix
Quoted 11 lines
Documentation/vfio.txt line 276
Quoted 9 lines
Documentation/vfio.txt new file +9
-0+ int (*get)(void *); + void (*put)(void *); + ssize_t (*read)(void *, char __user *, + size_t, loff_t *); + ssize_t (*write)(void *, const char __user *, + size_t, loff_t *); + long (*ioctl)(void *, unsigned int, unsigned long); + int (*mmap)(void *, struct vm_area_struct *); +};When defining an API, please do not omit parameter names.
ok
Quoted 4 lines
Should specify what the driver is supposed to do with get/put -- I guess not try to unbind when the count is nonzero? Races could still lead the unbinder to be blocked, but I guess it lets the driver know when it's likely to succeed.
Right, for the pci bus driver, it's mainly for reference counting, including the module_get to prevent vfio-pci from being unloaded. On the first get for a device, we also do a pci_enable() and pci_disable() on last put. I'll try to clarify in the docs.
Quoted 12 lines
Quoted 12 lines
drivers/vfio/Kconfig new file +6
-0@@ -0,0 +1,8 @@ +menuconfig VFIO + tristate "VFIO Non-Privileged userspace driver framework" + depends on IOMMU_API + help + VFIO provides a framework for secure userspace device drivers. + See Documentation/vfio.txt for more details.
Quoted 8 lines
drivers/vfio/Kconfig line 8
Quoted 2 lines
drivers/vfio/Kconfig new file +2
-0+ + If you don't know what to do here, say N.Can we limit the
IOMMU_APIdependency to the IOMMU parts of VFIO? It would still be useful for devices which don't do DMA, or where we accept the lack of protection/translation (e.g. we have a customer that wants to do KVM device assignment on one of our lower-end chips that lacks an IOMMU).
Ugh. I'm not really onboard with it given that we're trying to sell vfio as a secure user space driver interface with iommu-based protection. That said, vifo_iommu.c is already it's own file, with the thought that other platforms might need to manage the iommu differently. Theoretically the IOMMU_API requirement could be tied specifically to vfio_iommu and another iommu backend added.
Quoted 9 lines
drivers/vfio/Kconfig
Quoted 7 lines
drivers/vfio/Kconfig new file +7
-0+struct dma_map_page { + struct list_head list; + dma_addr_t daddr; + unsigned long vaddr; + int npage; + int rdwr; +};npage should be long.
Seems like I went back and forth on that a couple times, I'll see if I can remember why I landed on int or change it. Practically, int is "big enough", but that's not a good answer.
Quoted 2 lines
What is "rdwr"? non-zero for write? non-zero for read? :-)
is_writewould be a better name.
Others commented on this too, I'll switch to a bool rename it so it's obvious that it means write access enabled.
Quoted 19 lines
Quoted 19 lines
drivers/vfio/Kconfig new file +18
-0+ for (i = 0; i < npage; i++, iova += PAGE_SIZE, vaddr += PAGE_SIZE) { + unsigned long pfn = 0; + + ret = vaddr_get_pfn(vaddr, rdwr, &pfn); + if (ret) { + __vfio_dma_unmap(iommu, start, i, rdwr); + return ret; + } + + /* Only add actual locked pages to accounting */ + if (!is_invalid_reserved_pfn(pfn)) + locked++; + + ret = iommu_map(iommu->domain, iova, + (phys_addr_t)pfn << PAGE_SHIFT, 0, prot); + if (ret) { + /* Back out mappings on error */ + put_pfn(pfn, rdwr);
Quoted 8 lines
drivers/vfio/Kconfig
Quoted 4 lines
drivers/vfio/Kconfig new file +4
-0+ __vfio_dma_unmap(iommu, start, i, rdwr); + return ret; + } + }There's no way to hand this stuff to the IOMMU driver in chunks larger than a page? That's going to be a problem for our IOMMU, which wants to deal with large windows.
There is, this is just a simple implementation that maps individual pages. We "just" need to determine physically contiguous chunks and mlock them instead of using get_user_pages. The current implementation is much like how KVM maps iommu pages, but there shouldn't be a user API change to try to use larger chinks. We want this for IOMMU large page support too.
Quoted 4 lines
Quoted 4 lines
drivers/vfio/Kconfig new file +4
-0+ vfio_lock_acct(locked); + return 0; +} +
Quoted 8 lines
drivers/vfio/Kconfig
Quoted 5 lines
drivers/vfio/Kconfig new file +5
-0+static inline int ranges_overlap(unsigned long start1, size_t size1, + unsigned long start2, size_t size2) +{ + return !(start1 + size1 <= start2 || start2 + size2 <= start1); +}You pass DMA addresses to this, so use
dma_addr_t. unsigned long is not always large enough.
ok
Quoted 2 lines
What if one of the ranges wraps around (including the legitimate possibility of start + size == 0)?
Looks like a bug.
Quoted 7 lines
drivers/vfio/Kconfig
Quoted 5 lines
drivers/vfio/Kconfig new file +5
-0+static long vfio_iommu_unl_ioctl(struct file *filep, + unsigned int cmd, unsigned long arg) +{ + struct vfio_iommu *iommu = filep->private_data; + int ret = -ENOSYS;
-ENOIOCTLCMDor-ENOTTY?
ok
Quoted 10 lines
drivers/vfio/Kconfig
Quoted 8 lines
drivers/vfio/Kconfig new file +8
-0+ + if (cmd == VFIO_IOMMU_GET_FLAGS) { + u64 flags = VFIO_IOMMU_FLAGS_MAP_ANY; + + ret = put_user(flags, (u64 __user *)arg); + + } else if (cmd == VFIO_IOMMU_MAP_DMA) { + struct vfio_dma_map dm;Whitespace.
yep, will fix
Quoted 1 line
Any reason not to use a switch?
Personal preference. It got ugly using a switch in vfio_main, trying to keep variable scope to the case, followed suit here for consistency.
Quoted 6 lines
Quoted 2 lines
drivers/vfio/Kconfig new file +2
-0+/* Return true if any devices within a group are opened */ +static bool __vfio_group_devs_inuse(struct vfio_group *group)[snip]
Quoted 1 line
+static bool
__vfio_iommu_groups_inuse(struct vfio_iommu *iommu)[snip]
Quoted 1 line
+static bool
__vfio_iommu_inuse(struct vfio_iommu *iommu)
Quoted 8 lines
[snip]
drivers/vfio/Kconfig
Quoted 2 lines
drivers/vfio/Kconfig new file +2
-0+static void __vfio_group_set_iommu(struct vfio_group *group, + struct vfio_iommu *iommu)...and so on.
Why all the leading underscores? Doesn't look like you're trying to distinguish between this and a more public version with the same name.
__ implies it should be called under vfio.lock.
Quoted 27 lines
Quoted 27 lines
drivers/vfio/Kconfig new file +27
-0+/* Get a new device file descriptor. This will open the iommu, setting + * the current->mm ownership if it's not already set. It's difficult to + * specify the requirements for matching a user supplied buffer to a + * device, so we use a vfio driver callback to test for a match. For + * PCI, dev_name(dev) is unique, but other drivers may require including + * a parent device string. */ +static int vfio_group_get_device_fd(struct vfio_group *group, char *buf) +{ + struct vfio_iommu *iommu = group->iommu; + struct list_head *gpos; + int ret = -ENODEV; + + mutex_lock(&vfio.lock); + + if (!iommu->domain) { + ret = __vfio_open_iommu(iommu); + if (ret) + goto out; + } + + list_for_each(gpos, &iommu->group_list) { + struct list_head *dpos; + + group = list_entry(gpos, struct vfio_group, iommu_next); + + list_for_each(dpos, &group->device_list) { + struct vfio_device *device;
Quoted 8 lines
drivers/vfio/Kconfig
Quoted 5 lines
drivers/vfio/Kconfig new file +5
-0+ + device = list_entry(dpos, + struct vfio_device, device_next); + + if (device->ops->match(device->dev, buf)) {If there's a match, we're done with the loop -- might as well break out now rather than indent everything else.
Sure, even just changing the polarity and making this a continue would help the formatting below.
Quoted 9 lines
drivers/vfio/Kconfig
Quoted 6 lines
drivers/vfio/Kconfig new file +6
-0+ struct file *file; + + if (device->ops->get(device->device_data)) { + ret = -EFAULT; + goto out; + }Why does a failure of
get()result in-EFAULT?-EFAULTis for bad user addresses.
I'll just return what get() returns.
Quoted 13 lines
Quoted 13 lines
drivers/vfio/Kconfig new file +13
-0+ + /* We can't use anon_inode_getfd(), like above + * because we need to modify the f_mode flags + * directly to allow more than just ioctls */ + ret = get_unused_fd(); + if (ret < 0) { + device->ops->put(device->device_data); + goto out; + } + + file = anon_inode_getfile("[vfio-device]", + &vfio_device_fops, + device, O_RDWR);
Quoted 8 lines
drivers/vfio/Kconfig
Quoted 6 lines
drivers/vfio/Kconfig new file +6
-0+ if (IS_ERR(file)) { + put_unused_fd(ret); + ret = PTR_ERR(file); + device->ops->put(device->device_data); + goto out; + }Maybe cleaner with goto-based error management?
I didn't see enough duplication creeping in to try that here.
Quoted 19 lines
Quoted 19 lines
drivers/vfio/Kconfig new file +19
-0+/* Add a new device to the vfio framework with associated vfio driver + * callbacks. This is the entry point for vfio drivers to register devices. */ +int vfio_group_add_dev(struct device *dev, const struct vfio_device_ops *ops) +{ + struct list_head *pos; + struct vfio_group *group = NULL; + struct vfio_device *device = NULL; + unsigned int groupid; + int ret = 0; + bool new_group = false; + + if (!ops) + return -EINVAL; + + if (iommu_device_group(dev, &groupid)) + return -ENODEV; + + mutex_lock(&vfio.lock); +
Quoted 8 lines
drivers/vfio/Kconfig
Quoted 6 lines
drivers/vfio/Kconfig new file +6
-0+ list_for_each(pos, &vfio.group_list) { + group = list_entry(pos, struct vfio_group, group_next); + if (group->groupid == groupid) + break; + group = NULL; + }Factor this into
vfio_dev_to_group()(and likewise for other such lookups)?
Yeah, this ends up getting duplicated a few places.
Quoted 25 lines
Quoted 25 lines
drivers/vfio/Kconfig new file +25
-0+ if (!group) { + int minor; + + if (unlikely(idr_pre_get(&vfio.idr, GFP_KERNEL) == 0)) { + ret = -ENOMEM; + goto out; + } + + group = kzalloc(sizeof(*group), GFP_KERNEL); + if (!group) { + ret = -ENOMEM; + goto out; + } + + group->groupid = groupid; + INIT_LIST_HEAD(&group->device_list); + + ret = idr_get_new(&vfio.idr, group, &minor); + if (ret == 0 && minor > MINORMASK) { + idr_remove(&vfio.idr, minor); + kfree(group); + ret = -ENOSPC; + goto out; + } +
Quoted 8 lines
drivers/vfio/Kconfig
Quoted 6 lines
drivers/vfio/Kconfig new file +6
-0+ group->devt = MKDEV(MAJOR(vfio.devt), minor); + device_create(vfio.class, NULL, group->devt, + group, "%u", groupid); + + group->bus = dev->bus; + list_add(&group->group_next, &vfio.group_list);Factor out into
vfio_create_group()?
sounds good
Quoted 15 lines
drivers/vfio/Kconfig
Quoted 10 lines
drivers/vfio/Kconfig new file +10
-0+ new_group = true; + } else { + if (group->bus != dev->bus) { + printk(KERN_WARNING + "Error: IOMMU group ID conflict. Group ID %u " + "on both bus %s and %s\n", groupid, + group->bus->name, dev->bus->name); + ret = -EFAULT; + goto out; + }It took me a little while to figure out that this was comparing bus types, not actual bus instances (which would be an inappropriate restriction). :-P
Quoted 2 lines
Still, isn't it what we really care about that it's the same IOMMU domain? Couldn't different bus types share an
iommu_ops?
Nope, iommu_ops registration is now per bus_type. Also, Christian pointed out that groupid is really only guaranteed to be unique per bus_type so I've been updating groupid comparisons to compare the groupid, bus_type pair.
Quoted 1 line
And again,
-EFAULTisn't the right error.
Ok.
Thank you very much for the comments,
Alex
Quoted 29 lines · Alex Williamson
Quoted 19 lines · Scott Wood
Quoted 18 lines · Alex Williamson
drivers/vfio/vfio_iommu.c new file +18
-0+for (i =0 ; i < npage; i++, iova +=PAGE_SIZE , vaddr +=PAGE_SIZE ) { +unsigned long pfn =0 ; + + ret =vaddr_get_pfn (vaddr, rdwr, &pfn); +if (ret) { +__vfio_dma_unmap (iommu, start, i, rdwr); +return ret; + } + +/* Only add actual locked pages to accounting */ +if (!is_invalid_reserved_pfn (pfn)) + locked++; + + ret =iommu_map (iommu->domain, iova, + (phys_addr_t )pfn <<PAGE_SHIFT ,0 , prot); +if (ret) { +/* Back out mappings on error */ +put_pfn (pfn, rdwr);Quoted 8 lines
drivers/vfio/vfio_iommu.c line 250
Quoted 4 lines
drivers/vfio/vfio_iommu.c new file +4
-0+__vfio_dma_unmap (iommu, start, i, rdwr); +return ret; + } + }There's no way to hand this stuff to the IOMMU driver in chunks larger than a page? That's going to be a problem for our IOMMU, which wants to deal with large windows.
Quoted 6 lines
There is, this is just a simple implementation that maps individual pages. We "just" need to determine physically contiguous chunks and mlock them instead of using
get_user_pages. The current implementation is much like how KVM maps iommu pages, but there shouldn't be a user API change to try to use larger chinks. We want this for IOMMU large page support too.
Also, at one point intel-iommu didn't allow sub-ranges to be unmapped; an unmap of a single page would unmap the entire original mapping that contained that page. That made it easier to map each page individually for the flexibility it provided on unmap. I need to see if we still have that restriction. Thanks,
Alex
Quoted 8 lines · Alex Williamson
Quoted 1 line · Scott Wood
What are the semantics of "desired and/or returned dma address"?
I believe the original intention was that a user could leave dmaaddr clear and let the iommu layer provide an iova address. The iommu api has since evolved and that mapping scheme really isn't present anymore. We'll currently fail if we can map the requested address. I'll update the docs to make that be the definition.
OK... if there is any desire in the future to have the kernel pick an address (which could be useful for IOMMUs that don't set VFIO_IOMMU_FLAGS_MAP_ANY), there should be an explicit flag for this, since zero could be a valid address to request (doesn't mean "clear").
Quoted 9 lines
Quoted 3 lines
Note that the "length of structure" approach means that ioctl numbers will change whenever this grows -- perhaps we should avoid encoding the struct size into these ioctls?
How so? What's described here is effectively the base size. If we later add feature foo requiring additional fields, we set a flag, change the size, and tack those fields onto the end. The kernel side should balk if the size doesn't match what it expects from the flags it understands (which I think I probably need to be more strict about).
The size of the struct is encoded into the ioctl number via the _IOWR() macro. If we want the struct to be growable in the future, we should leave that out and just use _IO(). Otherwise if the size of the struct changes, the ioctl number changes. This is annoying for old userspace plus new kernel (have to add compat entries to the switch), and broken for old kernel plus new userspace.
Quoted 9 lines
Quoted 5 lines
Can we limit the
IOMMU_APIdependency to the IOMMU parts of VFIO? It would still be useful for devices which don't do DMA, or where we accept the lack of protection/translation (e.g. we have a customer that wants to do KVM device assignment on one of our lower-end chips that lacks an IOMMU).Ugh. I'm not really onboard with it given that we're trying to sell vfio as a secure user space driver interface with iommu-based protection.
That's its main use case, but it doesn't make much sense to duplicate the non-iommu-related bits for other use cases.
This applies at runtime too, some devices don't do DMA at all (and thus may not be part of an IOMMU group, even if there is an IOMMU present for other devices -- could be considered a standalone group of one device, with a null IOMMU backend). Support for such devices can wait, but it's good to keep the possibility in mind.
-Scott
Am 14.11.2011 um 23:26 schrieb Scott Wood <[email protected]>:
Quoted 25 lines · Alex Williamson
Quoted 8 lines · Scott Wood
Quoted 1 line
What are the semantics of "desired and/or returned dma address"?
I believe the original intention was that a user could leave dmaaddr clear and let the iommu layer provide an iova address. The iommu api has since evolved and that mapping scheme really isn't present anymore. We'll currently fail if we can map the requested address. I'll update the docs to make that be the definition.
OK... if there is any desire in the future to have the kernel pick an address (which could be useful for IOMMUs that don't set
VFIO_IOMMU_FLAGS_MAP_ANY), there should be an explicit flag for this, since zero could be a valid address to request (doesn't mean "clear").Quoted 9 lines
Quoted 3 lines
Note that the "length of structure" approach means that ioctl numbers will change whenever this grows -- perhaps we should avoid encoding the struct size into these ioctls?
How so? What's described here is effectively the base size. If we later add feature foo requiring additional fields, we set a flag, change the size, and tack those fields onto the end. The kernel side should balk if the size doesn't match what it expects from the flags it understands (which I think I probably need to be more strict about).
Quoted 6 lines
The size of the struct is encoded into the ioctl number via the
_IOWR()macro. If we want the struct to be growable in the future, we should leave that out and just use_IO(). Otherwise if the size of the struct changes, the ioctl number changes. This is annoying for old userspace plus new kernel (have to add compat entries to the switch), and broken for old kernel plus new userspace.
Avi wanted to write up a patch for this to allow ioctls with arbitrary size, for exctly this purpose.
Quoted 11 lines
Quoted 10 lines
Quoted 6 lines
Can we limit the
IOMMU_APIdependency to the IOMMU parts of VFIO? It would still be useful for devices which don't do DMA, or where we accept the lack of protection/translation (e.g. we have a customer that wants to do KVM device assignment on one of our lower-end chips that lacks an IOMMU).Ugh. I'm not really onboard with it given that we're trying to sell vfio as a secure user space driver interface with iommu-based protection.
Quoted 8 lines
That's its main use case, but it doesn't make much sense to duplicate the non-iommu-related bits for other use cases.
This applies at runtime too, some devices don't do DMA at all (and thus may not be part of an IOMMU group, even if there is an IOMMU present for other devices -- could be considered a standalone group of one device, with a null IOMMU backend). Support for such devices can wait, but it's good to keep the possibility in mind.
I agree. Potentially backing a device with a nop iommu also makes testing easier.
Alex
Quoted 1 line
Quoted 21 lines · Alex Williamson
Quoted 12 lines · Scott Wood
Documentation/vfio.txt line 276
Quoted 9 lines · Alex Williamson
Documentation/vfio.txt new file +9
-0+ int (*get)(void *); + void (*put)(void *); + ssize_t (*read)(void *, char __user *, + size_t, loff_t *); + ssize_t (*write)(void *, const char __user *, + size_t, loff_t *); + long (*ioctl)(void *, unsigned int, unsigned long); + int (*mmap)(void *, struct vm_area_struct *); +};When defining an API, please do not omit parameter names.
ok
Quoted 4 lines
Should specify what the driver is supposed to do with get/put -- I guess not try to unbind when the count is nonzero? Races could still lead the unbinder to be blocked, but I guess it lets the driver know when it's likely to succeed.
Quoted 4 lines
Right, for the pci bus driver, it's mainly for reference counting, including the
module_getto prevent vfio-pci from being unloaded. On the first get for a device, we also do apci_enable()andpci_disable()on last put. I'll try to clarify in the docs.
Looking at these again, I should just rename them to open/release. That matches the points when they're called. I suspect I started with just reference counting and it grew to more of a full blown open/release. Thanks,
Alex
Quoted 84 lines · Alex Williamson
VFIO provides a secure, IOMMU based interface for user space drivers, including device assignment to virtual machines. This provides the base management of IOMMU groups, devices, and IOMMU objects. See
Documentation/vfio.txtincluded in this patch for user and kernel API description.Note, this implements the new API discussed at KVM Forum 2011, as represented by the drvier version 0.2. It's hoped that this provides a modular enough interface to support PCI and non-PCI userspace drivers across various architectures and IOMMU implementations.
Signed-off-by Alex Williamson <[email protected]>---
Fingers crossed, this is the last RFC for VFIO, but we need the iommu group support before this can go upstream
(http://lkml.indiana.edu/hypermail/linux/kernel/1110.2/02303.html),
hoping this helps push that along.Since the last posting, this version completely modularizes the device backends and better defines the APIs between the core VFIO code and the device backends. I expect that we might also adopt a modular IOMMU interface as
iommu_opslearns about different types of hardware. Also many, many cleanups. Check the complete git history for details:
git://github.com/awilliam/linux-vfio.gitvfio-ng(matching qemu tree:
git://github.com/awilliam/qemu-vfio.git)This version, along with the supporting VFIO PCI backend can be found here:
git://github.com/awilliam/linux-vfio.gitvfio-next-20111103I've held off on implementing a
kernel->usersignaling mechanism for now since the previous netlink version produced too many gag reflexes. It's easy enough to set a bit in the group flags too indicate such support in the future, so I think we can move ahead without it.Appreciate any feedback or suggestions. Thanks,
Alex
Documentation/ioctl/ioctl-number.txt | 1 Documentation/vfio.txt | 304 +++++++++ MAINTAINERS | 8 drivers/Kconfig | 2 drivers/Makefile | 1 drivers/vfio/Kconfig | 8 drivers/vfio/Makefile | 3 drivers/vfio/vfio_iommu.c | 530 ++++++++++++++++ drivers/vfio/vfio_main.c | 1151 ++++++++++++++++++++++++++++++++++ drivers/vfio/vfio_private.h | 34 + include/linux/vfio.h | 155 +++++ 11 files changed, 2197 insertions(+), 0 deletions(-) create mode 100644 Documentation/vfio.txt create mode 100644 drivers/vfio/Kconfig create mode 100644 drivers/vfio/Makefile create mode 100644 drivers/vfio/vfio_iommu.c create mode 100644 drivers/vfio/vfio_main.c create mode 100644 drivers/vfio/vfio_private.h create mode 100644 include/linux/vfio.hDocumentation/ioctl/ioctl-number.txt +1
-0@@ -88,6 +88,7 @@ Code Seq#(hex) Include File Comments and kernel/power/user.c '8' all SNP8023 advanced NIC card <mailto:[email protected]> +';' 64-76 linux/vfio.h '@' 00-0F linux/radeonfb.h conflict! '@' 00-0F drivers/video/aty/aty128fb.c conflict! 'A' 00-1F linux/apm_bios.h conflict!Documentation/vfio.txt new file +0
-0
Documentation/vfio.txt line 10
Quoted 10 lines
Documentation/vfio.txt new file +10
-0@@ -0,0 +1,304 @@ +VFIO - "Virtual Function I/O"[1] +------------------------------------------------------------------------------- +Many modern system now provide DMA and interrupt remapping facilities +to help ensure I/O devices behave within the boundaries they've been +allotted. This includes x86 hardware with AMD-Vi and Intel VT-d as +well as POWER systems with Partitionable Endpoints (PEs) and even +embedded powerpc systems (technology name unknown). The VFIO driver +is an IOMMU/device agnostic framework for exposing direct device +access to userspace, in a secure, IOMMU protected environment. In +other words, this allows safe, non-privileged, userspace drivers.
It's perhaps worth emphasisng that "safe" depends on the hardware being sufficiently well behaved. BenH, I know, thinks there are a *lot* of cards that, e.g. have debug registers that allow a backdoor to their own config space via MMIO, which would bypass vfio's filtering of config space access. And that's before we even get into the varying degrees of completeness in the isolation provided by different IOMMUs.
Documentation/vfio.txt line 22
Quoted 11 lines
Documentation/vfio.txt new file +11
-0+Why do we want that? Virtual machines often make use of direct device +access ("device assignment") when configured for the highest possible +I/O performance. From a device and host perspective, this simply turns +the VM into a userspace driver, with the benefits of significantly +reduced latency, higher bandwidth, and direct use of bare-metal device +drivers[2]. + +Some applications, particularly in the high performance computing +field, also benefit from low-overhead, direct device access from +userspace. Examples include network adapters (often non-TCP/IP based) +and compute accelerators. Previous to VFIO, these drivers needed to
s/Previous/Prior/ although that may be a .us vs .au usage thing.
Quoted 22 lines
Documentation/vfio.txt new file +22
-0+go through the full development cycle to become proper upstream driver, +be maintained out of tree, or make use of the UIO framework, which +has no notion of IOMMU protection, limited interrupt support, and +requires root privileges to access things like PCI configuration space. + +The VFIO driver framework intends to unify these, replacing both the +KVM PCI specific device assignment currently used as well as provide +a more secure, more featureful userspace driver environment than UIO. + +Groups, Devices, IOMMUs, oh my +------------------------------------------------------------------------------- + +A fundamental component of VFIO is the notion of IOMMU groups. IOMMUs +can't always distinguish transactions from each individual device in +the system. Sometimes this is because of the IOMMU design, such as with +PEs, other times it's caused by the I/O topology, for instance a +PCIe-to-PCI bridge masking all devices behind it. We call the sets of +devices created by these restictions IOMMU groups (or just "groups" for +this document). + +The IOMMU cannot distiguish transactions between the individual devices +within the group, therefore the group is the basic unit of ownership for
Documentation/vfio.txt line 54
Quoted 10 lines
Documentation/vfio.txt new file +10
-0+a userspace process. Because of this, groups are also the primary +interface to both devices and IOMMU domains in VFIO. + +The VFIO representation of groups is created as devices are added into +the framework by a VFIO bus driver. The vfio-pci module is an example +of a bus driver. This module registers devices along with a set of bus +specific callbacks with the VFIO core. These callbacks provide the +interfaces later used for device access. As each new group is created, +as determined by iommu_device_group(), VFIO creates a /dev/vfio/$GROUP +character device.
Ok.. so, the fact that it's called "vfio-pci" suggests that the VFIO
bus driver is per bus type, not per bus instance. But grouping
constraints could be per bus instance, if you have a couple of different models of PCI host bridge with IOMMUs of different capabilities built in, for example.
Quoted 25 lines
Documentation/vfio.txt new file +25
-0+In addition to the device enumeration and callbacks, the VFIO bus driver +also provides a traditional device driver and is able to bind to devices +on it's bus. When a device is bound to the bus driver it's available to +VFIO. When all the devices within a group are bound to their bus drivers, +the group becomes "viable" and a user with sufficient access to the VFIO +group chardev can obtain exclusive access to the set of group devices. + +As documented in linux/vfio.h, several ioctls are provided on the +group chardev: + +#define VFIO_GROUP_GET_FLAGS _IOR(';', 100, __u64) + #define VFIO_GROUP_FLAGS_VIABLE (1 << 0) + #define VFIO_GROUP_FLAGS_MM_LOCKED (1 << 1) +#define VFIO_GROUP_MERGE _IOW(';', 101, int) +#define VFIO_GROUP_UNMERGE _IOW(';', 102, int) +#define VFIO_GROUP_GET_IOMMU_FD _IO(';', 103) +#define VFIO_GROUP_GET_DEVICE_FD _IOW(';', 104, char *) + +The last two ioctls return new file descriptors for accessing +individual devices within the group and programming the IOMMU. Each of +these new file descriptors provide their own set of file interfaces. +These ioctls will fail if any of the devices within the group are not +bound to their VFIO bus driver. Additionally, when either of these +interfaces are used, the group is then bound to the struct_mm of the +caller. The GET_FLAGS ioctl can be used to view the state of the group.
Documentation/vfio.txt
Quoted 10 lines
Documentation/vfio.txt new file +10
-0+ +When either the GET_IOMMU_FD or GET_DEVICE_FD ioctls are invoked, a +new IOMMU domain is created and all of the devices in the group are +attached to it. This is the only way to ensure full IOMMU isolation +of the group, but potentially wastes resources and cycles if the user +intends to manage multiple groups with the same set of IOMMU mappings. +VFIO therefore provides a group MERGE and UNMERGE interface, which +allows multiple groups to share an IOMMU domain. Not all IOMMUs allow +arbitrary groups to be merged, so the user should assume merging is +opportunistic.
I do not think "opportunistic" means what you think it means..
Quoted 9 lines
Documentation/vfio.txt new file +7
-0A new group, with no open device or IOMMU file +descriptors, can be merged into an existing, in-use, group using the +MERGE ioctl. A merged group can be unmerged using the UNMERGE ioctl +once all of the device file descriptors for the group being merged +"out" are closed. + +When groups are merged, the GET_IOMMU_FD and GET_DEVICE_FD ioctls are +essentially fungible between group file descriptors (ie. if deviceA
IDNT "fungible" MWYTIM, either.
Documentation/vfio.txt line 103
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+is in group X, and X is merged with Y, a file descriptor for A can be +retrieved using GET_DEVICE_FD on Y. Likewise, GET_IOMMU_FD returns a +file descriptor referencing the same internal IOMMU object from either +X or Y). Merged groups can be dissolved either explictly with UNMERGE +or automatically when ALL file descriptors for the merged group are +closed (all IOMMUs, all devices, all groups).
Blech. I'm really not liking this merge/unmerge API as it stands, it's horribly confusing. At the very least, we need some better terminology. We need some term for the metagroups; supergroups; iommu domains or-at-least-they-will-be-once-we-open-the-iommu or whathaveyous.
The first confusing thing about this interface is that each open group handle actually refers to two different things; the original group you opened and the metagroup it's a part of. For the GET_IOMMU_FD and GET_DEVICE_FD operations, you're using the metagroup and two "merged" group handles are interchangeable. For other MERGE and especially UNMERGE operations, it matters which is the original group.
The semantics of "merge" and "unmerge" under those names are really non-obvious. Merge kind of has to merge two whole metagroups, but it's unclear if unmerge reverses one merge, or just takes out one (atom) group. These operations need better names, at least.
Then it's unclear what order you can do various operations, and which order you can open and close various things. You can kind of figure it out but it takes far more thinking than it should.
So at the _very_ least, we need to invent new terminology and find a much better way of describing this API's semantics. I still think an entirely different interface, where metagroups are created from outside with a lifetime that's not tied to an fd would be a better idea.
Now, you specify that you can't use a group as the second argument of a merge if it already has an open iommu, but it's not clear from the doc if you can merge things into a group with an open iommu. Banning this would make life simpler, because the IOMMU's effective capabilities may change if you add more devices to the domain. That's yet another non-obvious constraint in the interface ordering, though.
Quoted 11 lines
Documentation/vfio.txt new file +10
-0+The IOMMU file descriptor provides this set of ioctls: + +#define VFIO_IOMMU_GET_FLAGS _IOR(';', 105, __u64) + #define VFIO_IOMMU_FLAGS_MAP_ANY (1 << 0) +#define VFIO_IOMMU_MAP_DMA _IOWR(';', 106, struct vfio_dma_map) +#define VFIO_IOMMU_UNMAP_DMA _IOWR(';', 107, struct vfio_dma_map) + +The GET_FLAGS ioctl returns basic information about the IOMMU domain. +We currently only support IOMMU domains that are able to map any +virtual address to any IOVA. This is indicated by the MAP_ANYflag.
So. I tend to think of an IOMMU mapping IOVAs to memory pages, rather than memory pages to IOVAs. The IOMMU itself, of course maps to physical addresses, and the meaning of "virtual address" in this context is not really clear. I think you would be better off saying the IOMMU can map any IOVA to any memory page. From a hardware POV that means any physical address, but of course for a VFIO user a page is specified by its process virtual address.
I think we need to pin exactly what "MAP_ANY" means down better. Now, VFIO is pretty much a lost cause if you can't map any normal process memory page into the IOMMU, so I think the only thing that is really covered is IOVAs. But saying "can map any IOVA" is not clear, because if you can't map it, it's not a (valid) IOVA. Better to say that IOVAs can be any 64-bit value, which I think is what you really mean here.
Of course, since POWER is a platform where this is *not* true, I'd prefer to have something giving the range of valid IOVAs in the core to start with.
Documentation/vfio.txt line 120
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+ +The (UN)MAP_DMA commands make use of struct vfio_dma_map for mapping +and unmapping IOVAs to process virtual addresses: + +struct vfio_dma_map { + __u64 len; /* length of structure */
Thanks for adding these structure length fields. But I think they should be called something other than 'len', which is likely to be confused with size (or some other length that's actually related to the operation's parameters). Better to call it 'structlen' or 'argslen' or something.
Documentation/vfio.txt line 125
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+ __u64 vaddr; /* process virtual addr */ + __u64 dmaaddr; /* desired and/or returned dma address */ + __u64 size; /* size in bytes */ + __u64 flags; +#define VFIO_DMA_MAP_FLAG_WRITE (1 << 0) /* req writeable DMA mem */
Make it independent READ and WRITE flags from the start. Not all combinations will be be valid on all hardware, but that way we have the possibilities covered without having to use strange encodings later.
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+}; + +Current users of VFIO use relatively static DMA mappings, not requiring +high frequency turnover. As new users are added, it's expected that the +IOMMU file descriptor will evolve to support new mapping interfaces, this +will be reflected in the flags and may present new ioctls and file
Documentation/vfio.txt line 141
Quoted 10 lines
Documentation/vfio.txt new file +10
-0+interfaces. + +The device GET_FLAGS ioctl is intended to return basic device type and +indicate support for optional capabilities. Flags currently include whether +the device is PCI or described by Device Tree, and whether the RESET ioctl +is supported: + +#define VFIO_DEVICE_GET_FLAGS _IOR(';', 108, __u64) + #define VFIO_DEVICE_FLAGS_PCI (1 << 0) + #define VFIO_DEVICE_FLAGS_DT (1 << 1)
TBH, I don't think the VFIO for DT stuff is mature enough yet to be in an initial infrastructure patch, though we should certainly be discussing it as an add-on patch.
Documentation/vfio.txt line 153
Quoted 12 lines
+ #define
VFIO_DEVICE_FLAGS_RESET(1 << 2)Documentation/vfio.txt new file +11
-0+ +The MMIO and IOP resources used by a device are described by regions. +The GET_NUM_REGIONS ioctl tells us how many regions the device supports: + +#define VFIO_DEVICE_GET_NUM_REGIONS _IOR(';', 109, int) + +Regions are described by a struct vfio_region_info, which is retrieved by +using the GET_REGION_INFO ioctl with vfio_region_info.index field set to +the desired region (0 based index). Note that devices may implement zero +sized regions (vfio-pci does this to provide a 1:1 BAR to region index +mapping).
So, I think you're saying that a zero-sized region is used to encode a NOP region, that is, to basically put a "no region here" in between valid region indices. You should spell that out.
[Incidentally, any chance you could borrow one of RH's tech writers for this? I'm afraid you seem to lack the knack for clear and easily read documentation]
Documentation/vfio.txt line 162
Quoted 8 lines
Documentation/vfio.txt new file +8
-0+struct vfio_region_info { + __u32 len; /* length of structure */ + __u32 index; /* region number */ + __u64 size; /* size in bytes of region */ + __u64 offset; /* start offset of region */ + __u64 flags; +#define VFIO_REGION_INFO_FLAG_MMAP (1 << 0) +#define VFIO_REGION_INFO_FLAG_RO (1 << 1)
Again having separate read and write bits from the start will save strange encodings later.
Documentation/vfio.txt line 165
Quoted 3 lines
Documentation/vfio.txt new file +3
-0+#define VFIO_REGION_INFO_FLAG_PHYS_VALID (1 << 2) + __u64 phys; /* physical address of region */ +};
I notice there is no field for "type" e.g. MMIO vs. PIO vs. config space for PCI. If you added that having a NONE type might be a clearer way of encoding a non-region than just having size==0.
Quoted 7 lines
Documentation/vfio.txt new file +7
-0+ +#define VFIO_DEVICE_GET_REGION_INFO _IOWR(';', 110, struct vfio_region_info) + +The offset indicates the offset into the device file descriptor which +accesses the given range (for read/write/mmap/seek). Flags indicate the +available access types and validity of optional fields. For instance +the phys field may only be valid for certain devices types.
Documentation/vfio.txt line 182
Quoted 10 lines
Documentation/vfio.txt new file +10
-0+ +Interrupts are described using a similar interface. GET_NUM_IRQS +reports the number or IRQ indexes for the device. + +#define VFIO_DEVICE_GET_NUM_IRQS _IOR(';', 111, int) + +struct vfio_irq_info { + __u32 len; /* length of structure */ + __u32 index; /* IRQ number */ + __u32 count; /* number of individual IRQs */
Is there a reason for allowing irqs in batches like this, rather than having each MSI be reflected by a separate irq_info?
Documentation/vfio.txt line 188
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+ __u64 flags; +#define VFIO_IRQ_INFO_FLAG_LEVEL (1 << 0) +}; + +Again, zero count entries are allowed (vfio-pci uses a static interrupt +type to index mapping).
I know what you mean, but you need a clearer way to express it.
Quoted 10 lines
Documentation/vfio.txt new file +10
-0+Information about each index can be retrieved using the GET_IRQ_INFO +ioctl, used much like GET_REGION_INFO. + +#define VFIO_DEVICE_GET_IRQ_INFO _IOWR(';', 112, struct vfio_irq_info) + +Individual indexes can describe single or sets of IRQs. This provides the +flexibility to describe PCI INTx, MSI, and MSI-X using a single interface. + +All VFIO interrupts are signaled to userspace via eventfds. Integer arrays, +as shown below, are used to pass the IRQ info index, the number of eventfds,
Documentation/vfio.txt line 209
Quoted 10 lines
Documentation/vfio.txt new file +10
-0+and each eventfd to be signaled. Using a count of 0 disables the interrupt. + +/* Set IRQ eventfds, arg[0] = index, arg[1] = count, arg[2-n] = eventfds */ +#define VFIO_DEVICE_SET_IRQ_EVENTFDS _IOW(';', 113, int) + +When a level triggered interrupt is signaled, the interrupt is masked +on the host. This prevents an unresponsive userspace driver from +continuing to interrupt the host system. After servicing the interrupt, +UNMASK_IRQ is used to allow the interrupt to retrigger. Note that level +triggered interrupts implicitly have a count of 1 per index.
This is a silly restriction. Even PCI devices can have up to 4 LSIs on a function in theory, though no-one ever does. Embedded devices can and do have multiple level interrupts.
Quoted 38 lines
Documentation/vfio.txt new file +38
-0+ +/* Unmask IRQ index, arg[0] = index */ +#define VFIO_DEVICE_UNMASK_IRQ _IOW(';', 114, int) + +Level triggered interrupts can also be unmasked using an irqfd. Use +SET_UNMASK_IRQ_EVENTFD to set the file descriptor for this. + +/* Set unmask eventfd, arg[0] = index, arg[1] = eventfd */ +#define VFIO_DEVICE_SET_UNMASK_IRQ_EVENTFD _IOW(';', 115, int) + +When supported, as indicated by the device flags, reset the device. + +#define VFIO_DEVICE_RESET _IO(';', 116) + +Device tree devices also invlude ioctls for further defining the +device tree properties of the device: + +struct vfio_dtpath { + __u32 len; /* length of structure */ + __u32 index; + __u64 flags; +#define VFIO_DTPATH_FLAGS_REGION (1 << 0) +#define VFIO_DTPATH_FLAGS_IRQ (1 << 1) + char *path; +}; +#define VFIO_DEVICE_GET_DTPATH _IOWR(';', 117, struct vfio_dtpath) + +struct vfio_dtindex { + __u32 len; /* length of structure */ + __u32 index; + __u32 prop_type; + __u32 prop_index; + __u64 flags; +#define VFIO_DTINDEX_FLAGS_REGION (1 << 0) +#define VFIO_DTINDEX_FLAGS_IRQ (1 << 1) +}; +#define VFIO_DEVICE_GET_DTINDEX _IOWR(';', 118, struct vfio_dtindex) +
Documentation/vfio.txt line 257
Quoted 10 lines
Documentation/vfio.txt new file +10
-0+ +VFIO bus driver API +------------------------------------------------------------------------------- + +Bus drivers, such as PCI, have three jobs: + 1) Add/remove devices from vfio + 2) Provide vfio_device_ops for device access + 3) Device binding and unbinding + +When initialized, the bus driver should enumerate the devices on it's
s/it's/its/
Quoted 253 lines
Documentation/vfio.txt new file +47
-0+bus and call vfio_group_add_dev() for each device. If the bus supports +hotplug, notifiers should be enabled to track devices being added and +removed. vfio_group_del_dev() removes a previously added device from +vfio. + +Adding a device registers a vfio_device_ops function pointer structure +for the device: + +struct vfio_device_ops { + bool (*match)(struct device *, char *); + int (*get)(void *); + void (*put)(void *); + ssize_t (*read)(void *, char __user *, + size_t, loff_t *); + ssize_t (*write)(void *, const char __user *, + size_t, loff_t *); + long (*ioctl)(void *, unsigned int, unsigned long); + int (*mmap)(void *, struct vm_area_struct *); +}; + +When a device is bound to the bus driver, the bus driver indicates this +to vfio using the vfio_bind_dev() interface. The device_data parameter +is a pointer to an opaque data structure for use only by the bus driver. +The get, put, read, write, ioctl, and mmap vfio_device_ops all pass +this data structure back to the bus driver. When a device is unbound +from the bus driver, the vfio_unbind_dev() interface signals this to +vfio. This function returns the pointer to the device_data structure +registered for the device. + +As noted previously, a group contains one or more devices, so +GROUP_GET_DEVICE_FD needs to identify the specific device being requested. +The vfio_device_ops.match callback is used to allow bus drivers to determine +the match. For drivers like vfio-pci, it's a simple match to dev_name(), +which is unique in the system due to the PCI bus topology, other bus drivers +may need to include parent devices to create a unique match, so this is +left as a bus driver interface. + +------------------------------------------------------------------------------- + +[1] VFIO was originally an acronym for "Virtual Function I/O" in it's +initial implementation by Tom Lyon while as Cisco. We've since outgrown +the acronym, but it's catchy. + +[2] As always there are trade-offs to virtual machine device +assignment that are beyond the scope of VFIO. It's expected that +future IOMMU technologies will reduce some, but maybe not all, of +these trade-offs.MAINTAINERS +8
-0@@ -7106,6 +7106,14 @@ S: Maintained F: Documentation/filesystems/vfat.txt F: fs/fat/ +VFIO DRIVER +M: Alex Williamson <[email protected]> +L: [email protected] +S: Maintained +F: Documentation/vfio.txt +F: drivers/vfio/ +F: include/linux/vfio.h + VIDEOBUF2 FRAMEWORK M: Pawel Osciak <[email protected]> M: Marek Szyprowski <[email protected]>drivers/Kconfig +2
-0@@ -112,6 +112,8 @@ source "drivers/auxdisplay/Kconfig" source "drivers/uio/Kconfig" +source "drivers/vfio/Kconfig" + source "drivers/vlynq/Kconfig" source "drivers/virtio/Kconfig"drivers/Makefile +1
-0@@ -58,6 +58,7 @@ obj-$(CONFIG_ATM) += atm/ obj-$(CONFIG_FUSION) += message/ obj-y += firewire/ obj-$(CONFIG_UIO) += uio/ +obj-$(CONFIG_VFIO) += vfio/ obj-y += cdrom/ obj-y += auxdisplay/ obj-$(CONFIG_PCCARD) += pcmcia/drivers/vfio/Kconfig new file +8
-0@@ -0,0 +1,8 @@ +menuconfig VFIO + tristate "VFIO Non-Privileged userspace driver framework" + depends on IOMMU_API + help + VFIO provides a framework for secure userspace device drivers. + See Documentation/vfio.txt for more details. + + If you don't know what to do here, say N.drivers/vfio/Makefile new file +3
-0@@ -0,0 +1,3 @@ +vfio-y := vfio_main.o vfio_iommu.o + +obj-$(CONFIG_VFIO) := vfio.odrivers/vfio/vfio_iommu.c new file +133
-0@@ -0,0 +1,530 @@ +/* +* VFIO: IOMMU DMA mapping support +* +* Copyright (C) 2011 Red Hat, Inc. All rights reserved. +* Author: Alex Williamson <[email protected]> +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License version 2 as +* published by the Free Software Foundation. +* +* Derived from original vfio: +* Copyright 2010 Cisco Systems, Inc. All rights reserved. +* Author: Tom Lyon, [email protected] +*/ + +#include <linux/compat.h> +#include <linux/device.h> +#include <linux/fs.h> +#include <linux/iommu.h> +#include <linux/module.h> +#include <linux/mm.h> +#include <linux/sched.h> +#include <linux/slab.h> +#include <linux/uaccess.h> +#include <linux/vfio.h> +#include <linux/workqueue.h> + +#include "vfio_private.h" + +struct dma_map_page { +struct list_head list; +dma_addr_t daddr; +unsigned long vaddr; +int npage; +int rdwr; +}; + +/* +* This code handles mapping and unmapping of user data buffers +* into DMA'ble space using the IOMMU +*/ + +#define NPAGE_TO_SIZE (npage) ((size_t)(npage) << PAGE_SHIFT) + +struct vwork { +struct mm_struct *mm; +int npage; +struct work_struct work; +}; + +/* delayed decrement for locked_vm */ +static void vfio_lock_acct_bg (struct work_struct *work) +{ + struct vwork *vwork = container_of(work, struct vwork, work); +struct mm_struct *mm; + + mm = vwork->mm; +down_write (&mm->mmap_sem); + mm->locked_vm += vwork->npage; +up_write (&mm->mmap_sem); +mmput (mm);/* unref mm */ +kfree (vwork); +} + +static void vfio_lock_acct (int npage) +{ +struct vwork *vwork; +struct mm_struct *mm; + +if (!current->mm) { +/* process exited */ +return ; + } +if (down_write_trylock (¤t->mm->mmap_sem)) { + current->mm->locked_vm += npage; +up_write (¤t->mm->mmap_sem); +return ; + } +/* +* Couldn't get mmap_sem lock, so must setup to decrement +* mm->locked_vm later. If locked_vm were atomic, we wouldn't +* need this silliness +*/ + vwork =kmalloc (sizeof (struct vwork ),GFP_KERNEL ); +if (!vwork) +return ; + mm =get_task_mm (current);/* take ref mm */ +if (!mm) { +kfree (vwork); +return ; + } +INIT_WORK (&vwork->work, vfio_lock_acct_bg); + vwork->mm = mm; + vwork->npage = npage; +schedule_work (&vwork->work); +} + +/* Some mappings aren't backed by a struct page, for example an mmap'd +* MMIO range for our own or another device. These use a different +* pfn conversion and shouldn't be tracked as locked pages. */ +static int is_invalid_reserved_pfn (unsigned long pfn) +{ +if (pfn_valid (pfn)) { +int reserved; +struct page *tail =pfn_to_page (pfn); +struct page *head =compound_trans_head (tail); + reserved =PageReserved (head); +if (head != tail) { +/* "head" is not a dangling pointer +* (compound_trans_head takes care of that) +* but the hugepage may have been split +* from under us (and we may not hold a +* reference count on the head page so it can +* be reused before we run PageReferenced), so +* we've to check PageTail before returning +* what we just read. +*/ +smp_rmb (); +if (PageTail (tail)) +return reserved; + } +return PageReserved (tail); + } + +return true; +} + +static int put_pfn (unsigned long pfn,int rdwr) +{ +if (!is_invalid_reserved_pfn (pfn)) { +struct page *page =pfn_to_page (pfn); +if (rdwr) +SetPageDirty (page);
drivers/vfio/vfio_iommu.c line 143
Quoted 10 lines
drivers/vfio/vfio_iommu.c new file +10
-0+put_page (page); +return 1 ; + } +return 0 ; +} + +/* Unmap DMA region */ +/* dgate must be held */ +static int __vfio_dma_unmap (struct vfio_iommu *iommu,unsigned long iova, +int npage,int rdwr)
Use of "read" and "write" in DMA can often be confusing, since it's not always clear if you're talking from the perspective of the CPU or the device (_writing_ data to a device will usually involve it doing DMA _reads_ from memory). It's often best to express things as DMA direction, 'to device', and 'from device' instead.
Quoted 12 lines
drivers/vfio/vfio_iommu.c new file +12
-0+{ +int i, unlocked =0 ; + +for (i =0 ; i < npage; i++, iova +=PAGE_SIZE ) { +unsigned long pfn; + + pfn =iommu_iova_to_phys (iommu->domain, iova) >>PAGE_SHIFT ; +if (pfn) { +iommu_unmap (iommu->domain, iova,0 ); + unlocked +=put_pfn (pfn, rdwr); + } + }
drivers/vfio/vfio_iommu.c line 165
Quoted 10 lines
drivers/vfio/vfio_iommu.c new file +10
-0+return unlocked; +} + +static void vfio_dma_unmap (struct vfio_iommu *iommu,unsigned long iova, +unsigned long npage,int rdwr) +{ +int unlocked; + + unlocked =__vfio_dma_unmap (iommu, iova, npage, rdwr); +vfio_lock_acct (-unlocked);
Have you checked that your accounting will work out if the user maps the same memory page to multiple IOVAs?
Quoted 6 lines
drivers/vfio/vfio_iommu.c new file +6
-0+} + +/* Unmap ALL DMA regions */ +void vfio_iommu_unmapall (struct vfio_iommu *iommu) +{ +struct list_head *pos, *pos2;
drivers/vfio/vfio_iommu.c line 181
Quoted 10 lines
drivers/vfio/vfio_iommu.c new file +10
-0+struct dma_map_page *mlp; + +mutex_lock (&iommu->dgate); +list_for_each_safe (pos, pos2, &iommu->dm_list) { + mlp = list_entry(pos, struct dma_map_page, list); +vfio_dma_unmap (iommu, mlp->daddr, mlp->npage, mlp->rdwr); +list_del (&mlp->list); +kfree (mlp); + } +mutex_unlock (&iommu->dgate);
Ouch, no good at all. Keeping track of every DMA map is no good on POWER or other systems where IOMMU operations are a hot path. I think you'll need an iommu specific hook for this instead, which uses whatever data structures are natural for the IOMMU. For example a 1-level pagetable, like we use on POWER will just zero every entry.
Quoted 12 lines
drivers/vfio/vfio_iommu.c new file +12
-0+} + +static int vaddr_get_pfn (unsigned long vaddr,int rdwr,unsigned long *pfn) +{ +struct page *page[1 ]; +struct vm_area_struct *vma; +int ret = -EFAULT ; + +if (get_user_pages_fast (vaddr,1 , rdwr, page) ==1 ) { + *pfn =page_to_pfn (page[0 ]); +return 0 ; + }
drivers/vfio/vfio_iommu.c line 203
Quoted 10 lines
drivers/vfio/vfio_iommu.c new file +10
-0+ +down_read (¤t->mm->mmap_sem); + + vma =find_vma_intersection (current->mm, vaddr, vaddr +1 ); + +if (vma && vma->vm_flags &VM_PFNMAP ) { + *pfn = ((vaddr - vma->vm_start) >>PAGE_SHIFT ) + vma->vm_pgoff; +if (is_invalid_reserved_pfn (*pfn)) + ret =0 ; + }
It's kind of nasty that you take gup_fast(), already designed to grab pointers for multiple user pages, then just use it one page at a time, even for a big map.
drivers/vfio/vfio_iommu.c line 213
Quoted 9 lines
drivers/vfio/vfio_iommu.c new file +9
-0+up_read (¤t->mm->mmap_sem); + +return ret; +} + +/* Map DMA region */ +/* dgate must be held */ +static int vfio_dma_map (struct vfio_iommu *iommu,unsigned long iova, +unsigned long vaddr,int npage,int rdwr)
iova should be a dma_addr_t. Bus address size need not match virtual address size, and may not fit in an unsigned long.
Quoted 36 lines
drivers/vfio/vfio_iommu.c new file +36
-0+{ +unsigned long start = iova; +int i, ret, locked =0 , prot =IOMMU_READ ; + +/* Verify pages are not already mapped */ +for (i =0 ; i < npage; i++, iova +=PAGE_SIZE ) +if (iommu_iova_to_phys (iommu->domain, iova)) +return -EBUSY ; + + iova = start; + +if (rdwr) + prot |=IOMMU_WRITE ; +if (iommu->cache) + prot |=IOMMU_CACHE ; + +for (i =0 ; i < npage; i++, iova +=PAGE_SIZE , vaddr +=PAGE_SIZE ) { +unsigned long pfn =0 ; + + ret =vaddr_get_pfn (vaddr, rdwr, &pfn); +if (ret) { +__vfio_dma_unmap (iommu, start, i, rdwr); +return ret; + } + +/* Only add actual locked pages to accounting */ +if (!is_invalid_reserved_pfn (pfn)) + locked++; + + ret =iommu_map (iommu->domain, iova, + (phys_addr_t )pfn <<PAGE_SHIFT ,0 , prot); +if (ret) { +/* Back out mappings on error */ +put_pfn (pfn, rdwr); +__vfio_dma_unmap (iommu, start, i, rdwr); +return ret;
drivers/vfio/vfio_iommu.c line 259
Quoted 10 lines
drivers/vfio/vfio_iommu.c new file +10
-0+ } + } +vfio_lock_acct (locked); +return 0 ; +} + +static inline int ranges_overlap (unsigned long start1,size_t size1, +unsigned long start2,size_t size2) +{ +return !(start1 + size1 <= start2 || start2 + size2 <= start1);
Needs overflow safety.
Quoted 6 lines
drivers/vfio/vfio_iommu.c new file +6
-0+} + +static struct dma_map_page *vfio_find_dma (struct vfio_iommu *iommu, +dma_addr_t start,size_t size) +{ +struct list_head *pos;
drivers/vfio/vfio_iommu.c line 275
Quoted 10 lines
drivers/vfio/vfio_iommu.c new file +10
-0+struct dma_map_page *mlp; + +list_for_each (pos, &iommu->dm_list) { + mlp = list_entry(pos, struct dma_map_page, list); +if (ranges_overlap (mlp->daddr,NPAGE_TO_SIZE (mlp->npage), + start, size)) +return mlp; + } +return NULL ; +}
Again, keeping track of each dma map operation is no good for performance.
Quoted 183 lines
drivers/vfio/vfio_iommu.c new file +183
-0+ +int vfio_remove_dma_overlap (struct vfio_iommu *iommu,dma_addr_t start, +size_t size,struct dma_map_page *mlp) +{ +struct dma_map_page *split; +int npage_lo, npage_hi; + +/* Existing dma region is completely covered, unmap all */ +if (start <= mlp->daddr && + start + size >= mlp->daddr +NPAGE_TO_SIZE (mlp->npage)) { +vfio_dma_unmap (iommu, mlp->daddr, mlp->npage, mlp->rdwr); +list_del (&mlp->list); + npage_lo = mlp->npage; +kfree (mlp); +return npage_lo; + } + +/* Overlap low address of existing range */ +if (start <= mlp->daddr) { +size_t overlap; + + overlap = start + size - mlp->daddr; + npage_lo = overlap >>PAGE_SHIFT ; + npage_hi = mlp->npage - npage_lo; + +vfio_dma_unmap (iommu, mlp->daddr, npage_lo, mlp->rdwr); + mlp->daddr += overlap; + mlp->vaddr += overlap; + mlp->npage -= npage_lo; +return npage_lo; + } + +/* Overlap high address of existing range */ +if (start + size >= mlp->daddr +NPAGE_TO_SIZE (mlp->npage)) { +size_t overlap; + + overlap = mlp->daddr +NPAGE_TO_SIZE (mlp->npage) - start; + npage_hi = overlap >>PAGE_SHIFT ; + npage_lo = mlp->npage - npage_hi; + +vfio_dma_unmap (iommu, start, npage_hi, mlp->rdwr); + mlp->npage -= npage_hi; +return npage_hi; + } + +/* Split existing */ + npage_lo = (start - mlp->daddr) >>PAGE_SHIFT ; + npage_hi = mlp->npage - (size >>PAGE_SHIFT ) - npage_lo; + + split =kzalloc (sizeof *split,GFP_KERNEL ); +if (!split) +return -ENOMEM ; + +vfio_dma_unmap (iommu, start, size >>PAGE_SHIFT , mlp->rdwr); + + mlp->npage = npage_lo; + + split->npage = npage_hi; + split->daddr = start + size; + split->vaddr = mlp->vaddr +NPAGE_TO_SIZE (npage_lo) + size; + split->rdwr = mlp->rdwr; +list_add (&split->list, &iommu->dm_list); +return size >>PAGE_SHIFT ; +} + +int vfio_dma_unmap_dm (struct vfio_iommu *iommu,struct vfio_dma_map *dmp) +{ +int ret =0 ; +size_t npage = dmp->size >>PAGE_SHIFT ; +struct list_head *pos, *n; + +if (dmp->dmaaddr & ~PAGE_MASK ) +return -EINVAL ; +if (dmp->size & ~PAGE_MASK ) +return -EINVAL ; + +mutex_lock (&iommu->dgate); + +list_for_each_safe (pos, n, &iommu->dm_list) { +struct dma_map_page *mlp; + + mlp = list_entry(pos, struct dma_map_page, list); +if (ranges_overlap (mlp->daddr,NPAGE_TO_SIZE (mlp->npage), + dmp->dmaaddr, dmp->size)) { + ret =vfio_remove_dma_overlap (iommu, dmp->dmaaddr, + dmp->size, mlp); +if (ret >0 ) + npage -=NPAGE_TO_SIZE (ret); +if (ret <0 || npage ==0 ) +break ; + } + } +mutex_unlock (&iommu->dgate); +return ret >0 ?0 : ret; +} + +int vfio_dma_map_dm (struct vfio_iommu *iommu,struct vfio_dma_map *dmp) +{ +int npage; +struct dma_map_page *mlp, *mmlp =NULL ; +dma_addr_t daddr = dmp->dmaaddr; +unsigned long locked, lock_limit, vaddr = dmp->vaddr; +size_t size = dmp->size; +int ret =0 , rdwr = dmp->flags &VFIO_DMA_MAP_FLAG_WRITE ; + +if (vaddr & (PAGE_SIZE -1 )) +return -EINVAL ; +if (daddr & (PAGE_SIZE -1 )) +return -EINVAL ; +if (size & (PAGE_SIZE -1 )) +return -EINVAL ; + + npage = size >>PAGE_SHIFT ; +if (!npage) +return -EINVAL ; + +if (!iommu) +return -EINVAL ; + +mutex_lock (&iommu->dgate); + +if (vfio_find_dma (iommu, daddr, size)) { + ret = -EBUSY ; + goto out_lock; + } + +/* account for locked pages */ + locked = current->mm->locked_vm + npage; + lock_limit =rlimit (RLIMIT_MEMLOCK ) >>PAGE_SHIFT ; +if (locked > lock_limit && !capable (CAP_IPC_LOCK )) { +printk (KERN_WARNING "%s: RLIMIT_MEMLOCK (%ld) exceeded\n" , + __func__,rlimit (RLIMIT_MEMLOCK )); + ret = -ENOMEM ; + goto out_lock; + } + + ret =vfio_dma_map (iommu, daddr, vaddr, npage, rdwr); +if (ret) + goto out_lock; + +/* Check if we abut a region below */ +if (daddr) { + mlp =vfio_find_dma (iommu, daddr -1 ,1 ); +if (mlp && mlp->rdwr == rdwr && + mlp->vaddr +NPAGE_TO_SIZE (mlp->npage) == vaddr) { + + mlp->npage += npage; + daddr = mlp->daddr; + vaddr = mlp->vaddr; + npage = mlp->npage; + size =NPAGE_TO_SIZE (npage); + + mmlp = mlp; + } + } + +if (daddr + size) { + mlp =vfio_find_dma (iommu, daddr + size,1 ); +if (mlp && mlp->rdwr == rdwr && mlp->vaddr == vaddr + size) { + + mlp->npage += npage; + mlp->daddr = daddr; + mlp->vaddr = vaddr; + +/* If merged above and below, remove previously +* merged entry. New entry covers it. */ +if (mmlp) { +list_del (&mmlp->list); +kfree (mmlp); + } + mmlp = mlp; + } + } + +if (!mmlp) { + mlp =kzalloc (sizeof *mlp,GFP_KERNEL ); +if (!mlp) { + ret = -ENOMEM ; +vfio_dma_unmap (iommu, daddr, npage, rdwr); + goto out_lock; + } + + mlp->npage = npage;
drivers/vfio/vfio_iommu.c line 468
Quoted 10 lines
drivers/vfio/vfio_iommu.c new file +10
-0+ mlp->daddr = daddr; + mlp->vaddr = vaddr; + mlp->rdwr = rdwr; +list_add (&mlp->list, &iommu->dm_list); + } + +out_lock: +mutex_unlock (&iommu->dgate); +return ret; +}
This whole tracking infrastructure is way too complex to impose on every IOMMU. We absolutely don't want to do all this when just updating a 1-level pagetable.
Quoted 8 lines
drivers/vfio/vfio_iommu.c new file +8
-0+static int vfio_iommu_release (struct inode *inode,struct file *filep) +{ +struct vfio_iommu *iommu = filep->private_data; + +vfio_release_iommu (iommu); +return 0 ; +} +
drivers/vfio/vfio_iommu.c line 487
Quoted 10 lines
drivers/vfio/vfio_iommu.c new file +10
-0+static long vfio_iommu_unl_ioctl (struct file *filep, +unsigned int cmd,unsigned long arg) +{ +struct vfio_iommu *iommu = filep->private_data; +int ret = -ENOSYS ; + +if (cmd ==VFIO_IOMMU_GET_FLAGS ) { +u64 flags =VFIO_IOMMU_FLAGS_MAP_ANY ; + + ret =put_user (flags, (u64 __user *)arg);
Um.. flags surely have to come from the IOMMU driver.
Quoted 21 lines
drivers/vfio/vfio_iommu.c new file +21
-0+ }else if (cmd ==VFIO_IOMMU_MAP_DMA ) { +struct vfio_dma_map dm; + +if (copy_from_user (&dm, (void __user *)arg,sizeof dm)) +return -EFAULT ; + + ret =vfio_dma_map_dm (iommu, &dm); + +if (!ret &©_to_user ((void __user *)arg, &dm,sizeof dm)) + ret = -EFAULT ; + + }else if (cmd ==VFIO_IOMMU_UNMAP_DMA ) { +struct vfio_dma_map dm; + +if (copy_from_user (&dm, (void __user *)arg,sizeof dm)) +return -EFAULT ; + + ret =vfio_dma_unmap_dm (iommu, &dm); + +if (!ret &©_to_user ((void __user *)arg, &dm,sizeof dm)) + ret = -EFAULT ;
drivers/vfio/vfio_iommu.c line 519
Quoted 10 lines
drivers/vfio/vfio_iommu.c new file +10
-0+ } +return ret; +} + +#ifdef CONFIG_COMPAT +static long vfio_iommu_compat_ioctl (struct file *filep, +unsigned int cmd,unsigned long arg) +{ + arg = (unsigned long )compat_ptr (arg); +return vfio_iommu_unl_ioctl (filep, cmd, arg);
Um, this only works if the structures are exactly compatible between 32-bit and 64-bit ABIs. I don't think that is always true.
Quoted 48 lines
drivers/vfio/vfio_iommu.c new file +11
-0+} +#endif /* CONFIG_COMPAT */ + +const struct file_operations vfio_iommu_fops = { + .owner =THIS_MODULE , + .release = vfio_iommu_release, + .unlocked_ioctl = vfio_iommu_unl_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = vfio_iommu_compat_ioctl, +#endif +};drivers/vfio/vfio_main.c new file +31
-0@@ -0,0 +1,1151 @@ +/* +* VFIO framework +* +* Copyright (C) 2011 Red Hat, Inc. All rights reserved. +* Author: Alex Williamson <[email protected]> +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License version 2 as +* published by the Free Software Foundation. +* +* Derived from original vfio: +* Copyright 2010 Cisco Systems, Inc. All rights reserved. +* Author: Tom Lyon, [email protected] +*/ + +#include <linux/cdev.h> +#include <linux/compat.h> +#include <linux/device.h> +#include <linux/file.h> +#include <linux/anon_inodes.h> +#include <linux/fs.h> +#include <linux/idr.h> +#include <linux/iommu.h> +#include <linux/mm.h> +#include <linux/module.h> +#include <linux/slab.h> +#include <linux/string.h> +#include <linux/uaccess.h> +#include <linux/vfio.h> +#include <linux/wait.h> +
drivers/vfio/vfio_main.c line 41
Quoted 10 lines
drivers/vfio/vfio_main.c new file +10
-0+#include "vfio_private.h" + +#define DRIVER_VERSION "0.2" +#define DRIVER_AUTHOR "Alex Williamson <[email protected]>" +#define DRIVER_DESC "VFIO - User Level meta-driver" + +static int allow_unsafe_intrs; +module_param (allow_unsafe_intrs, int,0 ); +MODULE_PARM_DESC (allow_unsafe_intrs, +"Allow use of IOMMUs which do not support interrupt remapping" );
This should not be a global option, but part of the AMD/Intel IOMMU specific code. In general it's a question of how strict the IOMMU driver is about isolation when it determines what the groups are, and only the IOMMU driver can know what the possibilities are for its class of hardware.
Quoted 445 lines
drivers/vfio/vfio_main.c new file +445
-0+ +static struct vfio { +dev_t devt; +struct cdev cdev; +struct list_head group_list; +struct mutex lock; +struct kref kref; +struct class *class; +struct idr idr; +wait_queue_head_t release_q; +} vfio; + +static const struct file_operations vfio_group_fops; +extern const struct file_operations vfio_iommu_fops; + +struct vfio_group { +dev_t devt; +unsigned int groupid; +struct bus_type *bus; +struct vfio_iommu *iommu; +struct list_head device_list; +struct list_head iommu_next; +struct list_head group_next; +int refcnt; +}; + +struct vfio_device { +struct device *dev; +const struct vfio_device_ops *ops; +struct vfio_iommu *iommu; +struct vfio_group *group; +struct list_head device_next; +bool attached; +int refcnt; +void *device_data; +}; + +/* +* Helper functions called under vfio.lock +*/ + +/* Return true if any devices within a group are opened */ +static bool __vfio_group_devs_inuse (struct vfio_group *group) +{ +struct list_head *pos; + +list_for_each (pos, &group->device_list) { +struct vfio_device *device; + + device = list_entry(pos, struct vfio_device, device_next); +if (device->refcnt) +return true; + } +return false; +} + +/* Return true if any of the groups attached to an iommu are opened. +* We can only tear apart merged groups when nothing is left open. */ +static bool __vfio_iommu_groups_inuse (struct vfio_iommu *iommu) +{ +struct list_head *pos; + +list_for_each (pos, &iommu->group_list) { +struct vfio_group *group; + + group = list_entry(pos, struct vfio_group, iommu_next); +if (group->refcnt) +return true; + } +return false; +} + +/* An iommu is "in use" if it has a file descriptor open or if any of +* the groups assigned to the iommu have devices open. */ +static bool __vfio_iommu_inuse (struct vfio_iommu *iommu) +{ +struct list_head *pos; + +if (iommu->refcnt) +return true; + +list_for_each (pos, &iommu->group_list) { +struct vfio_group *group; + + group = list_entry(pos, struct vfio_group, iommu_next); + +if (__vfio_group_devs_inuse (group)) +return true; + } +return false; +} + +static void __vfio_group_set_iommu (struct vfio_group *group, +struct vfio_iommu *iommu) +{ +struct list_head *pos; + +if (group->iommu) +list_del (&group->iommu_next); +if (iommu) +list_add (&group->iommu_next, &iommu->group_list); + + group->iommu = iommu; + +list_for_each (pos, &group->device_list) { +struct vfio_device *device; + + device = list_entry(pos, struct vfio_device, device_next); + device->iommu = iommu; + } +} + +static void __vfio_iommu_detach_dev (struct vfio_iommu *iommu, +struct vfio_device *device) +{ +BUG_ON (!iommu->domain && device->attached); + +if (!iommu->domain || !device->attached) +return ; + +iommu_detach_device (iommu->domain, device->dev); + device->attached = false; +} + +static void __vfio_iommu_detach_group (struct vfio_iommu *iommu, +struct vfio_group *group) +{ +struct list_head *pos; + +list_for_each (pos, &group->device_list) { +struct vfio_device *device; + + device = list_entry(pos, struct vfio_device, device_next); +__vfio_iommu_detach_dev (iommu, device); + } +} + +static int __vfio_iommu_attach_dev (struct vfio_iommu *iommu, +struct vfio_device *device) +{ +int ret; + +BUG_ON (device->attached); + +if (!iommu || !iommu->domain) +return -EINVAL ; + + ret =iommu_attach_device (iommu->domain, device->dev); +if (!ret) + device->attached = true; + +return ret; +} + +static int __vfio_iommu_attach_group (struct vfio_iommu *iommu, +struct vfio_group *group) +{ +struct list_head *pos; + +list_for_each (pos, &group->device_list) { +struct vfio_device *device; +int ret; + + device = list_entry(pos, struct vfio_device, device_next); + ret =__vfio_iommu_attach_dev (iommu, device); +if (ret) { +__vfio_iommu_detach_group (iommu, group); +return ret; + } + } +return 0 ; +} + +/* The iommu is viable, ie. ready to be configured, when all the devices +* for all the groups attached to the iommu are bound to their vfio device +* drivers (ex. vfio-pci). This sets the device_data private data pointer. */ +static bool __vfio_iommu_viable (struct vfio_iommu *iommu) +{ +struct list_head *gpos, *dpos; + +list_for_each (gpos, &iommu->group_list) { +struct vfio_group *group; + group = list_entry(gpos, struct vfio_group, iommu_next); + +list_for_each (dpos, &group->device_list) { +struct vfio_device *device; + device =list_entry (dpos, + struct vfio_device, device_next); + +if (!device->device_data) +return false; + } + } +return true; +} + +static void __vfio_close_iommu (struct vfio_iommu *iommu) +{ +struct list_head *pos; + +if (!iommu->domain) +return ; + +list_for_each (pos, &iommu->group_list) { +struct vfio_group *group; + group = list_entry(pos, struct vfio_group, iommu_next); + +__vfio_iommu_detach_group (iommu, group); + } + +vfio_iommu_unmapall (iommu); + +iommu_domain_free (iommu->domain); + iommu->domain =NULL ; + iommu->mm =NULL ; +} + +/* Open the IOMMU. This gates all access to the iommu or device file +* descriptors and sets current->mm as the exclusive user. */ +static int __vfio_open_iommu (struct vfio_iommu *iommu) +{ +struct list_head *pos; +int ret; + +if (!__vfio_iommu_viable (iommu)) +return -EBUSY ; + +if (iommu->domain) +return -EINVAL ; + + iommu->domain =iommu_domain_alloc (iommu->bus); +if (!iommu->domain) +return -EFAULT ; + +list_for_each (pos, &iommu->group_list) { +struct vfio_group *group; + group = list_entry(pos, struct vfio_group, iommu_next); + + ret =__vfio_iommu_attach_group (iommu, group); +if (ret) { +__vfio_close_iommu (iommu); +return ret; + } + } + +if (!allow_unsafe_intrs && + !iommu_domain_has_cap (iommu->domain,IOMMU_CAP_INTR_REMAP )) { +__vfio_close_iommu (iommu); +return -EFAULT ; + } + + iommu->cache = (iommu_domain_has_cap (iommu->domain, +IOMMU_CAP_CACHE_COHERENCY ) !=0 ); + iommu->mm = current->mm; + +return 0 ; +} + +/* Actively try to tear down the iommu and merged groups. If there are no +* open iommu or device fds, we close the iommu. If we close the iommu and +* there are also no open group fds, we can futher dissolve the group to +* iommu association and free the iommu data structure. */ +static int __vfio_try_dissolve_iommu (struct vfio_iommu *iommu) +{ + +if (__vfio_iommu_inuse (iommu)) +return -EBUSY ; + +__vfio_close_iommu (iommu); + +if (!__vfio_iommu_groups_inuse (iommu)) { +struct list_head *pos, *ppos; + +list_for_each_safe (pos, ppos, &iommu->group_list) { +struct vfio_group *group; + + group = list_entry(pos, struct vfio_group, iommu_next); +__vfio_group_set_iommu (group,NULL ); + } + + +kfree (iommu); + } + +return 0 ; +} + +static struct vfio_device *__vfio_lookup_dev (struct device *dev) +{ +struct list_head *gpos; +unsigned int groupid; + +if (iommu_device_group (dev, &groupid)) +return NULL ; + +list_for_each (gpos, &vfio.group_list) { +struct vfio_group *group; +struct list_head *dpos; + + group = list_entry(gpos, struct vfio_group, group_next); + +if (group->groupid != groupid) +continue ; + +list_for_each (dpos, &group->device_list) { +struct vfio_device *device; + + device =list_entry (dpos, + struct vfio_device, device_next); + +if (device->dev == dev) +return device; + } + } +return NULL ; +} + +/* All release paths simply decrement the refcnt, attempt to teardown +* the iommu and merged groups, and wakeup anything that might be +* waiting if we successfully dissolve anything. */ +static int vfio_do_release (int *refcnt,struct vfio_iommu *iommu) +{ +bool wake; + +mutex_lock (&vfio.lock); + + (*refcnt)--; + wake = (__vfio_try_dissolve_iommu (iommu) ==0 ); + +mutex_unlock (&vfio.lock); + +if (wake) +wake_up (&vfio.release_q); + +return 0 ; +} + +/* +* Device fops - passthrough to vfio device driver w/ device_data +*/ +static int vfio_device_release (struct inode *inode,struct file *filep) +{ +struct vfio_device *device = filep->private_data; + +vfio_do_release (&device->refcnt, device->iommu); + + device->ops->put (device->device_data); + +return 0 ; +} + +static long vfio_device_unl_ioctl (struct file *filep, +unsigned int cmd,unsigned long arg) +{ +struct vfio_device *device = filep->private_data; + +return device->ops->ioctl (device->device_data, cmd, arg); +} + +static ssize_t vfio_device_read (struct file *filep,char __user *buf, +size_t count,loff_t *ppos) +{ +struct vfio_device *device = filep->private_data; + +return device->ops->read (device->device_data, buf, count, ppos); +} + +static ssize_t vfio_device_write (struct file *filep,const char __user *buf, +size_t count,loff_t *ppos) +{ +struct vfio_device *device = filep->private_data; + +return device->ops->write (device->device_data, buf, count, ppos); +} + +static int vfio_device_mmap (struct file *filep,struct vm_area_struct *vma) +{ +struct vfio_device *device = filep->private_data; + +return device->ops->mmap (device->device_data, vma); +} + +#ifdef CONFIG_COMPAT +static long vfio_device_compat_ioctl (struct file *filep, +unsigned int cmd,unsigned long arg) +{ + arg = (unsigned long )compat_ptr (arg); +return vfio_device_unl_ioctl (filep, cmd, arg); +} +#endif /* CONFIG_COMPAT */ + +const struct file_operations vfio_device_fops = { + .owner =THIS_MODULE , + .release = vfio_device_release, + .read = vfio_device_read, + .write = vfio_device_write, + .unlocked_ioctl = vfio_device_unl_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = vfio_device_compat_ioctl, +#endif + .mmap = vfio_device_mmap, +}; + +/* +* Group fops +*/ +static int vfio_group_open (struct inode *inode,struct file *filep) +{ +struct vfio_group *group; +int ret =0 ; + +mutex_lock (&vfio.lock); + + group =idr_find (&vfio.idr,iminor (inode)); + +if (!group) { + ret = -ENODEV ; + goto out; + } + + filep->private_data = group; + +if (!group->iommu) { +struct vfio_iommu *iommu; + + iommu =kzalloc (sizeof (*iommu),GFP_KERNEL ); +if (!iommu) { + ret = -ENOMEM ; + goto out; + } +INIT_LIST_HEAD (&iommu->group_list); +INIT_LIST_HEAD (&iommu->dm_list); +mutex_init (&iommu->dgate); + iommu->bus = group->bus; +__vfio_group_set_iommu (group, iommu); + } + group->refcnt++; + +out: +mutex_unlock (&vfio.lock); + +return ret; +} + +static int vfio_group_release (struct inode *inode,struct file *filep)
drivers/vfio/vfio_main.c line 496
Quoted 10 lines
drivers/vfio/vfio_main.c new file +10
-0+{ +struct vfio_group *group = filep->private_data; + +return vfio_do_release (&group->refcnt, group->iommu); +} + +/* Attempt to merge the group pointed to by fd into group. The merge-ee +* group must not have an iommu or any devices open because we cannot +* maintain that context across the merge. The merge-er group can be +* in use. */
Yeah, so merge-er group in use still has its problems, because it could affect what the IOMMU is capable of.
Quoted 8 lines
drivers/vfio/vfio_main.c new file +8
-0+static int vfio_group_merge (struct vfio_group *group,int fd) +{ +struct vfio_group *new; +struct vfio_iommu *old_iommu; +struct file *file; +int ret =0 ; +bool opened = false; +
drivers/vfio/vfio_main.c line 514
Quoted 10 lines
drivers/vfio/vfio_main.c new file +10
-0+mutex_lock (&vfio.lock); + + file =fget (fd); +if (!file) { + ret = -EBADF ; + goto out_noput; + } + +/* Sanity check, is this really our fd? */ +if (file->f_op != &vfio_group_fops) {
This should be a WARN_ON or BUG_ON rather than just an error return, surely.
Quoted 108 lines
drivers/vfio/vfio_main.c new file +108
-0+ ret = -EINVAL ; + goto out; + } + + new = file->private_data; + +if (!new || new == group || !new->iommu || + new->iommu->domain || new->bus != group->bus) { + ret = -EINVAL ; + goto out; + } + +/* We need to attach all the devices to each domain separately +* in order to validate that the capabilities match for both. */ + ret =__vfio_open_iommu (new->iommu); +if (ret) + goto out; + +if (!group->iommu->domain) { + ret =__vfio_open_iommu (group->iommu); +if (ret) + goto out; + opened = true; + } + +/* If cache coherency doesn't match we'd potentialy need to +* remap existing iommu mappings in the merge-er domain. +* Poor return to bother trying to allow this currently. */ +if (iommu_domain_has_cap (group->iommu->domain, +IOMMU_CAP_CACHE_COHERENCY ) != +iommu_domain_has_cap (new->iommu->domain, +IOMMU_CAP_CACHE_COHERENCY )) { +__vfio_close_iommu (new->iommu); +if (opened) +__vfio_close_iommu (group->iommu); + ret = -EINVAL ; + goto out; + } + +/* Close the iommu for the merge-ee and attach all its devices +* to the merge-er iommu. */ +__vfio_close_iommu (new->iommu); + + ret =__vfio_iommu_attach_group (group->iommu, new); +if (ret) + goto out; + +/* set_iommu unlinks new from the iommu, so save a pointer to it */ + old_iommu = new->iommu; +__vfio_group_set_iommu (new, group->iommu); +kfree (old_iommu); + +out: +fput (file); +out_noput: +mutex_unlock (&vfio.lock); +return ret; +} + +/* Unmerge the group pointed to by fd from group. */ +static int vfio_group_unmerge (struct vfio_group *group,int fd) +{ +struct vfio_group *new; +struct vfio_iommu *new_iommu; +struct file *file; +int ret =0 ; + +/* Since the merge-out group is already opened, it needs to +* have an iommu struct associated with it. */ + new_iommu =kzalloc (sizeof (*new_iommu),GFP_KERNEL ); +if (!new_iommu) +return -ENOMEM ; + +INIT_LIST_HEAD (&new_iommu->group_list); +INIT_LIST_HEAD (&new_iommu->dm_list); +mutex_init (&new_iommu->dgate); + new_iommu->bus = group->bus; + +mutex_lock (&vfio.lock); + + file =fget (fd); +if (!file) { + ret = -EBADF ; + goto out_noput; + } + +/* Sanity check, is this really our fd? */ +if (file->f_op != &vfio_group_fops) { + ret = -EINVAL ; + goto out; + } + + new = file->private_data; +if (!new || new == group || new->iommu != group->iommu) { + ret = -EINVAL ; + goto out; + } + +/* We can't merge-out a group with devices still in use. */ +if (__vfio_group_devs_inuse (new)) { + ret = -EBUSY ; + goto out; + } + +__vfio_iommu_detach_group (group->iommu, new); +__vfio_group_set_iommu (new, new_iommu); + +out:
drivers/vfio/vfio_main.c line 632
Quoted 10 lines
drivers/vfio/vfio_main.c new file +10
-0+fput (file); +out_noput: +if (ret) +kfree (new_iommu); +mutex_unlock (&vfio.lock); +return ret; +} + +/* Get a new iommu file descriptor. This will open the iommu, setting +* the current->mm ownership if it's not already set. */
I know I've had this explained to me several times before, but I've forgotten again. Why do we need to wire the iommu to an mm?
Quoted 19 lines
drivers/vfio/vfio_main.c new file +19
-0+static int vfio_group_get_iommu_fd (struct vfio_group *group) +{ +int ret =0 ; + +mutex_lock (&vfio.lock); + +if (!group->iommu->domain) { + ret =__vfio_open_iommu (group->iommu); +if (ret) + goto out; + } + + ret =anon_inode_getfd ("[vfio-iommu]" , &vfio_iommu_fops, + group->iommu,O_RDWR ); +if (ret <0 ) + goto out; + + group->iommu->refcnt++; +out:
drivers/vfio/vfio_main.c line 661
Quoted 10 lines
drivers/vfio/vfio_main.c new file +10
-0+mutex_unlock (&vfio.lock); +return ret; +} + +/* Get a new device file descriptor. This will open the iommu, setting +* the current->mm ownership if it's not already set. It's difficult to +* specify the requirements for matching a user supplied buffer to a +* device, so we use a vfio driver callback to test for a match. For +* PCI, dev_name(dev) is unique, but other drivers may require including +* a parent device string. */
At some point we probably want an interface to enumerate the devices too, but that can probably wait.
Quoted 692 lines
drivers/vfio/vfio_main.c new file +490
-0+static int vfio_group_get_device_fd (struct vfio_group *group,char *buf) +{ +struct vfio_iommu *iommu = group->iommu; +struct list_head *gpos; +int ret = -ENODEV ; + +mutex_lock (&vfio.lock); + +if (!iommu->domain) { + ret =__vfio_open_iommu (iommu); +if (ret) + goto out; + } + +list_for_each (gpos, &iommu->group_list) { +struct list_head *dpos; + + group = list_entry(gpos, struct vfio_group, iommu_next); + +list_for_each (dpos, &group->device_list) { +struct vfio_device *device; + + device =list_entry (dpos, + struct vfio_device, device_next); + +if (device->ops->match (device->dev, buf)) { +struct file *file; + +if (device->ops->get (device->device_data)) { + ret = -EFAULT ; + goto out; + } + +/* We can't use anon_inode_getfd(), like above +* because we need to modify the f_mode flags +* directly to allow more than just ioctls */ + ret =get_unused_fd (); +if (ret <0 ) { + device->ops->put (device->device_data); + goto out; + } + + file =anon_inode_getfile ("[vfio-device]" , + &vfio_device_fops, + device,O_RDWR ); +if (IS_ERR (file)) { +put_unused_fd (ret); + ret =PTR_ERR (file); + device->ops->put (device->device_data); + goto out; + } + +/* Todo: add an anon_inode interface to do +* this. Appears to be missing by lack of +* need rather than explicitly prevented. +* Now there's need. */ + file->f_mode |= (FMODE_LSEEK | +FMODE_PREAD | +FMODE_PWRITE ); + +fd_install (ret, file); + + device->refcnt++; + goto out; + } + } + } +out: +mutex_unlock (&vfio.lock); +return ret; +} + +static long vfio_group_unl_ioctl (struct file *filep, +unsigned int cmd,unsigned long arg) +{ +struct vfio_group *group = filep->private_data; + +if (cmd ==VFIO_GROUP_GET_FLAGS ) { +u64 flags =0 ; + +mutex_lock (&vfio.lock); +if (__vfio_iommu_viable (group->iommu)) + flags |=VFIO_GROUP_FLAGS_VIABLE ; +mutex_unlock (&vfio.lock); + +if (group->iommu->mm) + flags |=VFIO_GROUP_FLAGS_MM_LOCKED ; + +return put_user (flags, (u64 __user *)arg); + } + +/* Below commands are restricted once the mm is set */ +if (group->iommu->mm && group->iommu->mm != current->mm) +return -EPERM ; + +if (cmd ==VFIO_GROUP_MERGE || cmd ==VFIO_GROUP_UNMERGE ) { +int fd; + +if (get_user (fd, (int __user *)arg)) +return -EFAULT ; +if (fd <0 ) +return -EINVAL ; + +if (cmd ==VFIO_GROUP_MERGE ) +return vfio_group_merge (group, fd); +else +return vfio_group_unmerge (group, fd); + }else if (cmd ==VFIO_GROUP_GET_IOMMU_FD ) { +return vfio_group_get_iommu_fd (group); + }else if (cmd ==VFIO_GROUP_GET_DEVICE_FD ) { +char *buf; +int ret; + + buf =strndup_user ((const char __user *)arg,PAGE_SIZE ); +if (IS_ERR (buf)) +return PTR_ERR (buf); + + ret =vfio_group_get_device_fd (group, buf); +kfree (buf); +return ret; + } + +return -ENOSYS ; +} + +#ifdef CONFIG_COMPAT +static long vfio_group_compat_ioctl (struct file *filep, +unsigned int cmd,unsigned long arg) +{ + arg = (unsigned long )compat_ptr (arg); +return vfio_group_unl_ioctl (filep, cmd, arg); +} +#endif /* CONFIG_COMPAT */ + +static const struct file_operations vfio_group_fops = { + .owner =THIS_MODULE , + .open = vfio_group_open, + .release = vfio_group_release, + .unlocked_ioctl = vfio_group_unl_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = vfio_group_compat_ioctl, +#endif +}; + +/* iommu fd release hook */ +int vfio_release_iommu (struct vfio_iommu *iommu) +{ +return vfio_do_release (&iommu->refcnt, iommu); +} + +/* +* VFIO driver API +*/ + +/* Add a new device to the vfio framework with associated vfio driver +* callbacks. This is the entry point for vfio drivers to register devices. */ +int vfio_group_add_dev (struct device *dev,const struct vfio_device_ops *ops) +{ +struct list_head *pos; +struct vfio_group *group =NULL ; +struct vfio_device *device =NULL ; +unsigned int groupid; +int ret =0 ; +bool new_group = false; + +if (!ops) +return -EINVAL ; + +if (iommu_device_group (dev, &groupid)) +return -ENODEV ; + +mutex_lock (&vfio.lock); + +list_for_each (pos, &vfio.group_list) { + group = list_entry(pos, struct vfio_group, group_next); +if (group->groupid == groupid) +break ; + group =NULL ; + } + +if (!group) { +int minor; + +if (unlikely (idr_pre_get (&vfio.idr,GFP_KERNEL ) ==0 )) { + ret = -ENOMEM ; + goto out; + } + + group =kzalloc (sizeof (*group),GFP_KERNEL ); +if (!group) { + ret = -ENOMEM ; + goto out; + } + + group->groupid = groupid; +INIT_LIST_HEAD (&group->device_list); + + ret =idr_get_new (&vfio.idr, group, &minor); +if (ret ==0 && minor >MINORMASK ) { +idr_remove (&vfio.idr, minor); +kfree (group); + ret = -ENOSPC ; + goto out; + } + + group->devt =MKDEV (MAJOR (vfio.devt), minor); +device_create (vfio.class,NULL , group->devt, + group,"%u" , groupid); + + group->bus = dev->bus; +list_add (&group->group_next, &vfio.group_list); + new_group = true; + }else { +if (group->bus != dev->bus) { +printk (KERN_WARNING +"Error: IOMMU group ID conflict. Group ID %u " +"on both bus %s and %s\n" , groupid, + group->bus->name, dev->bus->name); + ret = -EFAULT ; + goto out; + } + +list_for_each (pos, &group->device_list) { + device =list_entry (pos, + struct vfio_device, device_next); +if (device->dev == dev) +break ; + device =NULL ; + } + } + +if (!device) { +if (__vfio_group_devs_inuse (group) || + (group->iommu && group->iommu->refcnt)) { +printk (KERN_WARNING +"Adding device %s to group %u while group is already in use!!\n" , +dev_name (dev), group->groupid); +/* XXX How to prevent other drivers from claiming? */ + } + + device =kzalloc (sizeof (*device),GFP_KERNEL ); +if (!device) { +/* If we just created this group, tear it down */ +if (new_group) { +list_del (&group->group_next); +device_destroy (vfio.class, group->devt); +idr_remove (&vfio.idr,MINOR (group->devt)); +kfree (group); + } + ret = -ENOMEM ; + goto out; + } + +list_add (&device->device_next, &group->device_list); + device->dev = dev; + device->ops = ops; + device->iommu = group->iommu;/* NULL if new */ +__vfio_iommu_attach_dev (group->iommu, device); + } +out: +mutex_unlock (&vfio.lock); +return ret; +} +EXPORT_SYMBOL_GPL (vfio_group_add_dev); + +/* Remove a device from the vfio framework */ +void vfio_group_del_dev (struct device *dev) +{ +struct list_head *pos; +struct vfio_group *group =NULL ; +struct vfio_device *device =NULL ; +unsigned int groupid; + +if (iommu_device_group (dev, &groupid)) +return ; + +mutex_lock (&vfio.lock); + +list_for_each (pos, &vfio.group_list) { + group = list_entry(pos, struct vfio_group, group_next); +if (group->groupid == groupid) +break ; + group =NULL ; + } + +if (!group) + goto out; + +list_for_each (pos, &group->device_list) { + device = list_entry(pos, struct vfio_device, device_next); +if (device->dev == dev) +break ; + device =NULL ; + } + +if (!device) + goto out; + +BUG_ON (device->refcnt); + +if (device->attached) +__vfio_iommu_detach_dev (group->iommu, device); + +list_del (&device->device_next); +kfree (device); + +/* If this was the only device in the group, remove the group. +* Note that we intentionally unmerge empty groups here if the +* group fd isn't opened. */ +if (list_empty (&group->device_list) && group->refcnt ==0 ) { +struct vfio_iommu *iommu = group->iommu; + +if (iommu) { +__vfio_group_set_iommu (group,NULL ); +__vfio_try_dissolve_iommu (iommu); + } + +device_destroy (vfio.class, group->devt); +idr_remove (&vfio.idr,MINOR (group->devt)); +list_del (&group->group_next); +kfree (group); + } +out: +mutex_unlock (&vfio.lock); +} +EXPORT_SYMBOL_GPL (vfio_group_del_dev); + +/* When a device is bound to a vfio device driver (ex. vfio-pci), this +* entry point is used to mark the device usable (viable). The vfio +* device driver associates a private device_data struct with the device +* here, which will later be return for vfio_device_fops callbacks. */ +int vfio_bind_dev (struct device *dev,void *device_data) +{ +struct vfio_device *device; +int ret = -EINVAL ; + +BUG_ON (!device_data); + +mutex_lock (&vfio.lock); + + device =__vfio_lookup_dev (dev); + +BUG_ON (!device); + + ret =dev_set_drvdata (dev, device); +if (!ret) + device->device_data = device_data; + +mutex_unlock (&vfio.lock); +return ret; +} +EXPORT_SYMBOL_GPL (vfio_bind_dev); + +/* A device is only removeable if the iommu for the group is not in use. */ +static bool vfio_device_removeable (struct vfio_device *device) +{ +bool ret = true; + +mutex_lock (&vfio.lock); + +if (device->iommu &&__vfio_iommu_inuse (device->iommu)) + ret = false; + +mutex_unlock (&vfio.lock); +return ret; +} + +/* Notify vfio that a device is being unbound from the vfio device driver +* and return the device private device_data pointer. If the group is +* in use, we need to block or take other measures to make it safe for +* the device to be removed from the iommu. */ +void *vfio_unbind_dev (struct device *dev) +{ +struct vfio_device *device =dev_get_drvdata (dev); +void *device_data; + +BUG_ON (!device); + +again: +if (!vfio_device_removeable (device)) { +/* XXX signal for all devices in group to be removed or +* resort to killing the process holding the device fds. +* For now just block waiting for releases to wake us. */ +wait_event (vfio.release_q,vfio_device_removeable (device)); + } + +mutex_lock (&vfio.lock); + +/* Need to re-check that the device is still removeable under lock. */ +if (device->iommu &&__vfio_iommu_inuse (device->iommu)) { +mutex_unlock (&vfio.lock); + goto again; + } + + device_data = device->device_data; + + device->device_data =NULL ; +dev_set_drvdata (dev,NULL ); + +mutex_unlock (&vfio.lock); +return device_data; +} +EXPORT_SYMBOL_GPL (vfio_unbind_dev); + +/* +* Module/class support +*/ +static void vfio_class_release (struct kref *kref) +{ +class_destroy (vfio.class); + vfio.class =NULL ; +} + +static char *vfio_devnode (struct device *dev,mode_t *mode) +{ +return kasprintf (GFP_KERNEL ,"vfio/%s" ,dev_name (dev)); +} + +static int __init vfio_init (void ) +{ +int ret; + +idr_init (&vfio.idr); +mutex_init (&vfio.lock); +INIT_LIST_HEAD (&vfio.group_list); +init_waitqueue_head (&vfio.release_q); + +kref_init (&vfio.kref); + vfio.class =class_create (THIS_MODULE ,"vfio" ); +if (IS_ERR (vfio.class)) { + ret =PTR_ERR (vfio.class); + goto err_class; + } + + vfio.class->devnode = vfio_devnode; + +/* FIXME - how many minors to allocate... all of them! */ + ret =alloc_chrdev_region (&vfio.devt,0 ,MINORMASK ,"vfio" ); +if (ret) + goto err_chrdev; + +cdev_init (&vfio.cdev, &vfio_group_fops); + ret =cdev_add (&vfio.cdev, vfio.devt,MINORMASK ); +if (ret) + goto err_cdev; + +pr_info (DRIVER_DESC " version: " DRIVER_VERSION "\n" ); + +return 0 ; + +err_cdev: +unregister_chrdev_region (vfio.devt,MINORMASK ); +err_chrdev: +kref_put (&vfio.kref, vfio_class_release); +err_class: +return ret; +} + +static void __exit vfio_cleanup(void) +{ +struct list_head *gpos, *gppos; + +list_for_each_safe (gpos, gppos, &vfio.group_list) { +struct vfio_group *group; +struct list_head *dpos, *dppos; + + group = list_entry(gpos, struct vfio_group, group_next); + +list_for_each_safe (dpos, dppos, &group->device_list) { +struct vfio_device *device; + + device =list_entry (dpos, + struct vfio_device, device_next); +vfio_group_del_dev (device->dev); + } + } + +idr_destroy (&vfio.idr); +cdev_del (&vfio.cdev); +unregister_chrdev_region (vfio.devt,MINORMASK ); +kref_put (&vfio.kref, vfio_class_release); +} + +module_init (vfio_init); +module_exit (vfio_cleanup); + +MODULE_VERSION (DRIVER_VERSION ); +MODULE_LICENSE ("GPL v2" ); +MODULE_AUTHOR (DRIVER_AUTHOR ); +MODULE_DESCRIPTION (DRIVER_DESC );drivers/vfio/vfio_private.h new file +34
-0@@ -0,0 +1,34 @@ +/* +* Copyright (C) 2011 Red Hat, Inc. All rights reserved. +* Author: Alex Williamson <[email protected]> +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License version 2 as +* published by the Free Software Foundation. +* +* Derived from original vfio: +* Copyright 2010 Cisco Systems, Inc. All rights reserved. +* Author: Tom Lyon, [email protected] +*/ + +#include <linux/list.h> +#include <linux/mutex.h> + +#ifndef VFIO_PRIVATE_H +#define VFIO_PRIVATE_H + +struct vfio_iommu { +struct iommu_domain *domain; +struct bus_type *bus; +struct mutex dgate; +struct list_head dm_list; +struct mm_struct *mm; +struct list_head group_list; +int refcnt; +bool cache; +}; + +extern int vfio_release_iommu (struct vfio_iommu *iommu); +extern void vfio_iommu_unmapall (struct vfio_iommu *iommu); + +#endif /* VFIO_PRIVATE_H */ include/linux/vfio.h new file +155
-0@@ -0,0 +1,155 @@ +/* +* Copyright 2010 Cisco Systems, Inc. All rights reserved. +* Author: Tom Lyon, [email protected] +* +* This program is free software; you may redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation; version 2 of the License. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +* +* Portions derived from drivers/uio/uio.c: +* Copyright(C) 2005, Benedikt Spranger <[email protected]> +* Copyright(C) 2005, Thomas Gleixner <[email protected]> +* Copyright(C) 2006, Hans J. Koch <[email protected]> +* Copyright(C) 2006, Greg Kroah-Hartman <[email protected]> +* +* Portions derived from drivers/uio/uio_pci_generic.c: +* Copyright (C) 2009 Red Hat, Inc. +* Author: Michael S. Tsirkin <[email protected]> +*/ +#include <linux/types.h> + +#ifndef VFIO_H +#define VFIO_H + +#ifdef __KERNEL__ + +struct vfio_device_ops { +bool (*match)(struct device *,char *); +int (*get)(void *); +void (*put)(void *); +ssize_t (*read)(void *,char __user *, +size_t ,loff_t *); +ssize_t (*write)(void *,const char __user *, +size_t ,loff_t *); +long (*ioctl)(void *,unsigned int ,unsigned long ); +int (*mmap)(void *,struct vm_area_struct *); +}; + +extern int vfio_group_add_dev (struct device *device, +const struct vfio_device_ops *ops); +extern void vfio_group_del_dev (struct device *device); +extern int vfio_bind_dev (struct device *device,void *device_data); +extern void *vfio_unbind_dev (struct device *device); + +#endif /* __KERNEL__ */ + +/* +* VFIO driver - allow mapping and use of certain devices +* in unprivileged user processes. (If IOMMU is present) +* Especially useful for Virtual Function parts of SR-IOV devices +*/ + + +/* Kernel & User level defines for ioctls */ + +#define VFIO_GROUP_GET_FLAGS _IOR(';', 100, __u64) +#define VFIO_GROUP_FLAGS_VIABLE (1 << 0) +#define VFIO_GROUP_FLAGS_MM_LOCKED (1 << 1) +#define VFIO_GROUP_MERGE _IOW(';', 101, int) +#define VFIO_GROUP_UNMERGE _IOW(';', 102, int) +#define VFIO_GROUP_GET_IOMMU_FD _IO(';', 103) +#define VFIO_GROUP_GET_DEVICE_FD _IOW(';', 104, char *) + +/* +* Structure for DMA mapping of user buffers +* vaddr, dmaaddr, and size must all be page aligned +*/ +struct vfio_dma_map { +__u64 len;/* length of structure */ +__u64 vaddr;/* process virtual addr */ +__u64 dmaaddr;/* desired and/or returned dma address */ +__u64 size;/* size in bytes */ +__u64 flags; +#define VFIO_DMA_MAP_FLAG_WRITE (1 << 0)/* req writeable DMA mem */ +}; + +#define VFIO_IOMMU_GET_FLAGS _IOR(';', 105, __u64) +/* Does the IOMMU support mapping any IOVA to any virtual address? */ +#define VFIO_IOMMU_FLAGS_MAP_ANY (1 << 0) +#define VFIO_IOMMU_MAP_DMA _IOWR(';', 106, struct vfio_dma_map) +#define VFIO_IOMMU_UNMAP_DMA _IOWR(';', 107, struct vfio_dma_map) + +#define VFIO_DEVICE_GET_FLAGS _IOR(';', 108, __u64) +#define VFIO_DEVICE_FLAGS_PCI (1 << 0) +#define VFIO_DEVICE_FLAGS_DT (1 << 1) +#define VFIO_DEVICE_FLAGS_RESET (1 << 2) +#define VFIO_DEVICE_GET_NUM_REGIONS _IOR(';', 109, int) + +struct vfio_region_info { +__u32 len;/* length of structure */ +__u32 index;/* region number */ +__u64 size;/* size in bytes of region */ +__u64 offset;/* start offset of region */ +__u64 flags; +#define VFIO_REGION_INFO_FLAG_MMAP (1 << 0) +#define VFIO_REGION_INFO_FLAG_RO (1 << 1) +#define VFIO_REGION_INFO_FLAG_PHYS_VALID (1 << 2) +__u64 phys;/* physical address of region */ +}; + +#define VFIO_DEVICE_GET_REGION_INFO _IOWR(';', 110, struct vfio_region_info) + +#define VFIO_DEVICE_GET_NUM_IRQS _IOR(';', 111, int) + +struct vfio_irq_info { +__u32 len;/* length of structure */ +__u32 index;/* IRQ number */ +__u32 count;/* number of individual IRQs */ +__u32 flags; +#define VFIO_IRQ_INFO_FLAG_LEVEL (1 << 0) +}; + +#define VFIO_DEVICE_GET_IRQ_INFO _IOWR(';', 112, struct vfio_irq_info) + +/* Set IRQ eventfds, arg[0] = index, arg[1] = count, arg[2-n] = eventfds */ +#define VFIO_DEVICE_SET_IRQ_EVENTFDS _IOW(';', 113, int) + +/* Unmask IRQ index, arg[0] = index */ +#define VFIO_DEVICE_UNMASK_IRQ _IOW(';', 114, int) + +/* Set unmask eventfd, arg[0] = index, arg[1] = eventfd */ +#define VFIO_DEVICE_SET_UNMASK_IRQ_EVENTFD _IOW(';', 115, int) + +#define VFIO_DEVICE_RESET _IO(';', 116) + +struct vfio_dtpath { +__u32 len;/* length of structure */ +__u32 index; +__u64 flags; +#define VFIO_DTPATH_FLAGS_REGION (1 << 0) +#define VFIO_DTPATH_FLAGS_IRQ (1 << 1) +char *path; +}; +#define VFIO_DEVICE_GET_DTPATH _IOWR(';', 117, struct vfio_dtpath) + +struct vfio_dtindex { +__u32 len;/* length of structure */ +__u32 index; +__u32 prop_type; +__u32 prop_index; +__u64 flags; +#define VFIO_DTINDEX_FLAGS_REGION (1 << 0) +#define VFIO_DTINDEX_FLAGS_IRQ (1 << 1) +}; +#define VFIO_DEVICE_GET_DTINDEX _IOWR(';', 118, struct vfio_dtindex) + +#endif /* VFIO_H */
Signature · 4 lines
David Gibson | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you. NOT _the_ _other_ | _way_ _around_! http://www.ozlabs.org/~dgibson
Quoted 18 lines · David Gibson
Quoted 6 lines · Alex Williamson
Documentation/vfio.txt new file +0
-0Documentation/vfio.txt line 10
Quoted 10 lines
Documentation/vfio.txt new file +10
-0@@ -0,0 +1,304 @@ +VFIO - "Virtual Function I/O"[1] +------------------------------------------------------------------------------- +Many modern system now provide DMA and interrupt remapping facilities +to help ensure I/O devices behave within the boundaries they've been +allotted. This includes x86 hardware with AMD-Vi and Intel VT-d as +well as POWER systems with Partitionable Endpoints (PEs) and even +embedded powerpc systems (technology name unknown). The VFIO driver +is an IOMMU/device agnostic framework for exposing direct device +access to userspace, in a secure, IOMMU protected environment. In +other words, this allows safe, non-privileged, userspace drivers.
Quoted 7 lines
It's perhaps worth emphasisng that "safe" depends on the hardware being sufficiently well behaved. BenH, I know, thinks there are a *lot* of cards that, e.g. have debug registers that allow a backdoor to their own config space via MMIO, which would bypass vfio's filtering of config space access. And that's before we even get into the varying degrees of completeness in the isolation provided by different IOMMUs.
Fair enough. I know Tom had emphasized "well behaved" in the original doc. Virtual functions are probably the best indicator of well behaved.
Quoted 5 lines
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+Why do we want that? Virtual machines often make use of direct device +access ("device assignment") when configured for the highest possible +I/O performance. From a device and host perspective, this simply turns +the VM into a userspace driver, with the benefits of significantly +reduced latency, higher bandwidth, and direct use of bare-metal device
Quoted 8 lines
Documentation/vfio.txt line 22
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+drivers[2]. + +Some applications, particularly in the high performance computing +field, also benefit from low-overhead, direct device access from +userspace. Examples include network adapters (often non-TCP/IP based) +and compute accelerators. Previous to VFIO, these drivers needed tos/Previous/Prior/ although that may be a .us vs .au usage thing.
Same difference, AFAICT.
Quoted 30 lines
Quoted 30 lines
Documentation/vfio.txt new file +30
-0+go through the full development cycle to become proper upstream driver, +be maintained out of tree, or make use of the UIO framework, which +has no notion of IOMMU protection, limited interrupt support, and +requires root privileges to access things like PCI configuration space. + +The VFIO driver framework intends to unify these, replacing both the +KVM PCI specific device assignment currently used as well as provide +a more secure, more featureful userspace driver environment than UIO. + +Groups, Devices, IOMMUs, oh my +------------------------------------------------------------------------------- + +A fundamental component of VFIO is the notion of IOMMU groups. IOMMUs +can't always distinguish transactions from each individual device in +the system. Sometimes this is because of the IOMMU design, such as with +PEs, other times it's caused by the I/O topology, for instance a +PCIe-to-PCI bridge masking all devices behind it. We call the sets of +devices created by these restictions IOMMU groups (or just "groups" for +this document). + +The IOMMU cannot distiguish transactions between the individual devices +within the group, therefore the group is the basic unit of ownership for +a userspace process. Because of this, groups are also the primary +interface to both devices and IOMMU domains in VFIO. + +The VFIO representation of groups is created as devices are added into +the framework by a VFIO bus driver. The vfio-pci module is an example +of a bus driver. This module registers devices along with a set of bus +specific callbacks with the VFIO core. These callbacks provide the +interfaces later used for device access. As each new group is created,
Quoted 8 lines
Documentation/vfio.txt line 54
Quoted 2 lines
Documentation/vfio.txt new file +2
-0+as determined by iommu_device_group(), VFIO creates a /dev/vfio/$GROUP +character device.Ok.. so, the fact that it's called "vfio-pci" suggests that the VFIO
bus driver is per bus type, not per bus instance. But grouping
constraints could be per bus instance, if you have a couple of different models of PCI host bridge with IOMMUs of different capabilities built in, for example.
Yes, vfio-pci manages devices on the pci_bus_type; per type, not per bus instance. IOMMUs also register drivers per bus type, not per bus instance. The IOMMU driver is free to impose any constraints it wants.
Quoted 38 lines
Quoted 25 lines
Documentation/vfio.txt new file +25
-0+In addition to the device enumeration and callbacks, the VFIO bus driver +also provides a traditional device driver and is able to bind to devices +on it's bus. When a device is bound to the bus driver it's available to +VFIO. When all the devices within a group are bound to their bus drivers, +the group becomes "viable" and a user with sufficient access to the VFIO +group chardev can obtain exclusive access to the set of group devices. + +As documented in linux/vfio.h, several ioctls are provided on the +group chardev: + +#define VFIO_GROUP_GET_FLAGS _IOR(';', 100, __u64) + #define VFIO_GROUP_FLAGS_VIABLE (1 << 0) + #define VFIO_GROUP_FLAGS_MM_LOCKED (1 << 1) +#define VFIO_GROUP_MERGE _IOW(';', 101, int) +#define VFIO_GROUP_UNMERGE _IOW(';', 102, int) +#define VFIO_GROUP_GET_IOMMU_FD _IO(';', 103) +#define VFIO_GROUP_GET_DEVICE_FD _IOW(';', 104, char *) + +The last two ioctls return new file descriptors for accessing +individual devices within the group and programming the IOMMU. Each of +these new file descriptors provide their own set of file interfaces. +These ioctls will fail if any of the devices within the group are not +bound to their VFIO bus driver. Additionally, when either of these +interfaces are used, the group is then bound to the struct_mm of the +caller. The GET_FLAGS ioctl can be used to view the state of the group.Documentation/vfio.txt
Quoted 10 lines
Documentation/vfio.txt new file +10
-0+ +When either the GET_IOMMU_FD or GET_DEVICE_FD ioctls are invoked, a +new IOMMU domain is created and all of the devices in the group are +attached to it. This is the only way to ensure full IOMMU isolation +of the group, but potentially wastes resources and cycles if the user +intends to manage multiple groups with the same set of IOMMU mappings. +VFIO therefore provides a group MERGE and UNMERGE interface, which +allows multiple groups to share an IOMMU domain. Not all IOMMUs allow +arbitrary groups to be merged, so the user should assume merging is +opportunistic.I do not think "opportunistic" means what you think it means..
Quoted 11 lines
Quoted 9 lines
Documentation/vfio.txt new file +7
-0A new group, with no open device or IOMMU file +descriptors, can be merged into an existing, in-use, group using the +MERGE ioctl. A merged group can be unmerged using the UNMERGE ioctl +once all of the device file descriptors for the group being merged +"out" are closed. + +When groups are merged, the GET_IOMMU_FD and GET_DEVICE_FD ioctls are +essentially fungible between group file descriptors (ie. if deviceA
IDNT "fungible" MWYTIM, either.
Hmm, feel free to suggest. Maybe we're hitting .us vs .au connotation.
Quoted 13 lines
Documentation/vfio.txt line 103
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+is in group X, and X is merged with Y, a file descriptor for A can be +retrieved using GET_DEVICE_FD on Y. Likewise, GET_IOMMU_FD returns a +file descriptor referencing the same internal IOMMU object from either +X or Y). Merged groups can be dissolved either explictly with UNMERGE +or automatically when ALL file descriptors for the merged group are +closed (all IOMMUs, all devices, all groups).Blech. I'm really not liking this merge/unmerge API as it stands, it's horribly confusing. At the very least, we need some better terminology. We need some term for the metagroups; supergroups; iommu domains or-at-least-they-will-be-once-we-open-the-iommu or whathaveyous.
Quoted 5 lines
The first confusing thing about this interface is that each open group handle actually refers to two different things; the original group you opened and the metagroup it's a part of. For the
GET_IOMMU_FDandGET_DEVICE_FDoperations, you're using the metagroup and two "merged" group handles are interchangeable.
Fungible, even ;)
Quoted 2 lines
For other MERGE and especially
UNMERGE operations, it matters which is the original group.
If I stick two LEGO blocks together, I need to identify the individual block I want to remove to pull them back apart...
Quoted 4 lines
The semantics of "merge" and "unmerge" under those names are really non-obvious. Merge kind of has to merge two whole metagroups, but it's unclear if unmerge reverses one merge, or just takes out one (atom) group. These operations need better names, at least.
Christian suggested a change to UNMERGE that we do not need to specify a group to unmerge "from". This makes it more like a list implementation except there's no defined list_head. Any member of the list can pull in a new entry. Calling UNMERGE on any member extracts that member.
Quoted 10 lines
Then it's unclear what order you can do various operations, and which order you can open and close various things. You can kind of figure it out but it takes far more thinking than it should.
So at the _very_ least, we need to invent new terminology and find a much better way of describing this API's semantics. I still think an entirely different interface, where metagroups are created from outside with a lifetime that's not tied to an fd would be a better idea.
As we've discussed previously, configfs provides part of this, but has no ioctl support. It doesn't make sense to me to go play with groups in configfs, but then still interact with them via a char dev. It also splits the ownership model and makes it harder to enforce who gets to interact with the devices vs who gets to manipulate groups. The current model really isn't that complicated, imho. As always, feel free to suggest specific models. If you have a specific terminology other than MERGE, please suggest.
Quoted 5 lines
Now, you specify that you can't use a group as the second argument of a merge if it already has an open iommu, but it's not clear from the doc if you can merge things into a group with an open iommu.
From above:
A new group, with no open device or IOMMU file descriptors, can be merged into an existing, in-use, group using the MERGE ioctl.
^^^^^^
Quoted 4 lines
Banning
this would make life simpler, because the IOMMU's effective capabilities may change if you add more devices to the domain. That's yet another non-obvious constraint in the interface ordering, though.
Banning this would prevent using merged groups with hotplug, which I consider to be a primary use case.
Quoted 6 lines
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+The IOMMU file descriptor provides this set of ioctls: + +#define VFIO_IOMMU_GET_FLAGS _IOR(';', 105, __u64) + #define VFIO_IOMMU_FLAGS_MAP_ANY (1 << 0) +#define VFIO_IOMMU_MAP_DMA _IOWR(';', 106, struct vfio_dma_map) +#define VFIO_IOMMU_UNMAP_DMA _IOWR(';', 107, struct vfio_dma_map)
Quoted 8 lines
Quoted 5 lines
Documentation/vfio.txt new file +4
-0+ +The GET_FLAGS ioctl returns basic information about the IOMMU domain. +We currently only support IOMMU domains that are able to map any +virtual address to any IOVA. This is indicated by the MAP_ANYflag.
So. I tend to think of an IOMMU mapping IOVAs to memory pages, rather than memory pages to IOVAs.
I do too, not sure why I wrote it that way, will fix.
Quoted 6 lines
The IOMMU itself, of course maps to
physical addresses, and the meaning of "virtual address" in this context is not really clear. I think you would be better off saying the IOMMU can map any IOVA to any memory page. From a hardware POV that means any physical address, but of course for a VFIO user a page is specified by its process virtual address.
Will fix.
Quoted 7 lines
I think we need to pin exactly what "
MAP_ANY" means down better. Now, VFIO is pretty much a lost cause if you can't map any normal process memory page into the IOMMU, so I think the only thing that is really covered is IOVAs. But saying "can map any IOVA" is not clear, because if you can't map it, it's not a (valid) IOVA. Better to say that IOVAs can be any 64-bit value, which I think is what you really mean here.
ok
Quoted 3 lines
Of course, since POWER is a platform where this is *not* true, I'd prefer to have something giving the range of valid IOVAs in the core to start with.
Since iommu_ops does not yet have any concept of this (nudge, nudge), I figured this would be added later. A possible implementation would be that such an iommu would not set MAP_ANY, would add a new flag for MAP_RANGE, and provide a new VFIO_IOMMU_GET_RANGE_INFO ioctl to describe it. I'm guaranteed to get it wrong if I try to predict all your needs.
Quoted 4 lines
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+ +The (UN)MAP_DMA commands make use of struct vfio_dma_map for mapping +and unmapping IOVAs to process virtual addresses: +
Quoted 8 lines
Documentation/vfio.txt
Quoted 2 lines
Documentation/vfio.txt new file +2
-0+struct vfio_dma_map { + __u64 len; /* length of structure */Thanks for adding these structure length fields. But I think they should be called something other than 'len', which is likely to be confused with size (or some other length that's actually related to the operation's parameters). Better to call it 'structlen' or 'argslen' or something.
Ok. As Scott noted, I've failed to implement these in a way that actually allows extension, but I'll work on it.
Quoted 10 lines
Documentation/vfio.txt line 125
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+ __u64 vaddr; /* process virtual addr */ + __u64 dmaaddr; /* desired and/or returned dma address */ + __u64 size; /* size in bytes */ + __u64 flags; +#define VFIO_DMA_MAP_FLAG_WRITE (1 << 0) /* req writeable DMA mem */Make it independent READ and WRITE flags from the start. Not all combinations will be be valid on all hardware, but that way we have the possibilities covered without having to use strange encodings later.
Ok.
Quoted 12 lines
Quoted 12 lines
Documentation/vfio.txt new file +12
-0+}; + +Current users of VFIO use relatively static DMA mappings, not requiring +high frequency turnover. As new users are added, it's expected that the +IOMMU file descriptor will evolve to support new mapping interfaces, this +will be reflected in the flags and may present new ioctls and file +interfaces. + +The device GET_FLAGS ioctl is intended to return basic device type and +indicate support for optional capabilities. Flags currently include whether +the device is PCI or described by Device Tree, and whether the RESET ioctl +is supported:
Quoted 8 lines
Documentation/vfio.txt line 141
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+ +#define VFIO_DEVICE_GET_FLAGS _IOR(';', 108, __u64) + #define VFIO_DEVICE_FLAGS_PCI (1 << 0) + #define VFIO_DEVICE_FLAGS_DT (1 << 1)TBH, I don't think the VFIO for DT stuff is mature enough yet to be in an initial infrastructure patch, though we should certainly be discussing it as an add-on patch.
I agree for DT, and PCI should be added with vfio-pci, not the initial core.
Quoted 8 lines
Quoted 8 lines
+ #define
VFIO_DEVICE_FLAGS_RESET(1 << 2)Documentation/vfio.txt new file +7
-0+ +The MMIO and IOP resources used by a device are described by regions. +The GET_NUM_REGIONS ioctl tells us how many regions the device supports: + +#define VFIO_DEVICE_GET_NUM_REGIONS _IOR(';', 109, int) + +Regions are described by a struct vfio_region_info, which is retrieved by
Quoted 8 lines
Documentation/vfio.txt line 153
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+using the GET_REGION_INFO ioctl with vfio_region_info.index field set to +the desired region (0 based index). Note that devices may implement zero +sized regions (vfio-pci does this to provide a 1:1 BAR to region index +mapping).So, I think you're saying that a zero-sized region is used to encode a NOP region, that is, to basically put a "no region here" in between valid region indices. You should spell that out.
Ok.
Quoted 3 lines
[Incidentally, any chance you could borrow one of RH's tech writers for this? I'm afraid you seem to lack the knack for clear and easily read documentation]
Thanks for the encouragement :-\ It's no wonder there isn't more content in Documentation.
Quoted 11 lines
Documentation/vfio.txt line 162
Quoted 8 lines
Documentation/vfio.txt new file +8
-0+struct vfio_region_info { + __u32 len; /* length of structure */ + __u32 index; /* region number */ + __u64 size; /* size in bytes of region */ + __u64 offset; /* start offset of region */ + __u64 flags; +#define VFIO_REGION_INFO_FLAG_MMAP (1 << 0) +#define VFIO_REGION_INFO_FLAG_RO (1 << 1)Again having separate read and write bits from the start will save strange encodings later.
Seems highly unlikely, but we have bits to waste...
Quoted 7 lines
Documentation/vfio.txt line 165
Quoted 3 lines
Documentation/vfio.txt new file +3
-0+#define VFIO_REGION_INFO_FLAG_PHYS_VALID (1 << 2) + __u64 phys; /* physical address of region */ +};I notice there is no field for "type" e.g. MMIO vs. PIO vs. config space for PCI. If you added that having a NONE type might be a clearer way of encoding a non-region than just having size==0.
I thought there was some resistance to including MMIO and PIO bits in the flags. If that's passed, I can add it, but PCI can determine this through config space (and vfio-pci exposes config space at a fixed index). Having a regions w/ size == 0, MMIO and PIO flags unset seems a little redundant if that's the only reason for having them. A NONE flag doesn't make sense to me. Config space isn't NONE, but neither is it MMIO nor PIO; and someone would probably be offended about even mentioning PIO in the specification.
Quoted 12 lines
Quoted 12 lines
Documentation/vfio.txt new file +12
-0+ +#define VFIO_DEVICE_GET_REGION_INFO _IOWR(';', 110, struct vfio_region_info) + +The offset indicates the offset into the device file descriptor which +accesses the given range (for read/write/mmap/seek). Flags indicate the +available access types and validity of optional fields. For instance +the phys field may only be valid for certain devices types. + +Interrupts are described using a similar interface. GET_NUM_IRQS +reports the number or IRQ indexes for the device. + +#define VFIO_DEVICE_GET_NUM_IRQS _IOR(';', 111, int)
Quoted 8 lines
Documentation/vfio.txt line 182
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+ +struct vfio_irq_info { + __u32 len; /* length of structure */ + __u32 index; /* IRQ number */ + __u32 count; /* number of individual IRQs */Is there a reason for allowing irqs in batches like this, rather than having each MSI be reflected by a separate
irq_info?
Yes, bus drivers like vfio-pci can define index 1 as the MSI info structure and index 2 as MSI-X. There's really no need to expose 57 individual MSI interrupts and try to map them to the correct device specific MSI type if they can only logically be enabled in two distinct groups. Bus drivers with individually controllable MSI vectors are free to expose them separately. I assume device tree paths would help associate an index to a specific interrupt.
Quoted 8 lines
Documentation/vfio.txt line 188
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+ __u64 flags; +#define VFIO_IRQ_INFO_FLAG_LEVEL (1 << 0) +}; + +Again, zero count entries are allowed (vfio-pci uses a static interrupt +type to index mapping).I know what you mean, but you need a clearer way to express it.
I'll work on it.
Quoted 16 lines
Quoted 16 lines
Documentation/vfio.txt new file +16
-0+Information about each index can be retrieved using the GET_IRQ_INFO +ioctl, used much like GET_REGION_INFO. + +#define VFIO_DEVICE_GET_IRQ_INFO _IOWR(';', 112, struct vfio_irq_info) + +Individual indexes can describe single or sets of IRQs. This provides the +flexibility to describe PCI INTx, MSI, and MSI-X using a single interface. + +All VFIO interrupts are signaled to userspace via eventfds. Integer arrays, +as shown below, are used to pass the IRQ info index, the number of eventfds, +and each eventfd to be signaled. Using a count of 0 disables the interrupt. + +/* Set IRQ eventfds, arg[0] = index, arg[1] = count, arg[2-n] = eventfds */ +#define VFIO_DEVICE_SET_IRQ_EVENTFDS _IOW(';', 113, int) + +When a level triggered interrupt is signaled, the interrupt is masked
Quoted 8 lines
Documentation/vfio.txt line 209
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+on the host. This prevents an unresponsive userspace driver from +continuing to interrupt the host system. After servicing the interrupt, +UNMASK_IRQ is used to allow the interrupt to retrigger. Note that level +triggered interrupts implicitly have a count of 1 per index.This is a silly restriction. Even PCI devices can have up to 4 LSIs on a function in theory, though no-one ever does. Embedded devices can and do have multiple level interrupts.
Per the PCI spec, an individual PCI function can only ever have, at most, a single INTx line. A multi-function *device* can have up to 4 INTx lines, but what we're exposing here is a struct device, ie. a PCI function.
Other devices could certainly have multiple level interrupts, and if grouping them as we do with MSI on PCI makes sense, please let me know. I just didn't see the value in making the unmask operations handle sub-indexes if it's not needed.
Quoted 42 lines
Quoted 42 lines
Documentation/vfio.txt new file +42
-0+ +/* Unmask IRQ index, arg[0] = index */ +#define VFIO_DEVICE_UNMASK_IRQ _IOW(';', 114, int) + +Level triggered interrupts can also be unmasked using an irqfd. Use +SET_UNMASK_IRQ_EVENTFD to set the file descriptor for this. + +/* Set unmask eventfd, arg[0] = index, arg[1] = eventfd */ +#define VFIO_DEVICE_SET_UNMASK_IRQ_EVENTFD _IOW(';', 115, int) + +When supported, as indicated by the device flags, reset the device. + +#define VFIO_DEVICE_RESET _IO(';', 116) + +Device tree devices also invlude ioctls for further defining the +device tree properties of the device: + +struct vfio_dtpath { + __u32 len; /* length of structure */ + __u32 index; + __u64 flags; +#define VFIO_DTPATH_FLAGS_REGION (1 << 0) +#define VFIO_DTPATH_FLAGS_IRQ (1 << 1) + char *path; +}; +#define VFIO_DEVICE_GET_DTPATH _IOWR(';', 117, struct vfio_dtpath) + +struct vfio_dtindex { + __u32 len; /* length of structure */ + __u32 index; + __u32 prop_type; + __u32 prop_index; + __u64 flags; +#define VFIO_DTINDEX_FLAGS_REGION (1 << 0) +#define VFIO_DTINDEX_FLAGS_IRQ (1 << 1) +}; +#define VFIO_DEVICE_GET_DTINDEX _IOWR(';', 118, struct vfio_dtindex) + + +VFIO bus driver API +------------------------------------------------------------------------------- +
Quoted 8 lines
Documentation/vfio.txt line 257
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+Bus drivers, such as PCI, have three jobs: + 1) Add/remove devices from vfio + 2) Provide vfio_device_ops for device access + 3) Device binding and unbinding + +When initialized, the bus driver should enumerate the devices on it'ss/it's/its/
Noted.
<snip>
Quoted 10 lines
Documentation/vfio.txt
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+/* Unmap DMA region */ +/* dgate must be held */ +static int __vfio_dma_unmap(struct vfio_iommu *iommu, unsigned long iova, + int npage, int rdwr)Use of "read" and "write" in DMA can often be confusing, since it's not always clear if you're talking from the perspective of the CPU or the device (_writing_ data to a device will usually involve it doing DMA _reads_ from memory). It's often best to express things as DMA direction, 'to device', and 'from device' instead.
Good point.
Quoted 17 lines
Quoted 17 lines
Documentation/vfio.txt new file +17
-0+{ + int i, unlocked = 0; + + for (i = 0; i < npage; i++, iova += PAGE_SIZE) { + unsigned long pfn; + + pfn = iommu_iova_to_phys(iommu->domain, iova) >> PAGE_SHIFT; + if (pfn) { + iommu_unmap(iommu->domain, iova, 0); + unlocked += put_pfn(pfn, rdwr); + } + } + return unlocked; +} + +static void vfio_dma_unmap(struct vfio_iommu *iommu, unsigned long iova, + unsigned long npage, int rdwr)
Quoted 8 lines
Documentation/vfio.txt
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+{ + int unlocked; + + unlocked = __vfio_dma_unmap(iommu, iova, npage, rdwr); + vfio_lock_acct(-unlocked);Have you checked that your accounting will work out if the user maps the same memory page to multiple IOVAs?
Hmm, it probably doesn't. We potentially over-penalize the user process here.
Quoted 14 lines
Quoted 14 lines
Documentation/vfio.txt new file +14
-0+} + +/* Unmap ALL DMA regions */ +void vfio_iommu_unmapall(struct vfio_iommu *iommu) +{ + struct list_head *pos, *pos2; + struct dma_map_page *mlp; + + mutex_lock(&iommu->dgate); + list_for_each_safe(pos, pos2, &iommu->dm_list) { + mlp = list_entry(pos, struct dma_map_page, list); + vfio_dma_unmap(iommu, mlp->daddr, mlp->npage, mlp->rdwr); + list_del(&mlp->list); + kfree(mlp);
Quoted 8 lines
Documentation/vfio.txt
Quoted 2 lines
Documentation/vfio.txt new file +2
-0+ } + mutex_unlock(&iommu->dgate);Ouch, no good at all. Keeping track of every DMA map is no good on POWER or other systems where IOMMU operations are a hot path. I think you'll need an iommu specific hook for this instead, which uses whatever data structures are natural for the IOMMU. For example a 1-level pagetable, like we use on POWER will just zero every entry.
It's already been noted in the docs that current users have relatively static mappings and a performance interface is TBD for dynamically backing streaming DMA. The current vfio_iommu exposes iommu_ops, POWER will need to come up with something to expose instead.
Quoted 18 lines
Quoted 18 lines
Documentation/vfio.txt new file +18
-0+} + +static int vaddr_get_pfn(unsigned long vaddr, int rdwr, unsigned long *pfn) +{ + struct page *page[1]; + struct vm_area_struct *vma; + int ret = -EFAULT; + + if (get_user_pages_fast(vaddr, 1, rdwr, page) == 1) { + *pfn = page_to_pfn(page[0]); + return 0; + } + + down_read(¤t->mm->mmap_sem); + + vma = find_vma_intersection(current->mm, vaddr, vaddr + 1); + + if (vma && vma->vm_flags & VM_PFNMAP) {
Quoted 8 lines
Documentation/vfio.txt
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+ *pfn = ((vaddr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; + if (is_invalid_reserved_pfn(*pfn)) + ret = 0; + }It's kind of nasty that you take
gup_fast(), already designed to grab pointers for multiple user pages, then just use it one page at a time, even for a big map.
Yep, this needs work, but shouldn't really change the API.
Quoted 4 lines
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+ up_read(¤t->mm->mmap_sem); + + return ret; +}
Quoted 8 lines
Documentation/vfio.txt
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+ +/* Map DMA region */ +/* dgate must be held */ +static int vfio_dma_map(struct vfio_iommu *iommu, unsigned long iova, + unsigned long vaddr, int npage, int rdwr)iova should be a
dma_addr_t. Bus address size need not match virtual address size, and may not fit in an unsigned long.
ok.
Quoted 40 lines
Quoted 40 lines
Documentation/vfio.txt new file +40
-0+{ + unsigned long start = iova; + int i, ret, locked = 0, prot = IOMMU_READ; + + /* Verify pages are not already mapped */ + for (i = 0; i < npage; i++, iova += PAGE_SIZE) + if (iommu_iova_to_phys(iommu->domain, iova)) + return -EBUSY; + + iova = start; + + if (rdwr) + prot |= IOMMU_WRITE; + if (iommu->cache) + prot |= IOMMU_CACHE; + + for (i = 0; i < npage; i++, iova += PAGE_SIZE, vaddr += PAGE_SIZE) { + unsigned long pfn = 0; + + ret = vaddr_get_pfn(vaddr, rdwr, &pfn); + if (ret) { + __vfio_dma_unmap(iommu, start, i, rdwr); + return ret; + } + + /* Only add actual locked pages to accounting */ + if (!is_invalid_reserved_pfn(pfn)) + locked++; + + ret = iommu_map(iommu->domain, iova, + (phys_addr_t)pfn << PAGE_SHIFT, 0, prot); + if (ret) { + /* Back out mappings on error */ + put_pfn(pfn, rdwr); + __vfio_dma_unmap(iommu, start, i, rdwr); + return ret; + } + } + vfio_lock_acct(locked); + return 0;
Quoted 8 lines
Documentation/vfio.txt
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+} + +static inline int ranges_overlap(unsigned long start1, size_t size1, + unsigned long start2, size_t size2) +{ + return !(start1 + size1 <= start2 || start2 + size2 <= start1);Needs overflow safety.
Yep.
Quoted 11 lines
Quoted 11 lines
Documentation/vfio.txt new file +11
-0+} + +static struct dma_map_page *vfio_find_dma(struct vfio_iommu *iommu, + dma_addr_t start, size_t size) +{ + struct list_head *pos; + struct dma_map_page *mlp; + + list_for_each(pos, &iommu->dm_list) { + mlp = list_entry(pos, struct dma_map_page, list); + if (ranges_overlap(mlp->daddr, NPAGE_TO_SIZE(mlp->npage),
Quoted 8 lines
Documentation/vfio.txt
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+ start, size)) + return mlp; + } + return NULL; +}Again, keeping track of each dma map operation is no good for performance.
This is not the performance interface you're looking for.
Quoted 189 lines
Quoted 189 lines
Documentation/vfio.txt new file +189
-0+ +int vfio_remove_dma_overlap(struct vfio_iommu *iommu, dma_addr_t start, + size_t size, struct dma_map_page *mlp) +{ + struct dma_map_page *split; + int npage_lo, npage_hi; + + /* Existing dma region is completely covered, unmap all */ + if (start <= mlp->daddr && + start + size >= mlp->daddr + NPAGE_TO_SIZE(mlp->npage)) { + vfio_dma_unmap(iommu, mlp->daddr, mlp->npage, mlp->rdwr); + list_del(&mlp->list); + npage_lo = mlp->npage; + kfree(mlp); + return npage_lo; + } + + /* Overlap low address of existing range */ + if (start <= mlp->daddr) { + size_t overlap; + + overlap = start + size - mlp->daddr; + npage_lo = overlap >> PAGE_SHIFT; + npage_hi = mlp->npage - npage_lo; + + vfio_dma_unmap(iommu, mlp->daddr, npage_lo, mlp->rdwr); + mlp->daddr += overlap; + mlp->vaddr += overlap; + mlp->npage -= npage_lo; + return npage_lo; + } + + /* Overlap high address of existing range */ + if (start + size >= mlp->daddr + NPAGE_TO_SIZE(mlp->npage)) { + size_t overlap; + + overlap = mlp->daddr + NPAGE_TO_SIZE(mlp->npage) - start; + npage_hi = overlap >> PAGE_SHIFT; + npage_lo = mlp->npage - npage_hi; + + vfio_dma_unmap(iommu, start, npage_hi, mlp->rdwr); + mlp->npage -= npage_hi; + return npage_hi; + } + + /* Split existing */ + npage_lo = (start - mlp->daddr) >> PAGE_SHIFT; + npage_hi = mlp->npage - (size >> PAGE_SHIFT) - npage_lo; + + split = kzalloc(sizeof *split, GFP_KERNEL); + if (!split) + return -ENOMEM; + + vfio_dma_unmap(iommu, start, size >> PAGE_SHIFT, mlp->rdwr); + + mlp->npage = npage_lo; + + split->npage = npage_hi; + split->daddr = start + size; + split->vaddr = mlp->vaddr + NPAGE_TO_SIZE(npage_lo) + size; + split->rdwr = mlp->rdwr; + list_add(&split->list, &iommu->dm_list); + return size >> PAGE_SHIFT; +} + +int vfio_dma_unmap_dm(struct vfio_iommu *iommu, struct vfio_dma_map *dmp) +{ + int ret = 0; + size_t npage = dmp->size >> PAGE_SHIFT; + struct list_head *pos, *n; + + if (dmp->dmaaddr & ~PAGE_MASK) + return -EINVAL; + if (dmp->size & ~PAGE_MASK) + return -EINVAL; + + mutex_lock(&iommu->dgate); + + list_for_each_safe(pos, n, &iommu->dm_list) { + struct dma_map_page *mlp; + + mlp = list_entry(pos, struct dma_map_page, list); + if (ranges_overlap(mlp->daddr, NPAGE_TO_SIZE(mlp->npage), + dmp->dmaaddr, dmp->size)) { + ret = vfio_remove_dma_overlap(iommu, dmp->dmaaddr, + dmp->size, mlp); + if (ret > 0) + npage -= NPAGE_TO_SIZE(ret); + if (ret < 0 || npage == 0) + break; + } + } + mutex_unlock(&iommu->dgate); + return ret > 0 ? 0 : ret; +} + +int vfio_dma_map_dm(struct vfio_iommu *iommu, struct vfio_dma_map *dmp) +{ + int npage; + struct dma_map_page *mlp, *mmlp = NULL; + dma_addr_t daddr = dmp->dmaaddr; + unsigned long locked, lock_limit, vaddr = dmp->vaddr; + size_t size = dmp->size; + int ret = 0, rdwr = dmp->flags & VFIO_DMA_MAP_FLAG_WRITE; + + if (vaddr & (PAGE_SIZE-1)) + return -EINVAL; + if (daddr & (PAGE_SIZE-1)) + return -EINVAL; + if (size & (PAGE_SIZE-1)) + return -EINVAL; + + npage = size >> PAGE_SHIFT; + if (!npage) + return -EINVAL; + + if (!iommu) + return -EINVAL; + + mutex_lock(&iommu->dgate); + + if (vfio_find_dma(iommu, daddr, size)) { + ret = -EBUSY; + goto out_lock; + } + + /* account for locked pages */ + locked = current->mm->locked_vm + npage; + lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT; + if (locked > lock_limit && !capable(CAP_IPC_LOCK)) { + printk(KERN_WARNING "%s: RLIMIT_MEMLOCK (%ld) exceeded\n", + __func__, rlimit(RLIMIT_MEMLOCK)); + ret = -ENOMEM; + goto out_lock; + } + + ret = vfio_dma_map(iommu, daddr, vaddr, npage, rdwr); + if (ret) + goto out_lock; + + /* Check if we abut a region below */ + if (daddr) { + mlp = vfio_find_dma(iommu, daddr - 1, 1); + if (mlp && mlp->rdwr == rdwr && + mlp->vaddr + NPAGE_TO_SIZE(mlp->npage) == vaddr) { + + mlp->npage += npage; + daddr = mlp->daddr; + vaddr = mlp->vaddr; + npage = mlp->npage; + size = NPAGE_TO_SIZE(npage); + + mmlp = mlp; + } + } + + if (daddr + size) { + mlp = vfio_find_dma(iommu, daddr + size, 1); + if (mlp && mlp->rdwr == rdwr && mlp->vaddr == vaddr + size) { + + mlp->npage += npage; + mlp->daddr = daddr; + mlp->vaddr = vaddr; + + /* If merged above and below, remove previously + * merged entry. New entry covers it. */ + if (mmlp) { + list_del(&mmlp->list); + kfree(mmlp); + } + mmlp = mlp; + } + } + + if (!mmlp) { + mlp = kzalloc(sizeof *mlp, GFP_KERNEL); + if (!mlp) { + ret = -ENOMEM; + vfio_dma_unmap(iommu, daddr, npage, rdwr); + goto out_lock; + } + + mlp->npage = npage; + mlp->daddr = daddr; + mlp->vaddr = vaddr; + mlp->rdwr = rdwr; + list_add(&mlp->list, &iommu->dm_list); + } +
Quoted 8 lines
Documentation/vfio.txt
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+out_lock: + mutex_unlock(&iommu->dgate); + return ret; +}This whole tracking infrastructure is way too complex to impose on every IOMMU. We absolutely don't want to do all this when just updating a 1-level pagetable.
If only POWER implemented an iommu_ops so we had something on which we could base an alternate iommu model and pluggable iommu registration...
Quoted 12 lines
Quoted 12 lines
Documentation/vfio.txt new file +12
-0+static int vfio_iommu_release(struct inode *inode, struct file *filep) +{ + struct vfio_iommu *iommu = filep->private_data; + + vfio_release_iommu(iommu); + return 0; +} + +static long vfio_iommu_unl_ioctl(struct file *filep, + unsigned int cmd, unsigned long arg) +{ + struct vfio_iommu *iommu = filep->private_data;
Quoted 8 lines
Documentation/vfio.txt
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+ int ret = -ENOSYS; + + if (cmd == VFIO_IOMMU_GET_FLAGS) { + u64 flags = VFIO_IOMMU_FLAGS_MAP_ANY; + + ret = put_user(flags, (u64 __user *)arg);Um.. flags surely have to come from the IOMMU driver.
This vfio_iommu object is backed by iommu_ops, which supports this mapping.
Quoted 26 lines
Quoted 26 lines
Documentation/vfio.txt new file +26
-0+ } else if (cmd == VFIO_IOMMU_MAP_DMA) { + struct vfio_dma_map dm; + + if (copy_from_user(&dm, (void __user *)arg, sizeof dm)) + return -EFAULT; + + ret = vfio_dma_map_dm(iommu, &dm); + + if (!ret && copy_to_user((void __user *)arg, &dm, sizeof dm)) + ret = -EFAULT; + + } else if (cmd == VFIO_IOMMU_UNMAP_DMA) { + struct vfio_dma_map dm; + + if (copy_from_user(&dm, (void __user *)arg, sizeof dm)) + return -EFAULT; + + ret = vfio_dma_unmap_dm(iommu, &dm); + + if (!ret && copy_to_user((void __user *)arg, &dm, sizeof dm)) + ret = -EFAULT; + } + return ret; +} + +#ifdef CONFIG_COMPAT
Quoted 8 lines
Documentation/vfio.txt
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+static long vfio_iommu_compat_ioctl(struct file *filep, + unsigned int cmd, unsigned long arg) +{ + arg = (unsigned long)compat_ptr(arg); + return vfio_iommu_unl_ioctl(filep, cmd, arg);Um, this only works if the structures are exactly compatible between 32-bit and 64-bit ABIs. I don't think that is always true.
I think all our structure sizes are independent of host width. If I'm missing something, let me know.
Quoted 56 lines
Quoted 56 lines
Documentation/vfio.txt new file +11
-0+} +#endif /* CONFIG_COMPAT */ + +const struct file_operations vfio_iommu_fops = { + .owner = THIS_MODULE, + .release = vfio_iommu_release, + .unlocked_ioctl = vfio_iommu_unl_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = vfio_iommu_compat_ioctl, +#endif +};drivers/vfio/vfio_main.c new file +39
-0@@ -0,0 +1,1151 @@ +/* +* VFIO framework +* +* Copyright (C) 2011 Red Hat, Inc. All rights reserved. +* Author: Alex Williamson <[email protected]> +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License version 2 as +* published by the Free Software Foundation. +* +* Derived from original vfio: +* Copyright 2010 Cisco Systems, Inc. All rights reserved. +* Author: Tom Lyon, [email protected] +*/ + +#include <linux/cdev.h> +#include <linux/compat.h> +#include <linux/device.h> +#include <linux/file.h> +#include <linux/anon_inodes.h> +#include <linux/fs.h> +#include <linux/idr.h> +#include <linux/iommu.h> +#include <linux/mm.h> +#include <linux/module.h> +#include <linux/slab.h> +#include <linux/string.h> +#include <linux/uaccess.h> +#include <linux/vfio.h> +#include <linux/wait.h> + +#include "vfio_private.h" + +#define DRIVER_VERSION "0.2" +#define DRIVER_AUTHOR "Alex Williamson <[email protected]>" +#define DRIVER_DESC "VFIO - User Level meta-driver" + +static int allow_unsafe_intrs; +module_param (allow_unsafe_intrs, int,0 );
Quoted 8 lines
drivers/vfio/vfio_main.c line 41
Quoted 2 lines
drivers/vfio/vfio_main.c new file +2
-0+MODULE_PARM_DESC (allow_unsafe_intrs, +"Allow use of IOMMUs which do not support interrupt remapping" );This should not be a global option, but part of the AMD/Intel IOMMU specific code. In general it's a question of how strict the IOMMU driver is about isolation when it determines what the groups are, and only the IOMMU driver can know what the possibilities are for its class of hardware.
I agree this should probably be tied more closely to the iommu driver, but again, we only have iommu_ops right now.
<snip>
Quoted 8 lines
drivers/vfio/vfio_main.c line 496
Quoted 5 lines
drivers/vfio/vfio_main.c new file +5
-0+ +/* Attempt to merge the group pointed to by fd into group. The merge-ee +* group must not have an iommu or any devices open because we cannot +* maintain that context across the merge. The merge-er group can be +* in use. */ Yeah, so merge-er group in use still has its problems, because it could affect what the IOMMU is capable of.
As seen below, we deny merging if the iommu domains are not exactly compatible. Our notion of what compatible means depends on what iommu_ops exposes though.
Quoted 12 lines
Quoted 12 lines
drivers/vfio/vfio_main.c new file +12
-0+static int vfio_group_merge (struct vfio_group *group,int fd) +{ +struct vfio_group *new; +struct vfio_iommu *old_iommu; +struct file *file; +int ret =0 ; +bool opened = false; + +mutex_lock (&vfio.lock); + + file =fget (fd); +if (!file) {
Quoted 8 lines
drivers/vfio/vfio_main.c line 514
Quoted 6 lines
drivers/vfio/vfio_main.c new file +6
-0+ ret = -EBADF ; + goto out_noput; + } + +/* Sanity check, is this really our fd? */ +if (file->f_op != &vfio_group_fops) {This should be a
WARN_ONorBUG_ONrather than just an error return, surely.
No, I don't think so. We're passed a file descriptor that could be for anything. If the user passed a file descriptor for something that's not a vfio group, that's a user error, not an internal consistency error of vfio.
Quoted 113 lines
Quoted 113 lines
drivers/vfio/vfio_main.c new file +113
-0+ ret = -EINVAL ; + goto out; + } + + new = file->private_data; + +if (!new || new == group || !new->iommu || + new->iommu->domain || new->bus != group->bus) { + ret = -EINVAL ; + goto out; + } + +/* We need to attach all the devices to each domain separately +* in order to validate that the capabilities match for both. */ + ret =__vfio_open_iommu (new->iommu); +if (ret) + goto out; + +if (!group->iommu->domain) { + ret =__vfio_open_iommu (group->iommu); +if (ret) + goto out; + opened = true; + } + +/* If cache coherency doesn't match we'd potentialy need to +* remap existing iommu mappings in the merge-er domain. +* Poor return to bother trying to allow this currently. */ +if (iommu_domain_has_cap (group->iommu->domain, +IOMMU_CAP_CACHE_COHERENCY ) != +iommu_domain_has_cap (new->iommu->domain, +IOMMU_CAP_CACHE_COHERENCY )) { +__vfio_close_iommu (new->iommu); +if (opened) +__vfio_close_iommu (group->iommu); + ret = -EINVAL ; + goto out; + } + +/* Close the iommu for the merge-ee and attach all its devices +* to the merge-er iommu. */ +__vfio_close_iommu (new->iommu); + + ret =__vfio_iommu_attach_group (group->iommu, new); +if (ret) + goto out; + +/* set_iommu unlinks new from the iommu, so save a pointer to it */ + old_iommu = new->iommu; +__vfio_group_set_iommu (new, group->iommu); +kfree (old_iommu); + +out: +fput (file); +out_noput: +mutex_unlock (&vfio.lock); +return ret; +} + +/* Unmerge the group pointed to by fd from group. */ +static int vfio_group_unmerge (struct vfio_group *group,int fd) +{ +struct vfio_group *new; +struct vfio_iommu *new_iommu; +struct file *file; +int ret =0 ; + +/* Since the merge-out group is already opened, it needs to +* have an iommu struct associated with it. */ + new_iommu =kzalloc (sizeof (*new_iommu),GFP_KERNEL ); +if (!new_iommu) +return -ENOMEM ; + +INIT_LIST_HEAD (&new_iommu->group_list); +INIT_LIST_HEAD (&new_iommu->dm_list); +mutex_init (&new_iommu->dgate); + new_iommu->bus = group->bus; + +mutex_lock (&vfio.lock); + + file =fget (fd); +if (!file) { + ret = -EBADF ; + goto out_noput; + } + +/* Sanity check, is this really our fd? */ +if (file->f_op != &vfio_group_fops) { + ret = -EINVAL ; + goto out; + } + + new = file->private_data; +if (!new || new == group || new->iommu != group->iommu) { + ret = -EINVAL ; + goto out; + } + +/* We can't merge-out a group with devices still in use. */ +if (__vfio_group_devs_inuse (new)) { + ret = -EBUSY ; + goto out; + } + +__vfio_iommu_detach_group (group->iommu, new); +__vfio_group_set_iommu (new, new_iommu); + +out: +fput (file); +out_noput: +if (ret) +kfree (new_iommu); +mutex_unlock (&vfio.lock);
Quoted 8 lines
drivers/vfio/vfio_main.c line 632
Quoted 5 lines
drivers/vfio/vfio_main.c new file +5
-0+return ret; +} + +/* Get a new iommu file descriptor. This will open the iommu, setting +* the current->mm ownership if it's not already set. */ I know I've had this explained to me several times before, but I've forgotten again. Why do we need to wire the iommu to an mm?
We're mapping process virtual addresses into the IOMMU, so it makes sense to restrict ourselves to a single virtual address space. It also enforces the ownership, that only a single mm is in control of the group.
Quoted 24 lines
Quoted 24 lines
drivers/vfio/vfio_main.c new file +24
-0+static int vfio_group_get_iommu_fd (struct vfio_group *group) +{ +int ret =0 ; + +mutex_lock (&vfio.lock); + +if (!group->iommu->domain) { + ret =__vfio_open_iommu (group->iommu); +if (ret) + goto out; + } + + ret =anon_inode_getfd ("[vfio-iommu]" , &vfio_iommu_fops, + group->iommu,O_RDWR ); +if (ret <0 ) + goto out; + + group->iommu->refcnt++; +out: +mutex_unlock (&vfio.lock); +return ret; +} + +/* Get a new device file descriptor. This will open the iommu, setting
Quoted 8 lines
drivers/vfio/vfio_main.c line 661
Quoted 5 lines
drivers/vfio/vfio_main.c new file +5
-0+* the current->mm ownership if it's not already set. It's difficult to +* specify the requirements for matching a user supplied buffer to a +* device, so we use a vfio driver callback to test for a match. For +* PCI, dev_name(dev) is unique, but other drivers may require including +* a parent device string. */ At some point we probably want an interface to enumerate the devices too, but that can probably wait.
That's what I decided as well. I also haven't been able to come up with an interface for it that doesn't make me want to vomit.
Quoted 2 lines
drivers/vfio/vfio_main.c line 663
Quoted 2 lines
drivers/vfio/vfio_main.c new file +2
-0+static int vfio_group_get_device_fd (struct vfio_group *group,char *buf) +{
Thanks,
Alex
Quoted 85 lines · Alex Williamson
Quoted 18 lines · David Gibson
Quoted 6 lines · Alex Williamson
Documentation/vfio.txt new file +0
-0Documentation/vfio.txt line 10
Quoted 10 lines
Documentation/vfio.txt new file +10
-0@@ -0,0 +1,304 @@ +VFIO - "Virtual Function I/O"[1] +------------------------------------------------------------------------------- +Many modern system now provide DMA and interrupt remapping facilities +to help ensure I/O devices behave within the boundaries they've been +allotted. This includes x86 hardware with AMD-Vi and Intel VT-d as +well as POWER systems with Partitionable Endpoints (PEs) and even +embedded powerpc systems (technology name unknown). The VFIO driver +is an IOMMU/device agnostic framework for exposing direct device +access to userspace, in a secure, IOMMU protected environment. In +other words, this allows safe, non-privileged, userspace drivers.Quoted 7 lines
It's perhaps worth emphasisng that "safe" depends on the hardware being sufficiently well behaved. BenH, I know, thinks there are a *lot* of cards that, e.g. have debug registers that allow a backdoor to their own config space via MMIO, which would bypass vfio's filtering of config space access. And that's before we even get into the varying degrees of completeness in the isolation provided by different IOMMUs.
Fair enough. I know Tom had emphasized "well behaved" in the original doc. Virtual functions are probably the best indicator of well behaved.
Quoted 5 lines
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+Why do we want that? Virtual machines often make use of direct device +access ("device assignment") when configured for the highest possible +I/O performance. From a device and host perspective, this simply turns +the VM into a userspace driver, with the benefits of significantly +reduced latency, higher bandwidth, and direct use of bare-metal deviceQuoted 8 lines
Documentation/vfio.txt line 22
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+drivers[2]. + +Some applications, particularly in the high performance computing +field, also benefit from low-overhead, direct device access from +userspace. Examples include network adapters (often non-TCP/IP based) +and compute accelerators. Previous to VFIO, these drivers needed tos/Previous/Prior/ although that may be a .us vs .au usage thing.
Same difference, AFAICT.
Quoted 30 lines
Quoted 30 lines
Documentation/vfio.txt new file +30
-0+go through the full development cycle to become proper upstream driver, +be maintained out of tree, or make use of the UIO framework, which +has no notion of IOMMU protection, limited interrupt support, and +requires root privileges to access things like PCI configuration space. + +The VFIO driver framework intends to unify these, replacing both the +KVM PCI specific device assignment currently used as well as provide +a more secure, more featureful userspace driver environment than UIO. + +Groups, Devices, IOMMUs, oh my +------------------------------------------------------------------------------- + +A fundamental component of VFIO is the notion of IOMMU groups. IOMMUs +can't always distinguish transactions from each individual device in +the system. Sometimes this is because of the IOMMU design, such as with +PEs, other times it's caused by the I/O topology, for instance a +PCIe-to-PCI bridge masking all devices behind it. We call the sets of +devices created by these restictions IOMMU groups (or just "groups" for +this document). + +The IOMMU cannot distiguish transactions between the individual devices +within the group, therefore the group is the basic unit of ownership for +a userspace process. Because of this, groups are also the primary +interface to both devices and IOMMU domains in VFIO. + +The VFIO representation of groups is created as devices are added into +the framework by a VFIO bus driver. The vfio-pci module is an example +of a bus driver. This module registers devices along with a set of bus +specific callbacks with the VFIO core. These callbacks provide the +interfaces later used for device access. As each new group is created,Quoted 8 lines
Documentation/vfio.txt line 54
Quoted 2 lines
Documentation/vfio.txt new file +2
-0+as determined by iommu_device_group(), VFIO creates a /dev/vfio/$GROUP +character device.Ok.. so, the fact that it's called "vfio-pci" suggests that the VFIO
bus driver is per bus type, not per bus instance. But grouping
constraints could be per bus instance, if you have a couple of different models of PCI host bridge with IOMMUs of different capabilities built in, for example.
Quoted 2 lines
Yes, vfio-pci manages devices on the
pci_bus_type; per type, not per bus instance.
Ok, how can that work. vfio-pci is responsible for generating the groupings, yes? For which it needs to know the iommu/host bridge's isolation capabilities, which vary depending on the type of host bridge.
Quoted 53 lines
IOMMUs also register drivers per bus type, not per bus
instance. The IOMMU driver is free to impose any constraints it wants.Quoted 38 lines
Quoted 25 lines
Documentation/vfio.txt new file +25
-0+In addition to the device enumeration and callbacks, the VFIO bus driver +also provides a traditional device driver and is able to bind to devices +on it's bus. When a device is bound to the bus driver it's available to +VFIO. When all the devices within a group are bound to their bus drivers, +the group becomes "viable" and a user with sufficient access to the VFIO +group chardev can obtain exclusive access to the set of group devices. + +As documented in linux/vfio.h, several ioctls are provided on the +group chardev: + +#define VFIO_GROUP_GET_FLAGS _IOR(';', 100, __u64) + #define VFIO_GROUP_FLAGS_VIABLE (1 << 0) + #define VFIO_GROUP_FLAGS_MM_LOCKED (1 << 1) +#define VFIO_GROUP_MERGE _IOW(';', 101, int) +#define VFIO_GROUP_UNMERGE _IOW(';', 102, int) +#define VFIO_GROUP_GET_IOMMU_FD _IO(';', 103) +#define VFIO_GROUP_GET_DEVICE_FD _IOW(';', 104, char *) + +The last two ioctls return new file descriptors for accessing +individual devices within the group and programming the IOMMU. Each of +these new file descriptors provide their own set of file interfaces. +These ioctls will fail if any of the devices within the group are not +bound to their VFIO bus driver. Additionally, when either of these +interfaces are used, the group is then bound to the struct_mm of the +caller. The GET_FLAGS ioctl can be used to view the state of the group.Documentation/vfio.txt
Quoted 10 lines
Documentation/vfio.txt new file +10
-0+ +When either the GET_IOMMU_FD or GET_DEVICE_FD ioctls are invoked, a +new IOMMU domain is created and all of the devices in the group are +attached to it. This is the only way to ensure full IOMMU isolation +of the group, but potentially wastes resources and cycles if the user +intends to manage multiple groups with the same set of IOMMU mappings. +VFIO therefore provides a group MERGE and UNMERGE interface, which +allows multiple groups to share an IOMMU domain. Not all IOMMUs allow +arbitrary groups to be merged, so the user should assume merging is +opportunistic.I do not think "opportunistic" means what you think it means..
Quoted 11 lines
Quoted 9 lines
Documentation/vfio.txt new file +7
-0A new group, with no open device or IOMMU file +descriptors, can be merged into an existing, in-use, group using the +MERGE ioctl. A merged group can be unmerged using the UNMERGE ioctl +once all of the device file descriptors for the group being merged +"out" are closed. + +When groups are merged, the GET_IOMMU_FD and GET_DEVICE_FD ioctls are +essentially fungible between group file descriptors (ie. if deviceA
IDNT "fungible" MWYTIM, either.
Quoted 1 line
Hmm, feel free to suggest. Maybe we're hitting .us vs .au connotation.
In any case, I don't think it's a word whose meaning is unambiguous enough to use here.
Quoted 19 lines
Quoted 13 lines
Documentation/vfio.txt line 103
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+is in group X, and X is merged with Y, a file descriptor for A can be +retrieved using GET_DEVICE_FD on Y. Likewise, GET_IOMMU_FD returns a +file descriptor referencing the same internal IOMMU object from either +X or Y). Merged groups can be dissolved either explictly with UNMERGE +or automatically when ALL file descriptors for the merged group are +closed (all IOMMUs, all devices, all groups).Blech. I'm really not liking this merge/unmerge API as it stands, it's horribly confusing. At the very least, we need some better terminology. We need some term for the metagroups; supergroups; iommu domains or-at-least-they-will-be-once-we-open-the-iommu or whathaveyous.
Quoted 5 lines
The first confusing thing about this interface is that each open group handle actually refers to two different things; the original group you opened and the metagroup it's a part of. For the
GET_IOMMU_FDandGET_DEVICE_FDoperations, you're using the metagroup and two "merged" group handles are interchangeable.
Quoted 7 lines
Fungible, even ;)
Quoted 2 lines
For other MERGE and especially
UNMERGE operations, it matters which is the original group.If I stick two LEGO blocks together, I need to identify the individual block I want to remove to pull them back apart...
Yeah, I'm starting to get my head around the model, but the current description of it doesn't help very much. In particular the terms "merge" and "unmerge" lead one to the wrong mental model, I think.
Quoted 10 lines
Quoted 4 lines
The semantics of "merge" and "unmerge" under those names are really non-obvious. Merge kind of has to merge two whole metagroups, but it's unclear if unmerge reverses one merge, or just takes out one (atom) group. These operations need better names, at least.
Christian suggested a change to UNMERGE that we do not need to specify a group to unmerge "from". This makes it more like a list implementation except there's no defined
list_head. Any member of the list can pull in a new entry. Calling UNMERGE on any member extracts that member.
I think that's a good idea, but "unmerge" is not a good word for it.
Quoted 11 lines
Quoted 10 lines
Then it's unclear what order you can do various operations, and which order you can open and close various things. You can kind of figure it out but it takes far more thinking than it should.
So at the _very_ least, we need to invent new terminology and find a much better way of describing this API's semantics. I still think an entirely different interface, where metagroups are created from outside with a lifetime that's not tied to an fd would be a better idea.
Quoted 3 lines
As we've discussed previously, configfs provides part of this, but has no ioctl support. It doesn't make sense to me to go play with groups in configfs, but then still interact with them via a char dev.
Why not? You configure, say, loopback devices with losetup, then use them as a block device. Similar with nbd. You can configure serial devices with setserial, then use them as a char dev.
Quoted 2 lines
It also
splits the ownership model
I'm not even sure what that means.
Quoted 2 lines
and makes it harder to enforce who gets to interact with the devices vs who gets to manipulate groups.
How so.
Quoted 15 lines
The current
model really isn't that complicated, imho. As always, feel free to suggest specific models. If you have a specific terminology other than MERGE, please suggest.Quoted 5 lines
Now, you specify that you can't use a group as the second argument of a merge if it already has an open iommu, but it's not clear from the doc if you can merge things into a group with an open iommu.
From above:
A new group, with no open device or IOMMU file descriptors, can be merged into an existing, in-use, group using the MERGE ioctl.
^^^^^^
Quoted 7 lines
Quoted 4 lines
Banning
this would make life simpler, because the IOMMU's effective capabilities may change if you add more devices to the domain. That's yet another non-obvious constraint in the interface ordering, though.Banning this would prevent using merged groups with hotplug, which I consider to be a primary use case.
Yeah, fair enough, based on your later comments w.r.t. only combining feature compatible groups.
Quoted 40 lines
Quoted 6 lines
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+The IOMMU file descriptor provides this set of ioctls: + +#define VFIO_IOMMU_GET_FLAGS _IOR(';', 105, __u64) + #define VFIO_IOMMU_FLAGS_MAP_ANY (1 << 0) +#define VFIO_IOMMU_MAP_DMA _IOWR(';', 106, struct vfio_dma_map) +#define VFIO_IOMMU_UNMAP_DMA _IOWR(';', 107, struct vfio_dma_map)Quoted 8 lines
Quoted 5 lines
Documentation/vfio.txt new file +4
-0+ +The GET_FLAGS ioctl returns basic information about the IOMMU domain. +We currently only support IOMMU domains that are able to map any +virtual address to any IOVA. This is indicated by the MAP_ANYflag.
So. I tend to think of an IOMMU mapping IOVAs to memory pages, rather than memory pages to IOVAs.
I do too, not sure why I wrote it that way, will fix.
Quoted 6 lines
The IOMMU itself, of course maps to
physical addresses, and the meaning of "virtual address" in this context is not really clear. I think you would be better off saying the IOMMU can map any IOVA to any memory page. From a hardware POV that means any physical address, but of course for a VFIO user a page is specified by its process virtual address.Will fix.
Quoted 7 lines
I think we need to pin exactly what "
MAP_ANY" means down better. Now, VFIO is pretty much a lost cause if you can't map any normal process memory page into the IOMMU, so I think the only thing that is really covered is IOVAs. But saying "can map any IOVA" is not clear, because if you can't map it, it's not a (valid) IOVA. Better to say that IOVAs can be any 64-bit value, which I think is what you really mean here.ok
Quoted 3 lines
Of course, since POWER is a platform where this is *not* true, I'd prefer to have something giving the range of valid IOVAs in the core to start with.
Quoted 5 lines
Since
iommu_opsdoes not yet have any concept of this (nudge, nudge), I figured this would be added later. A possible implementation would be that such an iommu would not setMAP_ANY, would add a new flag forMAP_RANGE, and provide a newVFIO_IOMMU_GET_RANGE_INFOioctl to describe it. I'm guaranteed to get it wrong if I try to predict all your needs.
Hrm. "ANY" just really bothers me because "any iova" is not as clear a concept as it first appears. For starters it's actually "any page aligned" at the very least. But then it's only any 64-bit address for busses which have full 64-bit addressing (and I do wonder if there are any north bridges out there that forgot to implement some of the upper PCI address bits properly, given that 64-bit CPUs rarely actually implement more than 40-something physical address bits in practice).
I'd prefer to see at least something to advertise min and max IOVA and IOVA alignment. That's enough to cover x86 and POWER, including possible variants with an IOMMU page size different to the system page size (note that POWER kernels can have 64k pages as a config option, which means a TCE page size different to the system page size is quite common).
Obviously there could be more complex constraints that we would need to advertise with option bits.
Quoted 13 lines
Quoted 4 lines
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+ +The (UN)MAP_DMA commands make use of struct vfio_dma_map for mapping +and unmapping IOVAs to process virtual addresses: +Quoted 8 lines
Documentation/vfio.txt
Quoted 2 lines
Documentation/vfio.txt new file +2
-0+struct vfio_dma_map { + __u64 len; /* length of structure */Thanks for adding these structure length fields. But I think they should be called something other than 'len', which is likely to be confused with size (or some other length that's actually related to the operation's parameters). Better to call it 'structlen' or 'argslen' or something.
Quoted 2 lines
Ok. As Scott noted, I've failed to implement these in a way that actually allows extension, but I'll work on it.
Right. I had failed to realise quite how the encoding of structure size into the ioctl worked. With that in place, arguably we don't really need the size in the structure itself, because we can still have multiple sized versions of the ioctl. Still, whichever.
Quoted 55 lines
Quoted 11 lines
Documentation/vfio.txt line 125
Quoted 6 lines
Documentation/vfio.txt new file +5
-0+ __u64 vaddr; /* process virtual addr */ + __u64 dmaaddr; /* desired and/or returned dma address */ + __u64 size; /* size in bytes */ + __u64 flags; +#define VFIO_DMA_MAP_FLAG_WRITE (1 << 0) /* req writeable DMA mem */Make it independent READ and WRITE flags from the start. Not all combinations will be be valid on all hardware, but that way we have the possibilities covered without having to use strange encodings later.
Ok.
Quoted 12 lines
Quoted 12 lines
Documentation/vfio.txt new file +12
-0+}; + +Current users of VFIO use relatively static DMA mappings, not requiring +high frequency turnover. As new users are added, it's expected that the +IOMMU file descriptor will evolve to support new mapping interfaces, this +will be reflected in the flags and may present new ioctls and file +interfaces. + +The device GET_FLAGS ioctl is intended to return basic device type and +indicate support for optional capabilities. Flags currently include whether +the device is PCI or described by Device Tree, and whether the RESET ioctl +is supported:Quoted 8 lines
Documentation/vfio.txt line 141
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+ +#define VFIO_DEVICE_GET_FLAGS _IOR(';', 108, __u64) + #define VFIO_DEVICE_FLAGS_PCI (1 << 0) + #define VFIO_DEVICE_FLAGS_DT (1 << 1)TBH, I don't think the VFIO for DT stuff is mature enough yet to be in an initial infrastructure patch, though we should certainly be discussing it as an add-on patch.
I agree for DT, and PCI should be added with vfio-pci, not the initial core.
Quoted 8 lines
Quoted 8 lines
+ #define
VFIO_DEVICE_FLAGS_RESET(1 << 2)Documentation/vfio.txt new file +7
-0+ +The MMIO and IOP resources used by a device are described by regions. +The GET_NUM_REGIONS ioctl tells us how many regions the device supports: + +#define VFIO_DEVICE_GET_NUM_REGIONS _IOR(';', 109, int) + +Regions are described by a struct vfio_region_info, which is retrieved byQuoted 8 lines
Documentation/vfio.txt line 153
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+using the GET_REGION_INFO ioctl with vfio_region_info.index field set to +the desired region (0 based index). Note that devices may implement zero +sized regions (vfio-pci does this to provide a 1:1 BAR to region index +mapping).So, I think you're saying that a zero-sized region is used to encode a NOP region, that is, to basically put a "no region here" in between valid region indices. You should spell that out.
Quoted 8 lines
Ok.
Quoted 3 lines
[Incidentally, any chance you could borrow one of RH's tech writers for this? I'm afraid you seem to lack the knack for clear and easily read documentation]
Thanks for the encouragement :-\ It's no wonder there isn't more content in Documentation.
Sigh. Alas, yes.
Quoted 22 lines
Quoted 11 lines
Documentation/vfio.txt line 162
Quoted 8 lines
Documentation/vfio.txt new file +8
-0+struct vfio_region_info { + __u32 len; /* length of structure */ + __u32 index; /* region number */ + __u64 size; /* size in bytes of region */ + __u64 offset; /* start offset of region */ + __u64 flags; +#define VFIO_REGION_INFO_FLAG_MMAP (1 << 0) +#define VFIO_REGION_INFO_FLAG_RO (1 << 1)Again having separate read and write bits from the start will save strange encodings later.
Seems highly unlikely, but we have bits to waste...
Quoted 7 lines
Documentation/vfio.txt line 165
Quoted 3 lines
Documentation/vfio.txt new file +3
-0+#define VFIO_REGION_INFO_FLAG_PHYS_VALID (1 << 2) + __u64 phys; /* physical address of region */ +};I notice there is no field for "type" e.g. MMIO vs. PIO vs. config space for PCI. If you added that having a NONE type might be a clearer way of encoding a non-region than just having size==0.
Quoted 8 lines
I thought there was some resistance to including MMIO and PIO bits in the flags. If that's passed, I can add it, but PCI can determine this through config space (and vfio-pci exposes config space at a fixed index). Having a regions w/ size == 0, MMIO and PIO flags unset seems a little redundant if that's the only reason for having them. A NONE flag doesn't make sense to me. Config space isn't NONE, but neither is it MMIO nor PIO; and someone would probably be offended about even mentioning PIO in the specification.
No, my concept was that NONE would be used for the indexes where there is no valid BAR. I'll buy your argument on why not to include the PCI (or whatever) address space type here.
What I'm just a bit concerned by is whether we could have a case (not for PCI) of a real resource that still has size 0 - e.g. maybe some sort of doorbell that can't be read or written, but can be triggered some other way. I guess that's probably unlikely though.
Quoted 22 lines
Quoted 13 lines
Quoted 13 lines
Documentation/vfio.txt new file +12
-0+ +#define VFIO_DEVICE_GET_REGION_INFO _IOWR(';', 110, struct vfio_region_info) + +The offset indicates the offset into the device file descriptor which +accesses the given range (for read/write/mmap/seek). Flags indicate the +available access types and validity of optional fields. For instance +the phys field may only be valid for certain devices types. + +Interrupts are described using a similar interface. GET_NUM_IRQS +reports the number or IRQ indexes for the device. + +#define VFIO_DEVICE_GET_NUM_IRQS _IOR(';', 111, int)Quoted 8 lines
Documentation/vfio.txt line 182
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+ +struct vfio_irq_info { + __u32 len; /* length of structure */ + __u32 index; /* IRQ number */ + __u32 count; /* number of individual IRQs */Is there a reason for allowing irqs in batches like this, rather than having each MSI be reflected by a separate
irq_info?
Quoted 7 lines
Yes, bus drivers like vfio-pci can define index 1 as the MSI info structure and index 2 as MSI-X. There's really no need to expose 57 individual MSI interrupts and try to map them to the correct device specific MSI type if they can only logically be enabled in two distinct groups. Bus drivers with individually controllable MSI vectors are free to expose them separately. I assume device tree paths would help associate an index to a specific interrupt.
Ok, fair enough.
Quoted 36 lines
Quoted 8 lines
Documentation/vfio.txt line 188
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+ __u64 flags; +#define VFIO_IRQ_INFO_FLAG_LEVEL (1 << 0) +}; + +Again, zero count entries are allowed (vfio-pci uses a static interrupt +type to index mapping).I know what you mean, but you need a clearer way to express it.
I'll work on it.
Quoted 16 lines
Quoted 16 lines
Documentation/vfio.txt new file +16
-0+Information about each index can be retrieved using the GET_IRQ_INFO +ioctl, used much like GET_REGION_INFO. + +#define VFIO_DEVICE_GET_IRQ_INFO _IOWR(';', 112, struct vfio_irq_info) + +Individual indexes can describe single or sets of IRQs. This provides the +flexibility to describe PCI INTx, MSI, and MSI-X using a single interface. + +All VFIO interrupts are signaled to userspace via eventfds. Integer arrays, +as shown below, are used to pass the IRQ info index, the number of eventfds, +and each eventfd to be signaled. Using a count of 0 disables the interrupt. + +/* Set IRQ eventfds, arg[0] = index, arg[1] = count, arg[2-n] = eventfds */ +#define VFIO_DEVICE_SET_IRQ_EVENTFDS _IOW(';', 113, int) + +When a level triggered interrupt is signaled, the interrupt is maskedQuoted 8 lines
Documentation/vfio.txt line 209
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+on the host. This prevents an unresponsive userspace driver from +continuing to interrupt the host system. After servicing the interrupt, +UNMASK_IRQ is used to allow the interrupt to retrigger. Note that level +triggered interrupts implicitly have a count of 1 per index.This is a silly restriction. Even PCI devices can have up to 4 LSIs on a function in theory, though no-one ever does. Embedded devices can and do have multiple level interrupts.
Quoted 4 lines
Per the PCI spec, an individual PCI function can only ever have, at most, a single INTx line. A multi-function *device* can have up to 4 INTx lines, but what we're exposing here is a struct device, ie. a PCI function.
Ah, my mistake.
Quoted 4 lines
Other devices could certainly have multiple level interrupts, and if grouping them as we do with MSI on PCI makes sense, please let me know. I just didn't see the value in making the unmask operations handle sub-indexes if it's not needed.
I don't know of anything off hand. But I can't see any consideration that would make it unlikely either. I generally don't trust anything *not* to exist in embedded space.
Quoted 65 lines
Quoted 42 lines
Quoted 42 lines
Documentation/vfio.txt new file +42
-0+ +/* Unmask IRQ index, arg[0] = index */ +#define VFIO_DEVICE_UNMASK_IRQ _IOW(';', 114, int) + +Level triggered interrupts can also be unmasked using an irqfd. Use +SET_UNMASK_IRQ_EVENTFD to set the file descriptor for this. + +/* Set unmask eventfd, arg[0] = index, arg[1] = eventfd */ +#define VFIO_DEVICE_SET_UNMASK_IRQ_EVENTFD _IOW(';', 115, int) + +When supported, as indicated by the device flags, reset the device. + +#define VFIO_DEVICE_RESET _IO(';', 116) + +Device tree devices also invlude ioctls for further defining the +device tree properties of the device: + +struct vfio_dtpath { + __u32 len; /* length of structure */ + __u32 index; + __u64 flags; +#define VFIO_DTPATH_FLAGS_REGION (1 << 0) +#define VFIO_DTPATH_FLAGS_IRQ (1 << 1) + char *path; +}; +#define VFIO_DEVICE_GET_DTPATH _IOWR(';', 117, struct vfio_dtpath) + +struct vfio_dtindex { + __u32 len; /* length of structure */ + __u32 index; + __u32 prop_type; + __u32 prop_index; + __u64 flags; +#define VFIO_DTINDEX_FLAGS_REGION (1 << 0) +#define VFIO_DTINDEX_FLAGS_IRQ (1 << 1) +}; +#define VFIO_DEVICE_GET_DTINDEX _IOWR(';', 118, struct vfio_dtindex) + + +VFIO bus driver API +------------------------------------------------------------------------------- +Quoted 8 lines
Documentation/vfio.txt line 257
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+Bus drivers, such as PCI, have three jobs: + 1) Add/remove devices from vfio + 2) Provide vfio_device_ops for device access + 3) Device binding and unbinding + +When initialized, the bus driver should enumerate the devices on it'ss/it's/its/
Noted.
<snip>
Quoted 10 lines
Documentation/vfio.txt
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+/* Unmap DMA region */ +/* dgate must be held */ +static int __vfio_dma_unmap(struct vfio_iommu *iommu, unsigned long iova, + int npage, int rdwr)Use of "read" and "write" in DMA can often be confusing, since it's not always clear if you're talking from the perspective of the CPU or the device (_writing_ data to a device will usually involve it doing DMA _reads_ from memory). It's often best to express things as DMA direction, 'to device', and 'from device' instead.
Quoted 1 line
Good point.
This, of course, potentially affects many areas of the code and doco.
Quoted 26 lines
Quoted 17 lines
Quoted 17 lines
Documentation/vfio.txt new file +17
-0+{ + int i, unlocked = 0; + + for (i = 0; i < npage; i++, iova += PAGE_SIZE) { + unsigned long pfn; + + pfn = iommu_iova_to_phys(iommu->domain, iova) >> PAGE_SHIFT; + if (pfn) { + iommu_unmap(iommu->domain, iova, 0); + unlocked += put_pfn(pfn, rdwr); + } + } + return unlocked; +} + +static void vfio_dma_unmap(struct vfio_iommu *iommu, unsigned long iova, + unsigned long npage, int rdwr)Quoted 8 lines
Documentation/vfio.txt
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+{ + int unlocked; + + unlocked = __vfio_dma_unmap(iommu, iova, npage, rdwr); + vfio_lock_acct(-unlocked);Have you checked that your accounting will work out if the user maps the same memory page to multiple IOVAs?
Quoted 2 lines
Hmm, it probably doesn't. We potentially over-penalize the user process here.
Ok.
Quoted 23 lines
Quoted 14 lines
Quoted 14 lines
Documentation/vfio.txt new file +14
-0+} + +/* Unmap ALL DMA regions */ +void vfio_iommu_unmapall(struct vfio_iommu *iommu) +{ + struct list_head *pos, *pos2; + struct dma_map_page *mlp; + + mutex_lock(&iommu->dgate); + list_for_each_safe(pos, pos2, &iommu->dm_list) { + mlp = list_entry(pos, struct dma_map_page, list); + vfio_dma_unmap(iommu, mlp->daddr, mlp->npage, mlp->rdwr); + list_del(&mlp->list); + kfree(mlp);Quoted 8 lines
Documentation/vfio.txt
Quoted 2 lines
Documentation/vfio.txt new file +2
-0+ } + mutex_unlock(&iommu->dgate);Ouch, no good at all. Keeping track of every DMA map is no good on POWER or other systems where IOMMU operations are a hot path. I think you'll need an iommu specific hook for this instead, which uses whatever data structures are natural for the IOMMU. For example a 1-level pagetable, like we use on POWER will just zero every entry.
Quoted 4 lines
It's already been noted in the docs that current users have relatively static mappings and a performance interface is TBD for dynamically backing streaming DMA. The current
vfio_iommuexposesiommu_ops, POWER will need to come up with something to expose instead.
Right, but I'm not just talking about the current map/unmap calls themselves. This infrastructure for tracking it looks like it's intended to be generic for all mapping methods. If not, I can't see the reason for it, because I don't think the current interface requires such tracking inherently.
Quoted 27 lines
Quoted 18 lines
Quoted 18 lines
Documentation/vfio.txt new file +18
-0+} + +static int vaddr_get_pfn(unsigned long vaddr, int rdwr, unsigned long *pfn) +{ + struct page *page[1]; + struct vm_area_struct *vma; + int ret = -EFAULT; + + if (get_user_pages_fast(vaddr, 1, rdwr, page) == 1) { + *pfn = page_to_pfn(page[0]); + return 0; + } + + down_read(¤t->mm->mmap_sem); + + vma = find_vma_intersection(current->mm, vaddr, vaddr + 1); + + if (vma && vma->vm_flags & VM_PFNMAP) {Quoted 8 lines
Documentation/vfio.txt
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+ *pfn = ((vaddr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; + if (is_invalid_reserved_pfn(*pfn)) + ret = 0; + }It's kind of nasty that you take
gup_fast(), already designed to grab pointers for multiple user pages, then just use it one page at a time, even for a big map.
Quoted 1 line
Yep, this needs work, but shouldn't really change the API.
Yes, this could be a later optimization.
Quoted 13 lines
Quoted 4 lines
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+ up_read(¤t->mm->mmap_sem); + + return ret; +}Quoted 8 lines
Documentation/vfio.txt
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+ +/* Map DMA region */ +/* dgate must be held */ +static int vfio_dma_map(struct vfio_iommu *iommu, unsigned long iova, + unsigned long vaddr, int npage, int rdwr)iova should be a
dma_addr_t. Bus address size need not match virtual address size, and may not fit in an unsigned long.
Quoted 1 line
ok.
Again, same consideratoin in many places of course.
Quoted 271 lines
Quoted 40 lines
Quoted 40 lines
Documentation/vfio.txt new file +40
-0+{ + unsigned long start = iova; + int i, ret, locked = 0, prot = IOMMU_READ; + + /* Verify pages are not already mapped */ + for (i = 0; i < npage; i++, iova += PAGE_SIZE) + if (iommu_iova_to_phys(iommu->domain, iova)) + return -EBUSY; + + iova = start; + + if (rdwr) + prot |= IOMMU_WRITE; + if (iommu->cache) + prot |= IOMMU_CACHE; + + for (i = 0; i < npage; i++, iova += PAGE_SIZE, vaddr += PAGE_SIZE) { + unsigned long pfn = 0; + + ret = vaddr_get_pfn(vaddr, rdwr, &pfn); + if (ret) { + __vfio_dma_unmap(iommu, start, i, rdwr); + return ret; + } + + /* Only add actual locked pages to accounting */ + if (!is_invalid_reserved_pfn(pfn)) + locked++; + + ret = iommu_map(iommu->domain, iova, + (phys_addr_t)pfn << PAGE_SHIFT, 0, prot); + if (ret) { + /* Back out mappings on error */ + put_pfn(pfn, rdwr); + __vfio_dma_unmap(iommu, start, i, rdwr); + return ret; + } + } + vfio_lock_acct(locked); + return 0;Quoted 8 lines
Documentation/vfio.txt
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+} + +static inline int ranges_overlap(unsigned long start1, size_t size1, + unsigned long start2, size_t size2) +{ + return !(start1 + size1 <= start2 || start2 + size2 <= start1);Needs overflow safety.
Yep.
Quoted 11 lines
Quoted 11 lines
Documentation/vfio.txt new file +11
-0+} + +static struct dma_map_page *vfio_find_dma(struct vfio_iommu *iommu, + dma_addr_t start, size_t size) +{ + struct list_head *pos; + struct dma_map_page *mlp; + + list_for_each(pos, &iommu->dm_list) { + mlp = list_entry(pos, struct dma_map_page, list); + if (ranges_overlap(mlp->daddr, NPAGE_TO_SIZE(mlp->npage),Quoted 8 lines
Documentation/vfio.txt
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+ start, size)) + return mlp; + } + return NULL; +}Again, keeping track of each dma map operation is no good for performance.
This is not the performance interface you're looking for.
Quoted 189 lines
Quoted 189 lines
Documentation/vfio.txt new file +189
-0+ +int vfio_remove_dma_overlap(struct vfio_iommu *iommu, dma_addr_t start, + size_t size, struct dma_map_page *mlp) +{ + struct dma_map_page *split; + int npage_lo, npage_hi; + + /* Existing dma region is completely covered, unmap all */ + if (start <= mlp->daddr && + start + size >= mlp->daddr + NPAGE_TO_SIZE(mlp->npage)) { + vfio_dma_unmap(iommu, mlp->daddr, mlp->npage, mlp->rdwr); + list_del(&mlp->list); + npage_lo = mlp->npage; + kfree(mlp); + return npage_lo; + } + + /* Overlap low address of existing range */ + if (start <= mlp->daddr) { + size_t overlap; + + overlap = start + size - mlp->daddr; + npage_lo = overlap >> PAGE_SHIFT; + npage_hi = mlp->npage - npage_lo; + + vfio_dma_unmap(iommu, mlp->daddr, npage_lo, mlp->rdwr); + mlp->daddr += overlap; + mlp->vaddr += overlap; + mlp->npage -= npage_lo; + return npage_lo; + } + + /* Overlap high address of existing range */ + if (start + size >= mlp->daddr + NPAGE_TO_SIZE(mlp->npage)) { + size_t overlap; + + overlap = mlp->daddr + NPAGE_TO_SIZE(mlp->npage) - start; + npage_hi = overlap >> PAGE_SHIFT; + npage_lo = mlp->npage - npage_hi; + + vfio_dma_unmap(iommu, start, npage_hi, mlp->rdwr); + mlp->npage -= npage_hi; + return npage_hi; + } + + /* Split existing */ + npage_lo = (start - mlp->daddr) >> PAGE_SHIFT; + npage_hi = mlp->npage - (size >> PAGE_SHIFT) - npage_lo; + + split = kzalloc(sizeof *split, GFP_KERNEL); + if (!split) + return -ENOMEM; + + vfio_dma_unmap(iommu, start, size >> PAGE_SHIFT, mlp->rdwr); + + mlp->npage = npage_lo; + + split->npage = npage_hi; + split->daddr = start + size; + split->vaddr = mlp->vaddr + NPAGE_TO_SIZE(npage_lo) + size; + split->rdwr = mlp->rdwr; + list_add(&split->list, &iommu->dm_list); + return size >> PAGE_SHIFT; +} + +int vfio_dma_unmap_dm(struct vfio_iommu *iommu, struct vfio_dma_map *dmp) +{ + int ret = 0; + size_t npage = dmp->size >> PAGE_SHIFT; + struct list_head *pos, *n; + + if (dmp->dmaaddr & ~PAGE_MASK) + return -EINVAL; + if (dmp->size & ~PAGE_MASK) + return -EINVAL; + + mutex_lock(&iommu->dgate); + + list_for_each_safe(pos, n, &iommu->dm_list) { + struct dma_map_page *mlp; + + mlp = list_entry(pos, struct dma_map_page, list); + if (ranges_overlap(mlp->daddr, NPAGE_TO_SIZE(mlp->npage), + dmp->dmaaddr, dmp->size)) { + ret = vfio_remove_dma_overlap(iommu, dmp->dmaaddr, + dmp->size, mlp); + if (ret > 0) + npage -= NPAGE_TO_SIZE(ret); + if (ret < 0 || npage == 0) + break; + } + } + mutex_unlock(&iommu->dgate); + return ret > 0 ? 0 : ret; +} + +int vfio_dma_map_dm(struct vfio_iommu *iommu, struct vfio_dma_map *dmp) +{ + int npage; + struct dma_map_page *mlp, *mmlp = NULL; + dma_addr_t daddr = dmp->dmaaddr; + unsigned long locked, lock_limit, vaddr = dmp->vaddr; + size_t size = dmp->size; + int ret = 0, rdwr = dmp->flags & VFIO_DMA_MAP_FLAG_WRITE; + + if (vaddr & (PAGE_SIZE-1)) + return -EINVAL; + if (daddr & (PAGE_SIZE-1)) + return -EINVAL; + if (size & (PAGE_SIZE-1)) + return -EINVAL; + + npage = size >> PAGE_SHIFT; + if (!npage) + return -EINVAL; + + if (!iommu) + return -EINVAL; + + mutex_lock(&iommu->dgate); + + if (vfio_find_dma(iommu, daddr, size)) { + ret = -EBUSY; + goto out_lock; + } + + /* account for locked pages */ + locked = current->mm->locked_vm + npage; + lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT; + if (locked > lock_limit && !capable(CAP_IPC_LOCK)) { + printk(KERN_WARNING "%s: RLIMIT_MEMLOCK (%ld) exceeded\n", + __func__, rlimit(RLIMIT_MEMLOCK)); + ret = -ENOMEM; + goto out_lock; + } + + ret = vfio_dma_map(iommu, daddr, vaddr, npage, rdwr); + if (ret) + goto out_lock; + + /* Check if we abut a region below */ + if (daddr) { + mlp = vfio_find_dma(iommu, daddr - 1, 1); + if (mlp && mlp->rdwr == rdwr && + mlp->vaddr + NPAGE_TO_SIZE(mlp->npage) == vaddr) { + + mlp->npage += npage; + daddr = mlp->daddr; + vaddr = mlp->vaddr; + npage = mlp->npage; + size = NPAGE_TO_SIZE(npage); + + mmlp = mlp; + } + } + + if (daddr + size) { + mlp = vfio_find_dma(iommu, daddr + size, 1); + if (mlp && mlp->rdwr == rdwr && mlp->vaddr == vaddr + size) { + + mlp->npage += npage; + mlp->daddr = daddr; + mlp->vaddr = vaddr; + + /* If merged above and below, remove previously + * merged entry. New entry covers it. */ + if (mmlp) { + list_del(&mmlp->list); + kfree(mmlp); + } + mmlp = mlp; + } + } + + if (!mmlp) { + mlp = kzalloc(sizeof *mlp, GFP_KERNEL); + if (!mlp) { + ret = -ENOMEM; + vfio_dma_unmap(iommu, daddr, npage, rdwr); + goto out_lock; + } + + mlp->npage = npage; + mlp->daddr = daddr; + mlp->vaddr = vaddr; + mlp->rdwr = rdwr; + list_add(&mlp->list, &iommu->dm_list); + } +Quoted 8 lines
Documentation/vfio.txt
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+out_lock: + mutex_unlock(&iommu->dgate); + return ret; +}This whole tracking infrastructure is way too complex to impose on every IOMMU. We absolutely don't want to do all this when just updating a 1-level pagetable.
Quoted 2 lines
If only POWER implemented an
iommu_opsso we had something on which we could base an alternate iommu model and pluggable iommu registration...
Yeah, yeah. I'm having to find gaps of time between fighting various fires to work on vfio-ish infrastructure stuff.
Quoted 59 lines
Quoted 12 lines
Quoted 12 lines
Documentation/vfio.txt new file +12
-0+static int vfio_iommu_release(struct inode *inode, struct file *filep) +{ + struct vfio_iommu *iommu = filep->private_data; + + vfio_release_iommu(iommu); + return 0; +} + +static long vfio_iommu_unl_ioctl(struct file *filep, + unsigned int cmd, unsigned long arg) +{ + struct vfio_iommu *iommu = filep->private_data;Quoted 8 lines
Documentation/vfio.txt
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+ int ret = -ENOSYS; + + if (cmd == VFIO_IOMMU_GET_FLAGS) { + u64 flags = VFIO_IOMMU_FLAGS_MAP_ANY; + + ret = put_user(flags, (u64 __user *)arg);Um.. flags surely have to come from the IOMMU driver.
This
vfio_iommuobject is backed byiommu_ops, which supports this mapping.Quoted 26 lines
Quoted 26 lines
Documentation/vfio.txt new file +26
-0+ } else if (cmd == VFIO_IOMMU_MAP_DMA) { + struct vfio_dma_map dm; + + if (copy_from_user(&dm, (void __user *)arg, sizeof dm)) + return -EFAULT; + + ret = vfio_dma_map_dm(iommu, &dm); + + if (!ret && copy_to_user((void __user *)arg, &dm, sizeof dm)) + ret = -EFAULT; + + } else if (cmd == VFIO_IOMMU_UNMAP_DMA) { + struct vfio_dma_map dm; + + if (copy_from_user(&dm, (void __user *)arg, sizeof dm)) + return -EFAULT; + + ret = vfio_dma_unmap_dm(iommu, &dm); + + if (!ret && copy_to_user((void __user *)arg, &dm, sizeof dm)) + ret = -EFAULT; + } + return ret; +} + +#ifdef CONFIG_COMPATQuoted 8 lines
Documentation/vfio.txt
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+static long vfio_iommu_compat_ioctl(struct file *filep, + unsigned int cmd, unsigned long arg) +{ + arg = (unsigned long)compat_ptr(arg); + return vfio_iommu_unl_ioctl(filep, cmd, arg);Um, this only works if the structures are exactly compatible between 32-bit and 64-bit ABIs. I don't think that is always true.
Quoted 2 lines
I think all our structure sizes are independent of host width. If I'm missing something, let me know.
Ah, for structures, that might be true. I was seeing the bunch of ioctl()s that take ints.
Quoted 78 lines
Quoted 56 lines
Quoted 56 lines
Documentation/vfio.txt new file +11
-0+} +#endif /* CONFIG_COMPAT */ + +const struct file_operations vfio_iommu_fops = { + .owner = THIS_MODULE, + .release = vfio_iommu_release, + .unlocked_ioctl = vfio_iommu_unl_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = vfio_iommu_compat_ioctl, +#endif +};drivers/vfio/vfio_main.c new file +39
-0@@ -0,0 +1,1151 @@ +/* +* VFIO framework +* +* Copyright (C) 2011 Red Hat, Inc. All rights reserved. +* Author: Alex Williamson <[email protected]> +* +* This program is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License version 2 as +* published by the Free Software Foundation. +* +* Derived from original vfio: +* Copyright 2010 Cisco Systems, Inc. All rights reserved. +* Author: Tom Lyon, [email protected] +*/ + +#include <linux/cdev.h> +#include <linux/compat.h> +#include <linux/device.h> +#include <linux/file.h> +#include <linux/anon_inodes.h> +#include <linux/fs.h> +#include <linux/idr.h> +#include <linux/iommu.h> +#include <linux/mm.h> +#include <linux/module.h> +#include <linux/slab.h> +#include <linux/string.h> +#include <linux/uaccess.h> +#include <linux/vfio.h> +#include <linux/wait.h> + +#include "vfio_private.h" + +#define DRIVER_VERSION "0.2" +#define DRIVER_AUTHOR "Alex Williamson <[email protected]>" +#define DRIVER_DESC "VFIO - User Level meta-driver" + +static int allow_unsafe_intrs; +module_param (allow_unsafe_intrs, int,0 );Quoted 8 lines
drivers/vfio/vfio_main.c line 41
Quoted 2 lines
drivers/vfio/vfio_main.c new file +2
-0+MODULE_PARM_DESC (allow_unsafe_intrs, +"Allow use of IOMMUs which do not support interrupt remapping" );This should not be a global option, but part of the AMD/Intel IOMMU specific code. In general it's a question of how strict the IOMMU driver is about isolation when it determines what the groups are, and only the IOMMU driver can know what the possibilities are for its class of hardware.
I agree this should probably be tied more closely to the iommu driver, but again, we only have
iommu_opsright now.<snip>
Quoted 8 lines
drivers/vfio/vfio_main.c line 496
Quoted 5 lines
drivers/vfio/vfio_main.c new file +5
-0+ +/* Attempt to merge the group pointed to by fd into group. The merge-ee +* group must not have an iommu or any devices open because we cannot +* maintain that context across the merge. The merge-er group can be +* in use. */ Yeah, so merge-er group in use still has its problems, because it could affect what the IOMMU is capable of.
Quoted 3 lines
As seen below, we deny merging if the iommu domains are not exactly compatible. Our notion of what compatible means depends on what
iommu_opsexposes though.
Ok.
Quoted 21 lines
Quoted 12 lines
Quoted 12 lines
drivers/vfio/vfio_main.c new file +12
-0+static int vfio_group_merge (struct vfio_group *group,int fd) +{ +struct vfio_group *new; +struct vfio_iommu *old_iommu; +struct file *file; +int ret =0 ; +bool opened = false; + +mutex_lock (&vfio.lock); + + file =fget (fd); +if (!file) {Quoted 8 lines
drivers/vfio/vfio_main.c line 514
Quoted 6 lines
drivers/vfio/vfio_main.c new file +6
-0+ ret = -EBADF ; + goto out_noput; + } + +/* Sanity check, is this really our fd? */ +if (file->f_op != &vfio_group_fops) {This should be a
WARN_ONorBUG_ONrather than just an error return, surely.
Quoted 4 lines
No, I don't think so. We're passed a file descriptor that could be for anything. If the user passed a file descriptor for something that's not a vfio group, that's a user error, not an internal consistency error of vfio.
Sorry, I was mixing up which of the fd arguments was which.
Quoted 122 lines
Quoted 113 lines
Quoted 113 lines
drivers/vfio/vfio_main.c new file +113
-0+ ret = -EINVAL ; + goto out; + } + + new = file->private_data; + +if (!new || new == group || !new->iommu || + new->iommu->domain || new->bus != group->bus) { + ret = -EINVAL ; + goto out; + } + +/* We need to attach all the devices to each domain separately +* in order to validate that the capabilities match for both. */ + ret =__vfio_open_iommu (new->iommu); +if (ret) + goto out; + +if (!group->iommu->domain) { + ret =__vfio_open_iommu (group->iommu); +if (ret) + goto out; + opened = true; + } + +/* If cache coherency doesn't match we'd potentialy need to +* remap existing iommu mappings in the merge-er domain. +* Poor return to bother trying to allow this currently. */ +if (iommu_domain_has_cap (group->iommu->domain, +IOMMU_CAP_CACHE_COHERENCY ) != +iommu_domain_has_cap (new->iommu->domain, +IOMMU_CAP_CACHE_COHERENCY )) { +__vfio_close_iommu (new->iommu); +if (opened) +__vfio_close_iommu (group->iommu); + ret = -EINVAL ; + goto out; + } + +/* Close the iommu for the merge-ee and attach all its devices +* to the merge-er iommu. */ +__vfio_close_iommu (new->iommu); + + ret =__vfio_iommu_attach_group (group->iommu, new); +if (ret) + goto out; + +/* set_iommu unlinks new from the iommu, so save a pointer to it */ + old_iommu = new->iommu; +__vfio_group_set_iommu (new, group->iommu); +kfree (old_iommu); + +out: +fput (file); +out_noput: +mutex_unlock (&vfio.lock); +return ret; +} + +/* Unmerge the group pointed to by fd from group. */ +static int vfio_group_unmerge (struct vfio_group *group,int fd) +{ +struct vfio_group *new; +struct vfio_iommu *new_iommu; +struct file *file; +int ret =0 ; + +/* Since the merge-out group is already opened, it needs to +* have an iommu struct associated with it. */ + new_iommu =kzalloc (sizeof (*new_iommu),GFP_KERNEL ); +if (!new_iommu) +return -ENOMEM ; + +INIT_LIST_HEAD (&new_iommu->group_list); +INIT_LIST_HEAD (&new_iommu->dm_list); +mutex_init (&new_iommu->dgate); + new_iommu->bus = group->bus; + +mutex_lock (&vfio.lock); + + file =fget (fd); +if (!file) { + ret = -EBADF ; + goto out_noput; + } + +/* Sanity check, is this really our fd? */ +if (file->f_op != &vfio_group_fops) { + ret = -EINVAL ; + goto out; + } + + new = file->private_data; +if (!new || new == group || new->iommu != group->iommu) { + ret = -EINVAL ; + goto out; + } + +/* We can't merge-out a group with devices still in use. */ +if (__vfio_group_devs_inuse (new)) { + ret = -EBUSY ; + goto out; + } + +__vfio_iommu_detach_group (group->iommu, new); +__vfio_group_set_iommu (new, new_iommu); + +out: +fput (file); +out_noput: +if (ret) +kfree (new_iommu); +mutex_unlock (&vfio.lock);Quoted 8 lines
drivers/vfio/vfio_main.c line 632
Quoted 5 lines
drivers/vfio/vfio_main.c new file +5
-0+return ret; +} + +/* Get a new iommu file descriptor. This will open the iommu, setting +* the current->mm ownership if it's not already set. */ I know I've had this explained to me several times before, but I've forgotten again. Why do we need to wire the iommu to an mm?
Quoted 4 lines
We're mapping process virtual addresses into the IOMMU, so it makes sense to restrict ourselves to a single virtual address space. It also enforces the ownership, that only a single mm is in control of the group.
Neither of those seems conclusive to me, but I remember that I saw a strong reason earlier, even if I can't remember it now.
Quoted 33 lines
Quoted 24 lines
Quoted 24 lines
drivers/vfio/vfio_main.c new file +24
-0+static int vfio_group_get_iommu_fd (struct vfio_group *group) +{ +int ret =0 ; + +mutex_lock (&vfio.lock); + +if (!group->iommu->domain) { + ret =__vfio_open_iommu (group->iommu); +if (ret) + goto out; + } + + ret =anon_inode_getfd ("[vfio-iommu]" , &vfio_iommu_fops, + group->iommu,O_RDWR ); +if (ret <0 ) + goto out; + + group->iommu->refcnt++; +out: +mutex_unlock (&vfio.lock); +return ret; +} + +/* Get a new device file descriptor. This will open the iommu, setting Quoted 8 lines
drivers/vfio/vfio_main.c line 661
Quoted 5 lines
drivers/vfio/vfio_main.c new file +5
-0+* the current->mm ownership if it's not already set. It's difficult to +* specify the requirements for matching a user supplied buffer to a +* device, so we use a vfio driver callback to test for a match. For +* PCI, dev_name(dev) is unique, but other drivers may require including +* a parent device string. */ At some point we probably want an interface to enumerate the devices too, but that can probably wait.
Quoted 2 lines
That's what I decided as well. I also haven't been able to come up with an interface for it that doesn't make me want to vomit.
Ok.
Signature · 4 lines
David Gibson | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you. NOT _the_ _other_ | _way_ _around_! http://www.ozlabs.org/~dgibson
Quoted 3 lines · David Gibson
Quoted 2 lines · Alex Williamson
Quoted 1 line · David Gibson
On Thu, Nov 03, 2011 at 02:12:24PM -0600, Alex Williamson wrote:
<snip>
Quoted 30 lines
Quoted 30 lines
Quoted 29 lines
Quoted 13 lines
Documentation/vfio.txt new file +13
-0+Groups, Devices, IOMMUs, oh my +------------------------------------------------------------------------------- + +A fundamental component of VFIO is the notion of IOMMU groups. IOMMUs +can't always distinguish transactions from each individual device in +the system. Sometimes this is because of the IOMMU design, such as with +PEs, other times it's caused by the I/O topology, for instance a +PCIe-to-PCI bridge masking all devices behind it. We call the sets of +devices created by these restictions IOMMU groups (or just "groups" for +this document). + +The IOMMU cannot distiguish transactions between the individual devices +within the group, therefore the group is the basic unit of ownership forDocumentation/vfio.txt line 54
Quoted 10 lines
Documentation/vfio.txt new file +10
-0+a userspace process. Because of this, groups are also the primary +interface to both devices and IOMMU domains in VFIO. + +The VFIO representation of groups is created as devices are added into +the framework by a VFIO bus driver. The vfio-pci module is an example +of a bus driver. This module registers devices along with a set of bus +specific callbacks with the VFIO core. These callbacks provide the +interfaces later used for device access. As each new group is created, +as determined by iommu_device_group(), VFIO creates a /dev/vfio/$GROUP +character device.Ok.. so, the fact that it's called "vfio-pci" suggests that the VFIO
bus driver is per bus type, not per bus instance. But grouping
constraints could be per bus instance, if you have a couple of different models of PCI host bridge with IOMMUs of different capabilities built in, for example.
Quoted 7 lines
Quoted 2 lines
Yes, vfio-pci manages devices on the
pci_bus_type; per type, not per bus instance.Ok, how can that work. vfio-pci is responsible for generating the groupings, yes? For which it needs to know the iommu/host bridge's isolation capabilities, which vary depending on the type of host bridge.
No, grouping is done at the iommu driver level. vfio gets groupings via iomm_device_group(), which uses the iommu_ops for the bus_type of the requested device. I'll attempt to clarify where groups come from in the documentation.
Quoted 94 lines
Quoted 53 lines
IOMMUs also register drivers per bus type, not per bus
instance. The IOMMU driver is free to impose any constraints it wants.Quoted 38 lines
Quoted 25 lines
Documentation/vfio.txt new file +25
-0+In addition to the device enumeration and callbacks, the VFIO bus driver +also provides a traditional device driver and is able to bind to devices +on it's bus. When a device is bound to the bus driver it's available to +VFIO. When all the devices within a group are bound to their bus drivers, +the group becomes "viable" and a user with sufficient access to the VFIO +group chardev can obtain exclusive access to the set of group devices. + +As documented in linux/vfio.h, several ioctls are provided on the +group chardev: + +#define VFIO_GROUP_GET_FLAGS _IOR(';', 100, __u64) + #define VFIO_GROUP_FLAGS_VIABLE (1 << 0) + #define VFIO_GROUP_FLAGS_MM_LOCKED (1 << 1) +#define VFIO_GROUP_MERGE _IOW(';', 101, int) +#define VFIO_GROUP_UNMERGE _IOW(';', 102, int) +#define VFIO_GROUP_GET_IOMMU_FD _IO(';', 103) +#define VFIO_GROUP_GET_DEVICE_FD _IOW(';', 104, char *) + +The last two ioctls return new file descriptors for accessing +individual devices within the group and programming the IOMMU. Each of +these new file descriptors provide their own set of file interfaces. +These ioctls will fail if any of the devices within the group are not +bound to their VFIO bus driver. Additionally, when either of these +interfaces are used, the group is then bound to the struct_mm of the +caller. The GET_FLAGS ioctl can be used to view the state of the group.Documentation/vfio.txt
Quoted 10 lines
Documentation/vfio.txt new file +10
-0+ +When either the GET_IOMMU_FD or GET_DEVICE_FD ioctls are invoked, a +new IOMMU domain is created and all of the devices in the group are +attached to it. This is the only way to ensure full IOMMU isolation +of the group, but potentially wastes resources and cycles if the user +intends to manage multiple groups with the same set of IOMMU mappings. +VFIO therefore provides a group MERGE and UNMERGE interface, which +allows multiple groups to share an IOMMU domain. Not all IOMMUs allow +arbitrary groups to be merged, so the user should assume merging is +opportunistic.I do not think "opportunistic" means what you think it means..
Quoted 11 lines
Quoted 9 lines
A new group, with no open device or IOMMU file
Documentation/vfio.txt new file +7
-0+descriptors, can be merged into an existing, in-use, group using the +MERGE ioctl. A merged group can be unmerged using the UNMERGE ioctl +once all of the device file descriptors for the group being merged +"out" are closed. + +When groups are merged, the GET_IOMMU_FD and GET_DEVICE_FD ioctls are +essentially fungible between group file descriptors (ie. if deviceA
IDNT "fungible" MWYTIM, either.
Quoted 1 line
Hmm, feel free to suggest. Maybe we're hitting .us vs .au connotation.
In any case, I don't think it's a word whose meaning is unambiguous enough to use here.
Quoted 19 lines
Quoted 13 lines
Documentation/vfio.txt line 103
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+is in group X, and X is merged with Y, a file descriptor for A can be +retrieved using GET_DEVICE_FD on Y. Likewise, GET_IOMMU_FD returns a +file descriptor referencing the same internal IOMMU object from either +X or Y). Merged groups can be dissolved either explictly with UNMERGE +or automatically when ALL file descriptors for the merged group are +closed (all IOMMUs, all devices, all groups).Blech. I'm really not liking this merge/unmerge API as it stands, it's horribly confusing. At the very least, we need some better terminology. We need some term for the metagroups; supergroups; iommu domains or-at-least-they-will-be-once-we-open-the-iommu or whathaveyous.
Quoted 5 lines
The first confusing thing about this interface is that each open group handle actually refers to two different things; the original group you opened and the metagroup it's a part of. For the
GET_IOMMU_FDandGET_DEVICE_FDoperations, you're using the metagroup and two "merged" group handles are interchangeable.Quoted 7 lines
Fungible, even ;)
Quoted 2 lines
For other MERGE and especially
UNMERGE operations, it matters which is the original group.If I stick two LEGO blocks together, I need to identify the individual block I want to remove to pull them back apart...
Yeah, I'm starting to get my head around the model, but the current description of it doesn't help very much. In particular the terms "merge" and "unmerge" lead one to the wrong mental model, I think.
Quoted 5 lines
Quoted 4 lines
The semantics of "merge" and "unmerge" under those names are really non-obvious. Merge kind of has to merge two whole metagroups, but it's unclear if unmerge reverses one merge, or just takes out one (atom) group. These operations need better names, at least.
Quoted 7 lines
Quoted 5 lines
Christian suggested a change to UNMERGE that we do not need to specify a group to unmerge "from". This makes it more like a list implementation except there's no defined
list_head. Any member of the list can pull in a new entry. Calling UNMERGE on any member extracts that member.I think that's a good idea, but "unmerge" is not a good word for it.
I can't think of better, if you can, please suggest.
Quoted 22 lines
Quoted 11 lines
Quoted 10 lines
Then it's unclear what order you can do various operations, and which order you can open and close various things. You can kind of figure it out but it takes far more thinking than it should.
So at the _very_ least, we need to invent new terminology and find a much better way of describing this API's semantics. I still think an entirely different interface, where metagroups are created from outside with a lifetime that's not tied to an fd would be a better idea.
Quoted 3 lines
As we've discussed previously, configfs provides part of this, but has no ioctl support. It doesn't make sense to me to go play with groups in configfs, but then still interact with them via a char dev.
Why not? You configure, say, loopback devices with losetup, then use them as a block device. Similar with nbd. You can configure serial devices with setserial, then use them as a char dev.
Quoted 2 lines
It also
splits the ownership model
Quoted 6 lines
I'm not even sure what that means.
Quoted 2 lines
and makes it harder to enforce who gets to interact with the devices vs who gets to manipulate groups.
How so.
Let's map out what a configfs interface would look like, maybe I'll convince myself it's on the table. We'd probably start with
/config/vfio/$bus_type.name/
That would probably be pre-populated with a bunch of $groupid files, matching /dev/vfio/$bus_type.name/$groupid char dev files (assuming configfs can pre-populate files). To make a user defined group, we might then do:
mkdir /config/vfio/$bus_type.name/my_group
That would generate a /dev/vfio/$bus_type.name/my_group char dev. To add groups to the new my_group "super group", we'd need to do something like:
ln -s /config/vfio/$bus_type.name/$groupidA /config/vfio/$bus_type.name/my_group/nic_group
I might then add a second group as:
ln -s /config/vfio/$bus_type.name/$groupidB /config/vfio/$bus_type.name/my_group/hba_group
Either link could fail if the target group is not viable, the group is already in use, or the second link could fail if the iommu domains were incompatible.
Do these links cause /dev/vfio/$bus_type.name/{$groupidA,$groupidB} to disappear? If not, do we allow them to be opened? Linking would also have to fail if we later tried to link one of these groupids to a different super group.
Now we want to give my_group to a user, so we have to go back to /dev and
chown $user /dev/vfio/$bus_type.name/my_group
At this point my_group would have the existing set of group ioctls sans {UN}MERGE, of course.
So $user can use the super group, but not manipulate it's members. Do we then allow:
chown $user /config/vfio/$bus_type.name/my_group
If so, what does it imply about the user then doing:
ln -s /config/vfio/$bus_type.name/$groupidC /config/vfio/$bus_type.name/my_group/stolen_group
Would we instead need to chown the configfs groups as well as the super group?
chown $user /config/vfio/$bus_type.name/my_group
chown $user /config/vfio/$bus_type.name/$groupidA
chown $user /config/vfio/$bus_type.name/$groupidB
ie:
# chown $user:$user /config/vfio/$bus_type.name/$groupC $ ln -s /config/vfio/$bus_type.name/$groupidC /config/vfio/$bus_type.name/my_group/given_group
(linking has to look at the permissions of the target as well as the link name)
Now we've introduced that we have ownership of configfs entries, what does that imply about the char dev entries? For instance, can $userA own /dev/vfio/$bus_type.name/$groupidA, but $userB own the configfs file? We also have another security consideration that an exploit on the host might allow a 3rd party to insert a device into a group.
This is where I start to get lost in the complexity versus simply giving the user permissions for the char dev and allowing them to stick groups together so long as the have permissions for the group.
We also add an entire filesystem to the interface that already spans sysfs, dev, eventfds and potentially netlink.
If terminology is the complaint against the {UN}MERGE ioctl interface, I'm still not sold that configfs is the answer. /me goes to the thesaurus... amalgamate? blend? combine? cement? unite? join?
Quoted 87 lines
Quoted 15 lines
The current
model really isn't that complicated, imho. As always, feel free to suggest specific models. If you have a specific terminology other than MERGE, please suggest.Quoted 5 lines
Now, you specify that you can't use a group as the second argument of a merge if it already has an open iommu, but it's not clear from the doc if you can merge things into a group with an open iommu.
From above:
A new group, with no open device or IOMMU file descriptors, can be merged into an existing, in-use, group using the MERGE ioctl.
^^^^^^Quoted 7 lines
Quoted 4 lines
Banning
this would make life simpler, because the IOMMU's effective capabilities may change if you add more devices to the domain. That's yet another non-obvious constraint in the interface ordering, though.Banning this would prevent using merged groups with hotplug, which I consider to be a primary use case.
Yeah, fair enough, based on your later comments w.r.t. only combining feature compatible groups.
Quoted 40 lines
Quoted 6 lines
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+The IOMMU file descriptor provides this set of ioctls: + +#define VFIO_IOMMU_GET_FLAGS _IOR(';', 105, __u64) + #define VFIO_IOMMU_FLAGS_MAP_ANY (1 << 0) +#define VFIO_IOMMU_MAP_DMA _IOWR(';', 106, struct vfio_dma_map) +#define VFIO_IOMMU_UNMAP_DMA _IOWR(';', 107, struct vfio_dma_map)Quoted 8 lines
Quoted 5 lines
Documentation/vfio.txt new file +4
-0+ +The GET_FLAGS ioctl returns basic information about the IOMMU domain. +We currently only support IOMMU domains that are able to map any +virtual address to any IOVA. This is indicated by the MAP_ANYflag.
So. I tend to think of an IOMMU mapping IOVAs to memory pages, rather than memory pages to IOVAs.
I do too, not sure why I wrote it that way, will fix.
Quoted 6 lines
The IOMMU itself, of course maps to
physical addresses, and the meaning of "virtual address" in this context is not really clear. I think you would be better off saying the IOMMU can map any IOVA to any memory page. From a hardware POV that means any physical address, but of course for a VFIO user a page is specified by its process virtual address.Will fix.
Quoted 7 lines
I think we need to pin exactly what "
MAP_ANY" means down better. Now, VFIO is pretty much a lost cause if you can't map any normal process memory page into the IOMMU, so I think the only thing that is really covered is IOVAs. But saying "can map any IOVA" is not clear, because if you can't map it, it's not a (valid) IOVA. Better to say that IOVAs can be any 64-bit value, which I think is what you really mean here.ok
Quoted 3 lines
Of course, since POWER is a platform where this is *not* true, I'd prefer to have something giving the range of valid IOVAs in the core to start with.
Quoted 5 lines
Since
iommu_opsdoes not yet have any concept of this (nudge, nudge), I figured this would be added later. A possible implementation would be that such an iommu would not setMAP_ANY, would add a new flag forMAP_RANGE, and provide a newVFIO_IOMMU_GET_RANGE_INFOioctl to describe it. I'm guaranteed to get it wrong if I try to predict all your needs.Hrm. "ANY" just really bothers me because "any iova" is not as clear a concept as it first appears. For starters it's actually "any page aligned" at the very least. But then it's only any 64-bit address for busses which have full 64-bit addressing (and I do wonder if there are any north bridges out there that forgot to implement some of the upper PCI address bits properly, given that 64-bit CPUs rarely actually implement more than 40-something physical address bits in practice).
I'd prefer to see at least something to advertise min and max IOVA and IOVA alignment. That's enough to cover x86 and POWER, including possible variants with an IOMMU page size different to the system page size (note that POWER kernels can have 64k pages as a config option, which means a TCE page size different to the system page size is quite common).
Quoted 2 lines
Obviously there could be more complex constraints that we would need to advertise with option bits.
x86 has limitations as well. I don't think most x86 IOMMUs support a
full 64bit IOVA space, so point take.
struct vfio_iommu_info {
__u64 len; /* or structlen/arglen */
__u64 flags; /* replaces VFIO_IOMMU_GET_FLAGS, none defined yet */
__u64 iova_max;
__u64 iova_min;
__u64 granularity;
};#define VFIO_IOMMU_GET_INFO _IOR(';', xxx, struct vfio_iommu_info)
Is granularity the minimum granularity, typically PAGE_SIZE barring special configurations noted above, or is it a bitmap of supported granularities? Ex. If we support 4k normal pages and 2M large pages, we might set bits 12 and 21.
Quoted 13 lines
Quoted 13 lines
Quoted 12 lines
Documentation/vfio.txt line 120
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+ +The (UN)MAP_DMA commands make use of struct vfio_dma_map for mapping +and unmapping IOVAs to process virtual addresses: + +struct vfio_dma_map { + __u64 len; /* length of structure */Thanks for adding these structure length fields. But I think they should be called something other than 'len', which is likely to be confused with size (or some other length that's actually related to the operation's parameters). Better to call it 'structlen' or 'argslen' or something.
Quoted 7 lines
Quoted 2 lines
Ok. As Scott noted, I've failed to implement these in a way that actually allows extension, but I'll work on it.
Right. I had failed to realise quite how the encoding of structure size into the ioctl worked. With that in place, arguably we don't really need the size in the structure itself, because we can still have multiple sized versions of the ioctl. Still, whichever.
Hmm, that might be cleaner than eliminating the size with just using _IO(). So we might have something like:
#define VFIO_IOMMU_MAP_DMA _IOWR(';', 106, struct vfio_dma_map)
#define VFIO_IOMMU_MAP_DMA_V2 _IOWR(';', 106, struct vfio_dma_map_v2)
For which the driver might do:
case VFIO_IOMMU_MAP_DMA:
case VFIO_IOMMU_MAP_DMA_V2:
{
struct vfio_dma_map map;
/* We don't care about the extra v2 bits */
if (copy_from_user(&map, (void __user *)arg, sizeof map))
return -EFAULT;...
That presumes v2 is compatible other than extra fields. Any objections (this gets rid of length from all ioctl passed structs)?
Quoted 96 lines
Quoted 54 lines
Quoted 10 lines
Documentation/vfio.txt line 125
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+ __u64 vaddr; /* process virtual addr */ + __u64 dmaaddr; /* desired and/or returned dma address */ + __u64 size; /* size in bytes */ + __u64 flags; +#define VFIO_DMA_MAP_FLAG_WRITE (1 << 0) /* req writeable DMA mem */Make it independent READ and WRITE flags from the start. Not all combinations will be be valid on all hardware, but that way we have the possibilities covered without having to use strange encodings later.
Ok.
Quoted 12 lines
Quoted 12 lines
Documentation/vfio.txt new file +12
-0+}; + +Current users of VFIO use relatively static DMA mappings, not requiring +high frequency turnover. As new users are added, it's expected that the +IOMMU file descriptor will evolve to support new mapping interfaces, this +will be reflected in the flags and may present new ioctls and file +interfaces. + +The device GET_FLAGS ioctl is intended to return basic device type and +indicate support for optional capabilities. Flags currently include whether +the device is PCI or described by Device Tree, and whether the RESET ioctl +is supported:Quoted 8 lines
Documentation/vfio.txt line 141
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+ +#define VFIO_DEVICE_GET_FLAGS _IOR(';', 108, __u64) + #define VFIO_DEVICE_FLAGS_PCI (1 << 0) + #define VFIO_DEVICE_FLAGS_DT (1 << 1)TBH, I don't think the VFIO for DT stuff is mature enough yet to be in an initial infrastructure patch, though we should certainly be discussing it as an add-on patch.
I agree for DT, and PCI should be added with vfio-pci, not the initial core.
Quoted 8 lines
Quoted 8 lines
+ #define
VFIO_DEVICE_FLAGS_RESET(1 << 2)Documentation/vfio.txt new file +7
-0+ +The MMIO and IOP resources used by a device are described by regions. +The GET_NUM_REGIONS ioctl tells us how many regions the device supports: + +#define VFIO_DEVICE_GET_NUM_REGIONS _IOR(';', 109, int) + +Regions are described by a struct vfio_region_info, which is retrieved byQuoted 8 lines
Documentation/vfio.txt line 153
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+using the GET_REGION_INFO ioctl with vfio_region_info.index field set to +the desired region (0 based index). Note that devices may implement zero +sized regions (vfio-pci does this to provide a 1:1 BAR to region index +mapping).So, I think you're saying that a zero-sized region is used to encode a NOP region, that is, to basically put a "no region here" in between valid region indices. You should spell that out.
Quoted 8 lines
Ok.
Quoted 3 lines
[Incidentally, any chance you could borrow one of RH's tech writers for this? I'm afraid you seem to lack the knack for clear and easily read documentation]
Thanks for the encouragement :-\ It's no wonder there isn't more content in Documentation.
Sigh. Alas, yes.
Quoted 22 lines
Quoted 11 lines
Documentation/vfio.txt line 162
Quoted 8 lines
Documentation/vfio.txt new file +8
-0+struct vfio_region_info { + __u32 len; /* length of structure */ + __u32 index; /* region number */ + __u64 size; /* size in bytes of region */ + __u64 offset; /* start offset of region */ + __u64 flags; +#define VFIO_REGION_INFO_FLAG_MMAP (1 << 0) +#define VFIO_REGION_INFO_FLAG_RO (1 << 1)Again having separate read and write bits from the start will save strange encodings later.
Seems highly unlikely, but we have bits to waste...
Quoted 7 lines
Documentation/vfio.txt line 165
Quoted 3 lines
Documentation/vfio.txt new file +3
-0+#define VFIO_REGION_INFO_FLAG_PHYS_VALID (1 << 2) + __u64 phys; /* physical address of region */ +};I notice there is no field for "type" e.g. MMIO vs. PIO vs. config space for PCI. If you added that having a NONE type might be a clearer way of encoding a non-region than just having size==0.
Quoted 8 lines
I thought there was some resistance to including MMIO and PIO bits in the flags. If that's passed, I can add it, but PCI can determine this through config space (and vfio-pci exposes config space at a fixed index). Having a regions w/ size == 0, MMIO and PIO flags unset seems a little redundant if that's the only reason for having them. A NONE flag doesn't make sense to me. Config space isn't NONE, but neither is it MMIO nor PIO; and someone would probably be offended about even mentioning PIO in the specification.
Quoted 8 lines
No, my concept was that NONE would be used for the indexes where there is no valid BAR. I'll buy your argument on why not to include the PCI (or whatever) address space type here.
What I'm just a bit concerned by is whether we could have a case (not for PCI) of a real resource that still has size 0 - e.g. maybe some sort of doorbell that can't be read or written, but can be triggered some other way. I guess that's probably unlikely though.
Right, and if somehow you had such a region where the size is zero, but allowed some kind of operation on it, we could define a flag for it.
Quoted 74 lines
Quoted 21 lines
Quoted 12 lines
Quoted 12 lines
Documentation/vfio.txt new file +12
-0+ +#define VFIO_DEVICE_GET_REGION_INFO _IOWR(';', 110, struct vfio_region_info) + +The offset indicates the offset into the device file descriptor which +accesses the given range (for read/write/mmap/seek). Flags indicate the +available access types and validity of optional fields. For instance +the phys field may only be valid for certain devices types. + +Interrupts are described using a similar interface. GET_NUM_IRQS +reports the number or IRQ indexes for the device. + +#define VFIO_DEVICE_GET_NUM_IRQS _IOR(';', 111, int)Quoted 8 lines
Documentation/vfio.txt line 182
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+ +struct vfio_irq_info { + __u32 len; /* length of structure */ + __u32 index; /* IRQ number */ + __u32 count; /* number of individual IRQs */Is there a reason for allowing irqs in batches like this, rather than having each MSI be reflected by a separate
irq_info?Quoted 7 lines
Yes, bus drivers like vfio-pci can define index 1 as the MSI info structure and index 2 as MSI-X. There's really no need to expose 57 individual MSI interrupts and try to map them to the correct device specific MSI type if they can only logically be enabled in two distinct groups. Bus drivers with individually controllable MSI vectors are free to expose them separately. I assume device tree paths would help associate an index to a specific interrupt.
Ok, fair enough.
Quoted 36 lines
Quoted 8 lines
Documentation/vfio.txt line 188
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+ __u64 flags; +#define VFIO_IRQ_INFO_FLAG_LEVEL (1 << 0) +}; + +Again, zero count entries are allowed (vfio-pci uses a static interrupt +type to index mapping).I know what you mean, but you need a clearer way to express it.
I'll work on it.
Quoted 16 lines
Quoted 16 lines
Documentation/vfio.txt new file +16
-0+Information about each index can be retrieved using the GET_IRQ_INFO +ioctl, used much like GET_REGION_INFO. + +#define VFIO_DEVICE_GET_IRQ_INFO _IOWR(';', 112, struct vfio_irq_info) + +Individual indexes can describe single or sets of IRQs. This provides the +flexibility to describe PCI INTx, MSI, and MSI-X using a single interface. + +All VFIO interrupts are signaled to userspace via eventfds. Integer arrays, +as shown below, are used to pass the IRQ info index, the number of eventfds, +and each eventfd to be signaled. Using a count of 0 disables the interrupt. + +/* Set IRQ eventfds, arg[0] = index, arg[1] = count, arg[2-n] = eventfds */ +#define VFIO_DEVICE_SET_IRQ_EVENTFDS _IOW(';', 113, int) + +When a level triggered interrupt is signaled, the interrupt is maskedQuoted 8 lines
Documentation/vfio.txt line 209
Quoted 4 lines
Documentation/vfio.txt new file +4
-0+on the host. This prevents an unresponsive userspace driver from +continuing to interrupt the host system. After servicing the interrupt, +UNMASK_IRQ is used to allow the interrupt to retrigger. Note that level +triggered interrupts implicitly have a count of 1 per index.This is a silly restriction. Even PCI devices can have up to 4 LSIs on a function in theory, though no-one ever does. Embedded devices can and do have multiple level interrupts.
Quoted 4 lines
Per the PCI spec, an individual PCI function can only ever have, at most, a single INTx line. A multi-function *device* can have up to 4 INTx lines, but what we're exposing here is a struct device, ie. a PCI function.
Ah, my mistake.
Quoted 8 lines
Quoted 4 lines
Other devices could certainly have multiple level interrupts, and if grouping them as we do with MSI on PCI makes sense, please let me know. I just didn't see the value in making the unmask operations handle sub-indexes if it's not needed.
I don't know of anything off hand. But I can't see any consideration that would make it unlikely either. I generally don't trust anything *not* to exist in embedded space.
Fair enough. Level IRQs are still triggered individually, so unmasking is too, which means UNMASK_IRQ takes something like { int index; int subindex }.
SET_UNMASK_IRQ_EVENTFDS should follow SET_IRQ_EVENTFDS and take { int index; int count; int fds[] }.
Quoted 65 lines
Quoted 65 lines
Quoted 42 lines
Quoted 42 lines
Documentation/vfio.txt new file +42
-0+ +/* Unmask IRQ index, arg[0] = index */ +#define VFIO_DEVICE_UNMASK_IRQ _IOW(';', 114, int) + +Level triggered interrupts can also be unmasked using an irqfd. Use +SET_UNMASK_IRQ_EVENTFD to set the file descriptor for this. + +/* Set unmask eventfd, arg[0] = index, arg[1] = eventfd */ +#define VFIO_DEVICE_SET_UNMASK_IRQ_EVENTFD _IOW(';', 115, int) + +When supported, as indicated by the device flags, reset the device. + +#define VFIO_DEVICE_RESET _IO(';', 116) + +Device tree devices also invlude ioctls for further defining the +device tree properties of the device: + +struct vfio_dtpath { + __u32 len; /* length of structure */ + __u32 index; + __u64 flags; +#define VFIO_DTPATH_FLAGS_REGION (1 << 0) +#define VFIO_DTPATH_FLAGS_IRQ (1 << 1) + char *path; +}; +#define VFIO_DEVICE_GET_DTPATH _IOWR(';', 117, struct vfio_dtpath) + +struct vfio_dtindex { + __u32 len; /* length of structure */ + __u32 index; + __u32 prop_type; + __u32 prop_index; + __u64 flags; +#define VFIO_DTINDEX_FLAGS_REGION (1 << 0) +#define VFIO_DTINDEX_FLAGS_IRQ (1 << 1) +}; +#define VFIO_DEVICE_GET_DTINDEX _IOWR(';', 118, struct vfio_dtindex) + + +VFIO bus driver API +------------------------------------------------------------------------------- +Quoted 8 lines
Documentation/vfio.txt line 257
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+Bus drivers, such as PCI, have three jobs: + 1) Add/remove devices from vfio + 2) Provide vfio_device_ops for device access + 3) Device binding and unbinding + +When initialized, the bus driver should enumerate the devices on it'ss/it's/its/
Noted.
<snip>
Quoted 10 lines
drivers/vfio/vfio_iommu.c line 143
Quoted 4 lines
drivers/vfio/vfio_iommu.c new file +4
-0+/* Unmap DMA region */ +/* dgate must be held */ +static int __vfio_dma_unmap (struct vfio_iommu *iommu,unsigned long iova, +int npage,int rdwr)Use of "read" and "write" in DMA can often be confusing, since it's not always clear if you're talking from the perspective of the CPU or the device (_writing_ data to a device will usually involve it doing DMA _reads_ from memory). It's often best to express things as DMA direction, 'to device', and 'from device' instead.
Quoted 3 lines
Quoted 1 line
Good point.
This, of course, potentially affects many areas of the code and doco.
I've changed vfio_iommu to use <linux/dma-direction.h> definitions internally. For the ioctl I've so far simply included WRITE and READ flags, which I can clarify are from the device perspective. Flags like VFIO_DMA_MAP_FLAG_TO_DEVICE/FROM_DEVICE are actually more confusing to me at this interface level. We also have IOMMU_READ/IOMMU_WRITE which makes me question using dma-direction.h and if we shouldn't just define everything as from the device perspective.
Quoted 26 lines
Quoted 26 lines
Quoted 25 lines
Quoted 12 lines
drivers/vfio/vfio_iommu.c new file +12
-0+{ +int i, unlocked =0 ; + +for (i =0 ; i < npage; i++, iova +=PAGE_SIZE ) { +unsigned long pfn; + + pfn =iommu_iova_to_phys (iommu->domain, iova) >>PAGE_SHIFT ; +if (pfn) { +iommu_unmap (iommu->domain, iova,0 ); + unlocked +=put_pfn (pfn, rdwr); + } + }drivers/vfio/vfio_iommu.c line 165
Quoted 10 lines
drivers/vfio/vfio_iommu.c new file +10
-0+return unlocked; +} + +static void vfio_dma_unmap (struct vfio_iommu *iommu,unsigned long iova, +unsigned long npage,int rdwr) +{ +int unlocked; + + unlocked =__vfio_dma_unmap (iommu, iova, npage, rdwr); +vfio_lock_acct (-unlocked);Have you checked that your accounting will work out if the user maps the same memory page to multiple IOVAs?
Quoted 4 lines
Quoted 2 lines
Hmm, it probably doesn't. We potentially over-penalize the user process here.
Ok.
FWIW, I don't intend to fix this right now, but I have added a comment in the code noting it. We'll have to see if there's an efficient way to make the tracking better.
Quoted 28 lines
Quoted 23 lines
Quoted 14 lines
Quoted 14 lines
drivers/vfio/vfio_iommu.c new file +14
-0+} + +/* Unmap ALL DMA regions */ +void vfio_iommu_unmapall (struct vfio_iommu *iommu) +{ +struct list_head *pos, *pos2; +struct dma_map_page *mlp; + +mutex_lock (&iommu->dgate); +list_for_each_safe (pos, pos2, &iommu->dm_list) { + mlp = list_entry(pos, struct dma_map_page, list); +vfio_dma_unmap (iommu, mlp->daddr, mlp->npage, mlp->rdwr); +list_del (&mlp->list); +kfree (mlp);Quoted 8 lines
Review
Quoted 2 lines
(quoted diff) +2
-0+ } + mutex_unlock(&iommu->dgate);Ouch, no good at all. Keeping track of every DMA map is no good on POWER or other systems where IOMMU operations are a hot path. I think you'll need an iommu specific hook for this instead, which uses whatever data structures are natural for the IOMMU. For example a 1-level pagetable, like we use on POWER will just zero every entry.
Quoted 4 lines
It's already been noted in the docs that current users have relatively static mappings and a performance interface is TBD for dynamically backing streaming DMA. The current
vfio_iommuexposesiommu_ops, POWER will need to come up with something to expose instead.
Quoted 5 lines
Right, but I'm not just talking about the current map/unmap calls themselves. This infrastructure for tracking it looks like it's intended to be generic for all mapping methods. If not, I can't see the reason for it, because I don't think the current interface requires such tracking inherently.
It does seem that way, but there is a purpose. We need to unmap everything on release. It's easy to assume that iommu_domain_free() will unmap everything from the IOMMU, which it does, but we've also done a get_user_pages on each of those in vfio, which we need to cleanup. We can't rely on userspace to do this since they might have been SIGKILL'd. Making it generic with coalescing of adjacent regions and such is primarily for space efficiency.
<snip>
Quoted 10 lines
Quoted 10 lines
Quoted 9 lines
drivers/vfio/vfio_iommu.c line 519
Quoted 6 lines
drivers/vfio/vfio_iommu.c new file +6
-0+#ifdef CONFIG_COMPAT +static long vfio_iommu_compat_ioctl (struct file *filep, +unsigned int cmd,unsigned long arg) +{ + arg = (unsigned long )compat_ptr (arg); +return vfio_iommu_unl_ioctl (filep, cmd, arg);Um, this only works if the structures are exactly compatible between 32-bit and 64-bit ABIs. I don't think that is always true.
Quoted 5 lines
Quoted 2 lines
I think all our structure sizes are independent of host width. If I'm missing something, let me know.
Ah, for structures, that might be true. I was seeing the bunch of ioctl()s that take ints.
Ugh, I suppose you're thinking of an ILP64 platform with ILP32 compat mode. Darn it, guess we need to make everything 64bit, including file descriptors.
<snip>
Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
drivers/vfio/vfio_main.c line 632
Quoted 3 lines
drivers/vfio/vfio_main.c new file +3
-0+ +/* Get a new iommu file descriptor. This will open the iommu, setting +* the current->mm ownership if it's not already set. */ I know I've had this explained to me several times before, but I've forgotten again. Why do we need to wire the iommu to an mm?
Quoted 7 lines
Quoted 4 lines
We're mapping process virtual addresses into the IOMMU, so it makes sense to restrict ourselves to a single virtual address space. It also enforces the ownership, that only a single mm is in control of the group.
Neither of those seems conclusive to me, but I remember that I saw a strong reason earlier, even if I can't remember it now.
The point of the group is to provide a unit of ownership. We can't let $userA open $groupid and fetch a device, then have $userB do the same, grabbing a different device. The mappings will step on each other and the devices have no isolation. We can't restrict that purely by file permissions or we'll have the same problem with sudo. At one point we discussed a single open instance, but that unnecessarily limits the user, so we settled on the mm. Thanks,
Alex
Quoted 8 lines · Alex Williamson
Hmm, that might be cleaner than eliminating the size with just using
_IO(). So we might have something like:#define
VFIO_IOMMU_MAP_DMA_IOWR(';', 106, struct vfio_dma_map)
#defineVFIO_IOMMU_MAP_DMA_V2_IOWR(';', 106, struct vfio_dma_map_v2)For which the driver might do:
Quoted 8 lines
case
VFIO_IOMMU_MAP_DMA:
caseVFIO_IOMMU_MAP_DMA_V2:{ struct vfio_dma_map map; /* We don't care about the extra v2 bits */ if (copy_from_user(&map, (void __user *)arg, sizeof map)) return -EFAULT;
That won't work if you have an old kernel that doesn't know about v2, and a new user that uses v2. To make this work you'd have to strip out the size from the ioctl number before switching (but still use it when considering whether to access the v2 fields). Simpler to just leave it out of the ioctl number and put it in the struct field as currently planned.
Quoted 8 lines
Quoted 5 lines
Quoted 2 lines
I think all our structure sizes are independent of host width. If I'm missing something, let me know.
Ah, for structures, that might be true. I was seeing the bunch of ioctl()s that take ints.
Ugh, I suppose you're thinking of an ILP64 platform with ILP32 compat mode.
Does Linux support ILP64? There are "int" ioctls all over the place, and I don't think we do compat wrappers for them. In fact, some of the ioctls in linux/fs.h use "int" for the compatible version of ioctls originally defined as "long".
It's cleaner to always use the fixed types, though.
Quoted 2 lines
Darn it, guess we need to make everything 64bit, including file descriptors.
What's wrong with __u32/__s32 (or uint32_t/int32_t)?
I really do not see Linux supporting an ABI that has no 32-bit type at all, especially in a situation where userspace compatibility is needed. If that does happen, the ABI breakage will go well beyond VFIO.
Quoted 5 lines
The point of the group is to provide a unit of ownership. We can't let $userA open $groupid and fetch a device, then have $userB do the same, grabbing a different device. The mappings will step on each other and the devices have no isolation. We can't restrict that purely by file permissions or we'll have the same problem with sudo.
What is the problem with sudo? If you're running processes as the same user, regardless of how, they're going to be able to mess with each other.
Is it possible to expose access to only specific groups via an individually-permissionable /dev/device, so only the entity handing out access to devices needs access to everything?
Quoted 2 lines
At one point we discussed a single open instance, but that unnecessarily limits the user, so we settled on the mm. Thanks,
It would be nice if this limitation weren't excessively integrated into the design -- in the embedded space we've got unusual partitioning setups, including failover arrangements where partitions share devices. The device may be configured with the IOMMU pointing only at regions that are shared by both mms, or the non-shared regions may be reconfigured as active ownership of the device gets handed around.
It would be up to userspace code to make sure that the mappings don't "step on each other". The mapping could be done with whichever mm issued the map call for a given region.
For this use case, there is unlikely to be an issue with ownership because there will not be separate privilege domains creating partitions -- other use cases could refrain from enabling multiple-mm support unless ownership issues are resolved.
This doesn't need to be supported initially, but we should try to avoid letting the assumption permeate the code.
-Scott
Quoted 18 lines · Scott Wood
Quoted 8 lines · Alex Williamson
Hmm, that might be cleaner than eliminating the size with just using
_IO(). So we might have something like:#define
VFIO_IOMMU_MAP_DMA_IOWR(';', 106, structvfio_dma_map) #defineVFIO_IOMMU_MAP_DMA_V2_IOWR(';', 106, struct vfio_dma_map_v2)For which the driver might do:
Quoted 8 lines
case
VFIO_IOMMU_MAP_DMA:
caseVFIO_IOMMU_MAP_DMA_V2:
{
structvfio_dma_mapmap;/* We don't care about the extra v2 bits */
if (copy_from_user(&map, (void __user *)arg, sizeof map)) return-EFAULT;
Quoted 6 lines
That won't work if you have an old kernel that doesn't know about v2, and a new user that uses v2. To make this work you'd have to strip out the size from the ioctl number before switching (but still use it when considering whether to access the v2 fields). Simpler to just leave it out of the ioctl number and put it in the struct field as currently planned.
Ok, _IO for all ioctls passing structs then.
Quoted 9 lines
Quoted 8 lines
Quoted 5 lines
Quoted 2 lines
I think all our structure sizes are independent of host width. If I'm missing something, let me know.
Ah, for structures, that might be true. I was seeing the bunch of ioctl()s that take ints.
Ugh, I suppose you're thinking of an ILP64 platform with ILP32 compat mode.
Quoted 6 lines
Does Linux support ILP64? There are "int" ioctls all over the place, and I don't think we do compat wrappers for them. In fact, some of the ioctls in
linux/fs.huse "int" for the compatible version of ioctls originally defined as "long".It's cleaner to always use the fixed types, though.
I've updated anything that passes data to use a structure and will make use of __s32 in place of ints. If there ever exists an ILP64 system, we can use a flag bit of the structure to indicate 64bit file descriptor support.
Quoted 8 lines
Quoted 2 lines
Darn it, guess we need to make everything 64bit, including file descriptors.
What's wrong with __u32/__s32 (or uint32_t/int32_t)?
I really do not see Linux supporting an ABI that has no 32-bit type at all, especially in a situation where userspace compatibility is needed. If that does happen, the ABI breakage will go well beyond VFIO.
Yep, I think the structs fix this and still leave room for the impossible.
Quoted 9 lines
Quoted 5 lines
The point of the group is to provide a unit of ownership. We can't let $userA open $groupid and fetch a device, then have $userB do the same, grabbing a different device. The mappings will step on each other and the devices have no isolation. We can't restrict that purely by file permissions or we'll have the same problem with sudo.
What is the problem with sudo? If you're running processes as the same user, regardless of how, they're going to be able to mess with each other.
Just trying to indicate that file permissions are easy to bypass and privileged users can inadvertently do stupid stuff. Kind of likerequest_region() in the kernel. Kernel drivers are privileged, but
we still want to enforce an owner of that region. VFIO extends the ownership of a device to a single entity in userspace. How do we identify that entity and keep others out?
Quoted 3 lines
Is it possible to expose access to only specific groups via an individually-permissionable
/dev/device, so only the entity handing out access to devices needs access to everything?
Yes, that's fundamental to vfio. vfio-bus drivers enumerate devices to the vfio-core. Privileged users bind devices to the vfio-bus driver creating viable groups. Groups are represented as chardevs under /dev/vfio. If a user has permission to access the chardev, they have the ability to use the devices. Once they get a device or iommu descriptor the group is tied to them via the struct mm and only they are permitted to access the other devices in the group.
Quoted 14 lines
Quoted 2 lines
At one point we discussed a single open instance, but that unnecessarily limits the user, so we settled on the mm. Thanks,
It would be nice if this limitation weren't excessively integrated into the design -- in the embedded space we've got unusual partitioning setups, including failover arrangements where partitions share devices. The device may be configured with the IOMMU pointing only at regions that are shared by both mms, or the non-shared regions may be reconfigured as active ownership of the device gets handed around.
It would be up to userspace code to make sure that the mappings don't "step on each other". The mapping could be done with whichever mm issued the map call for a given region.
Quoted 7 lines
For this use case, there is unlikely to be an issue with ownership because there will not be separate privilege domains creating partitions -- other use cases could refrain from enabling multiple-mm support unless ownership issues are resolved.
This doesn't need to be supported initially, but we should try to avoid letting the assumption permeate the code.
So I'm hearing "we want to use this driver you're developing that's centered around using the iommu to securely provide access to a device from userspace, but can we do it without the iommu and can we loosen up the security a bit?" Is that about right? ;) Thanks,
Alex
Quoted 5 lines · Alex Williamson
Quoted 4 lines · Scott Wood
Quoted 2 lines · Alex Williamson
Ugh, I suppose you're thinking of an ILP64 platform with ILP32 compat mode.
Quoted 8 lines
Quoted 6 lines
Does Linux support ILP64? There are "int" ioctls all over the place, and I don't think we do compat wrappers for them. In fact, some of the ioctls in
linux/fs.huse "int" for the compatible version of ioctls originally defined as "long".It's cleaner to always use the fixed types, though.
I've updated anything that passes data to use a structure
That's a bit extreme...
Quoted 3 lines
and will make use of
__s32in place of ints. If there ever exists an ILP64 system, we can use a flag bit of the structure to indicate 64bit file descriptor support.
If we end up supporting an ABI where compatibility between user and kernel is broken even when we use fixed-size types and are careful about alignment, we'll need a compat wrapper, and we'll know what ABI userspace is supposed to be using. I'm not sure how a flag would help.
Quoted 6 lines
Quoted 6 lines
Quoted 5 lines
The point of the group is to provide a unit of ownership. We can't let $userA open $groupid and fetch a device, then have $userB do the same, grabbing a different device. The mappings will step on each other and the devices have no isolation. We can't restrict that purely by file permissions or we'll have the same problem with sudo.
Quoted 6 lines
Quoted 3 lines
What is the problem with sudo? If you're running processes as the same user, regardless of how, they're going to be able to mess with each other.
Just trying to indicate that file permissions are easy to bypass and privileged users can inadvertently do stupid stuff.
Preventing stupid stuff can also prevent useful stuff. Security and accident-avoidance are different things. "We can't let" is the domain of the former.
Quoted 4 lines
Kind of like
request_region()in the kernel. Kernel drivers are privileged, but
we still want to enforce an owner of that region. VFIO extends the ownership of a device to a single entity in userspace. How do we identify that entity and keep others out?
That's fine as long as it's an optional safeguard that can be turned off if needed. Maybe require userspace to set a flag via some mechanism to indicate it's opening the device in shared mode.
Quoted 16 lines
Quoted 16 lines
It would be nice if this limitation weren't excessively integrated into the design -- in the embedded space we've got unusual partitioning setups, including failover arrangements where partitions share devices. The device may be configured with the IOMMU pointing only at regions that are shared by both mms, or the non-shared regions may be reconfigured as active ownership of the device gets handed around.
It would be up to userspace code to make sure that the mappings don't "step on each other". The mapping could be done with whichever mm issued the map call for a given region.
For this use case, there is unlikely to be an issue with ownership because there will not be separate privilege domains creating partitions -- other use cases could refrain from enabling multiple-mm support unless ownership issues are resolved.
Quoted 7 lines
Quoted 2 lines
This doesn't need to be supported initially, but we should try to avoid letting the assumption permeate the code.
So I'm hearing "we want to use this driver you're developing that's centered around using the iommu to securely provide access to a device from userspace, but can we do it without the iommu and can we loosen up the security a bit?" Is that about right? ;) Thanks,
We have a variety of use cases for userspace and KVM-guest access to devices. Some of those involve an iommu, some don't. Some involve shared ownership (which isn't necessarily a loosening of security -- there's still an iommu, and access control on the vfio group), some don't. Some don't involve DMA at all. I see no reason to have entirely separate kernel mechanisms for these use cases.
I'm not asking you to implement any of this, just hoping you'll keep such flexibility in mind when deciding on fundamental assumptions that the code and API are to make.
-Scott
Quoted 11 lines · Scott Wood
Quoted 10 lines · Alex Williamson
Quoted 9 lines · Scott Wood
Quoted 2 lines · Alex Williamson
Ugh, I suppose you're thinking of an ILP64 platform with ILP32 compat mode.
Does Linux support ILP64? There are "int" ioctls all over the place, and I don't think we do compat wrappers for them. In fact, some of the ioctls in
linux/fs.huse "int" for the compatible version of ioctls originally defined as "long".
Quoted 5 lines
Quoted 3 lines
Quoted 1 line
It's cleaner to always use the fixed types, though.
I've updated anything that passes data to use a structure
That's a bit extreme...
Ok, I lied, it's not everything. I have consolidated some GET_FLAGS and GET_NUM_* calls into generic GET_INFO ioctls so we have more flexibility. I think the structures make sense there. I'm not as convinced on the eventfd and irq unmask structures, but who knows, they might save us some day.
Here's where I stand on the API definitions, maybe we can get some agreement on this before diving into semantics of the documentation or or implementation, though it still includes the merge interface. Thanks,
Alex
/*
* VFIO API definition
*
* Copyright (C) 2011 Red Hat, Inc. All rights reserved.
* Author: Alex Williamson <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#ifndef VFIO_H
#define VFIO_H
#include <linux/types.h>
#ifdef __KERNEL__ /* Internal VFIO-core/bus driver API */
/**
* struct vfio_device_ops - VFIO bus driver device callbacks
*
* @match: Return true if buf describes the device
* @open: Called when userspace receives file descriptor for device
* @release: Called when userspace releases file descriptor for device
* @read: Perform read(2) on device file descriptor
* @write: Perform write(2) on device file descriptor
* @ioctl: Perform ioctl(2) on device file descriptor, supporting VFIO_DEVICE_*
* operations documented below
* @mmap: Perform mmap(2) on a region of the device file descriptor */
struct vfio_device_ops {
bool (*match)(struct device *dev, const char *buf);
int (*open)(void *device_data);
void (*release)(void *device_data);
ssize_t (*read)(void *device_data, char __user *buf,
size_t count, loff_t *ppos);
ssize_t (*write)(void *device_data, const char __user *buf,
size_t count, loff_t *size);
long (*ioctl)(void *device_data, unsigned int cmd,
unsigned long arg);
int (*mmap)(void *device_data, struct vm_area_struct *vma);
};/**
* vfio_group_add_dev() - Add a device to the vfio-core
*
* @dev: Device to add
* @ops: VFIO bus driver callbacks for device
*
* This registration makes the VFIO core aware of the device, creates
* groups objects as required and exposes chardevs under /dev/vfio. *
* Return 0 on success, errno on failure.
*/
extern int vfio_group_add_dev(struct device *dev,
const struct vfio_device_ops *ops);
/**
* vfio_group_del_dev() - Remove a device from the vfio-core *
* @dev: Device to remove
*
* Remove a device previously added to the VFIO core, removing groups
* and chardevs as necessary.
*/
extern void vfio_group_del_dev(struct device *dev);
/**
* vfio_bind_dev() - Indicate device is bound to the VFIO bus driver and
* register private data structure for ops callbacks.
*
* @dev: Device being bound
* @device_data: VFIO bus driver private data
*
* This registration indicate that a device previously registered with
* vfio_group_add_dev() is now available for use by the VFIO core. When
* all devices within a group are available, the group is viable and my
* be used by userspace drivers. Typically called from VFIO bus driver
* probe function.
*
* Return 0 on success, errno on failure
*/
extern int vfio_bind_dev(struct device *dev, void *device_data);
/**
* vfio_unbind_dev() - Indicate device is unbinding from VFIO bus driver *
* @dev: Device being unbound
*
* De-registration of the device previously registered with vfio_bind_dev()
* from VFIO. Upon completion, the device is no longer available for use by
* the VFIO core. Typically called from the VFIO bus driver remove function.
* The VFIO core will attempt to release the device from users and may take
* measures to free the device and/or block as necessary.
*
* Returns pointer to private device_data structure registered with
* vfio_bind_dev().
*/
extern void *vfio_unbind_dev(struct device *dev);
#endif /* __KERNEL__ */
/* Kernel & User level defines for VFIO IOCTLs. */
/*
* The IOCTL interface is designed for extensibility by embedding the
* structure length (argsz) and flags into structures passed between
* kernel and userspace. We therefore use the _IO() macro for these
* defines to avoid implicitly embedding a size into the ioctl request.
* As structure fields are added, argsz will increase to match and flag
* bits will be defined to indicate additional fields with valid data.
* It's *always* the caller's responsibility to indicate the size of
* the structure passed by setting argsz appropriately.
*/
#define VFIO_TYPE ';'
#define VFIO_BASE 100
/* --------------- IOCTLs for GROUP file descriptors --------------- */
/**
* VFIO_GROUP_GET_INFO - _IOR(VFIO_TYPE, VFIO_BASE + 0, struct vfio_group_info) *
* Retrieve information about the group. Fills in provided
* struct vfio_group_info. Caller sets argsz.
*/
struct vfio_group_info {
__u32 argsz;
__u32 flags;#define VFIO_GROUP_FLAGS_VIABLE (1 << 0)
#define VFIO_GROUP_FLAGS_MM_LOCKED (1 << 1)
};
#define VFIO_GROUP_GET_INFO _IO(VFIO_TYPE, VFIO_BASE + 0);
/**
* VFIO_GROUP_MERGE - _IOW(VFIO_TYPE, VFIO_BASE + 1, __s32) *
* Merge group indicated by passed file descriptor into current group.
* Current group may be in use, group indicated by file descriptor
* cannot be in use (no open iommu or devices).
*/
#define VFIO_GROUP_MERGE _IOW(VFIO_TYPE, VFIO_BASE + 1, __s32)
/**
* VFIO_GROUP_UNMERGE - _IO(VFIO_TYPE, VFIO_BASE + 2)
*
* Remove the current group from a merged set. The current group cannot
* have any open devices.
*/
#define VFIO_GROUP_UNMERGE _IO(VFIO_TYPE, VFIO_BASE + 2)
/**
* VFIO_GROUP_GET_IOMMU_FD - _IO(VFIO_TYPE, VFIO_BASE + 3)
*
* Return a new file descriptor for the IOMMU object. The IOMMU object
* is shared among members of a merged group.
*/
#define VFIO_GROUP_GET_IOMMU_FD _IO(VFIO_TYPE, VFIO_BASE + 3)
/**
* VFIO_GROUP_GET_DEVICE_FD - _IOW(VFIO_TYPE, VFIO_BASE + 4, char) *
* Return a new file descriptor for the device object described by
* the provided char array.
*/
#define VFIO_GROUP_GET_DEVICE_FD _IOW(VFIO_TYPE, VFIO_BASE + 4, char)
/* --------------- IOCTLs for IOMMU file descriptors --------------- */
/**
* VFIO_IOMMU_GET_INFO - _IOR(VFIO_TYPE, VFIO_BASE + 5, struct vfio_iommu_info) *
* Retrieve information about the IOMMU object. Fills in provided
* struct vfio_iommu_info. Caller sets argsz.
*/
struct vfio_iommu_info {
__u32 argsz;
__u32 flags;
__u64 iova_max; /* Maximum IOVA address */
__u64 iova_min; /* Minimum IOVA address */
__u64 alignment; /* Required alignment, often PAGE_SIZE */
};#define VFIO_IOMMU_GET_INFO _IO(VFIO_TYPE, VFIO_BASE + 5)
/**
* VFIO_IOMMU_MAP_DMA - _IOW(VFIO_TYPE, VFIO_BASE + 6, struct vfio_dma_map) *
* Map or unmap process virtual addresses to IO virtual addresses using
* the provided struct vfio_dma_map. Caller sets argsz.
*/
struct vfio_dma_map {
__u32 argsz;
__u32 flags;
#define VFIO_DMA_MAP_FLAG_MAP (1 << 0) /* Map (1) vs Unmap (0) */
#define VFIO_DMA_MAP_FLAG_READ (1 << 1) /* readable from device */
#define VFIO_DMA_MAP_FLAG_WRITE (1 << 2) /* writable from device */
__u64 vaddr; /* Process virtual address */
__u64 iova; /* IO virtual address */
__u64 size; /* Size of mapping (bytes) */
};#define VFIO_IOMMU_MAP_DMA _IO(VFIO_TYPE, VFIO_BASE + 6)
/* --------------- IOCTLs for DEVICE file descriptors --------------- */
/**
* VFIO_DEVICE_GET_INFO - _IOR(VFIO_TYPE, VFIO_BASE + 7,
* struct vfio_device_info)
*
* Retrieve information about the device. Fills in provided
* struct vfio_device_info. Caller sets argsz.
*/
struct vfio_device_info {
__u32 argsz;
__u32 flags;
#define VFIO_DEVICE_FLAGS_RESET (1 << 0) /* Device supports reset */
__u32 num_regions; /* Max region index + 1 */
__u32 num_irqs; /* Max IRQ index + 1 */
};#define VFIO_DEVICE_GET_INFO _IO(VFIO_TYPE, VFIO_BASE + 7)
/**
* VFIO_DEVICE_GET_REGION_INFO - _IOWR(VFIO_TYPE, VFIO_BASE + 8,
* struct vfio_region_info)
*
* Retrieve information about a device region. Caller provides
* struct vfio_region_info with index value set. Caller sets argsz. */
struct vfio_region_info {
__u32 argsz;
__u32 flags;
#define VFIO_REGION_INFO_FLAG_MMAP (1 << 0) /* Region supports mmap */
#define VFIO_REGION_INFO_FLAG_RO (1 << 1) /* Region is read-only */
__u32 index; /* Region index */
__u32 resv; /* Reserved for alignment */
__u64 size; /* Region size (bytes) */
__u64 offset; /* Region offset from start of device fd */
};#define VFIO_DEVICE_GET_REGION_INFO _IO(VFIO_TYPE, VFIO_BASE + 8)
/**
* VFIO_DEVICE_GET_IRQ_INFO - _IOWR(VFIO_TYPE, VFIO_BASE + 9,
* struct vfio_irq_info)
*
* Retrieve information about a device IRQ. Caller provides
* struct vfio_irq_info with index value set. Caller sets argsz. */
struct vfio_irq_info {
__u32 argsz;
__u32 flags;
#define VFIO_IRQ_INFO_FLAG_LEVEL (1 << 0) /* Level (1) vs Edge (0) */
__u32 index; /* IRQ index */
__u32 count; /* Number of IRQs within this index */
};#define VFIO_DEVICE_GET_IRQ_INFO _IO(VFIO_TYPE, VFIO_BASE + 9)
/**
* VFIO_DEVICE_SET_IRQ_EVENTFDS - _IOW(VFIO_TYPE, VFIO_BASE + 10,
* struct vfio_irq_eventfds)
*
* Set eventfds for IRQs using the struct vfio_irq_eventfds provided.
* Setting the eventfds also enables the interrupt. Caller sets argsz. */
struct vfio_irq_eventfds {
__u32 argsz;
__u32 flags;
__u32 index; /* IRQ index */
__u32 count; /* Number of eventfds */
__s32 eventfds[]; /* eventfd for sub-index, -1 to unset */
};#define VFIO_DEVICE_SET_IRQ_EVENTFDS _IO(VFIO_TYPE, VFIO_BASE + 10)
/**
* VFIO_DEVICE_UNMASK_IRQ - _IOW(VFIO_TYPE, VFIO_BASE + 11,
* struct vfio_unmask_irq)
*
* Unmask the IRQ described by the provided struct vfio_unmask_irq.
* Level triggered IRQs are masked when posted to userspace and must
* be unmasked to re-trigger. Caller sets argsz.
*/
struct vfio_unmask_irq {
__u32 argsz;
__u32 flags;
__u32 index; /* IRQ index */
__u32 subindex; /* Sub-index to unmask */
};#define VFIO_DEVICE_UNMASK_IRQ _IO(VFIO_TYPE, VFIO_BASE + 11)
/**
* VFIO_DEVICE_SET_UNMASK_IRQ_EVENTFD - _IOW(VFIO_TYPE, VFIO_BASE + 12,
* struct vfio_irq_eventfds)
*
* Set eventfds to be used for unmasking IRQs using the provided
* struct vfio_irq_eventfds.
*/
#define VFIO_DEVICE_SET_UNMASK_IRQ_EVENTFD _IO(VFIO_TYPE, VFIO_BASE + 12)
/**
* VFIO_DEVICE_RESET - _IO(VFIO_TYPE, VFIO_BASE + 13) *
* Reset a device.
*/
#define VFIO_DEVICE_RESET _IO(VFIO_TYPE, VFIO_BASE + 13)
#endif /* VFIO_H */
Quoted 43 lines · Alex Williamson
Quoted 3 lines · David Gibson
Quoted 2 lines · Alex Williamson
Quoted 1 line · David Gibson
On Thu, Nov 03, 2011 at 02:12:24PM -0600, Alex Williamson wrote:
<snip>
Quoted 30 lines
Quoted 30 lines
Quoted 29 lines
Quoted 13 lines
Documentation/vfio.txt new file +13
-0+Groups, Devices, IOMMUs, oh my +------------------------------------------------------------------------------- + +A fundamental component of VFIO is the notion of IOMMU groups. IOMMUs +can't always distinguish transactions from each individual device in +the system. Sometimes this is because of the IOMMU design, such as with +PEs, other times it's caused by the I/O topology, for instance a +PCIe-to-PCI bridge masking all devices behind it. We call the sets of +devices created by these restictions IOMMU groups (or just "groups" for +this document). + +The IOMMU cannot distiguish transactions between the individual devices +within the group, therefore the group is the basic unit of ownership forDocumentation/vfio.txt line 54
Quoted 10 lines
Documentation/vfio.txt new file +10
-0+a userspace process. Because of this, groups are also the primary +interface to both devices and IOMMU domains in VFIO. + +The VFIO representation of groups is created as devices are added into +the framework by a VFIO bus driver. The vfio-pci module is an example +of a bus driver. This module registers devices along with a set of bus +specific callbacks with the VFIO core. These callbacks provide the +interfaces later used for device access. As each new group is created, +as determined by iommu_device_group(), VFIO creates a /dev/vfio/$GROUP +character device.Ok.. so, the fact that it's called "vfio-pci" suggests that the VFIO
bus driver is per bus type, not per bus instance. But grouping
constraints could be per bus instance, if you have a couple of different models of PCI host bridge with IOMMUs of different capabilities built in, for example.Quoted 7 lines
Quoted 2 lines
Yes, vfio-pci manages devices on the
pci_bus_type; per type, not per bus instance.Ok, how can that work. vfio-pci is responsible for generating the groupings, yes? For which it needs to know the iommu/host bridge's isolation capabilities, which vary depending on the type of host bridge.
Quoted 4 lines
No, grouping is done at the iommu driver level. vfio gets groupings via
iomm_device_group(), which uses theiommu_opsfor thebus_typeof the requested device. I'll attempt to clarify where groups come from in the documentation.
Hrm, but still per bus type, not bus instance. Hrm. Yeah, I need to look at the earlier iommu patches in more detail.
[snip]
Quoted 15 lines
Quoted 15 lines
Yeah, I'm starting to get my head around the model, but the current description of it doesn't help very much. In particular the terms "merge" and "unmerge" lead one to the wrong mental model, I think.
Quoted 10 lines
Quoted 4 lines
The semantics of "merge" and "unmerge" under those names are really non-obvious. Merge kind of has to merge two whole metagroups, but it's unclear if unmerge reverses one merge, or just takes out one (atom) group. These operations need better names, at least.
Christian suggested a change to UNMERGE that we do not need to specify a group to unmerge "from". This makes it more like a list implementation except there's no defined
list_head. Any member of the list can pull in a new entry. Calling UNMERGE on any member extracts that member.
Quoted 3 lines
Quoted 1 line
I think that's a good idea, but "unmerge" is not a good word for it.
I can't think of better, if you can, please suggest.
Well, I think addgroup and removegroup would be better than merge and unmerge, although they have their own problems.
Quoted 24 lines
Quoted 24 lines
Quoted 11 lines
Quoted 10 lines
Then it's unclear what order you can do various operations, and which order you can open and close various things. You can kind of figure it out but it takes far more thinking than it should.
So at the _very_ least, we need to invent new terminology and find a much better way of describing this API's semantics. I still think an entirely different interface, where metagroups are created from outside with a lifetime that's not tied to an fd would be a better idea.
Quoted 3 lines
As we've discussed previously, configfs provides part of this, but has no ioctl support. It doesn't make sense to me to go play with groups in configfs, but then still interact with them via a char dev.
Why not? You configure, say, loopback devices with losetup, then use them as a block device. Similar with nbd. You can configure serial devices with setserial, then use them as a char dev.
Quoted 2 lines
It also
splits the ownership modelI'm not even sure what that means.
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
and makes it harder to enforce who gets to interact with the devices vs who gets to manipulate groups.
How so.
Let's map out what a configfs interface would look like, maybe I'll convince myself it's on the table. We'd probably start with
Hrm, assumin we used configfs, which is not the only option.
Quoted 13 lines
/config/vfio/$bus_type.name/
That would probably be pre-populated with a bunch of $groupid files, matching
/dev/vfio/$bus_type.name/$groupidchar dev files (assuming configfs can pre-populate files). To make a user defined group, we might then do:mkdir /config/vfio/$bus_type.name/my_group
That would generate a
/dev/vfio/$bus_type.name/my_groupchar dev. To add groups to the newmy_group"super group", we'd need to do something like:
Quoted 7 lines
ln -s /config/vfio/$bus_type.name/$groupidA /config/vfio/$bus_type.name/my_group/nic_group
I might then add a second group as:
ln -s /config/vfio/$bus_type.name/$groupidB /config/vfio/$bus_type.name/my_group/hba_group
Either link could fail if the target group is not viable,
The link op shouldn't fail because the subgroup isn't viable. Instead, the supergroup jusy won't be viable until all devices in all subgroups are bound to vfio.
Quoted 8 lines
the group is
already in use, or the second link could fail if the iommu domains were incompatible.Do these links cause
/dev/vfio/$bus_type.name/{$groupidA,$groupidB}to disappear? If not, do we allow them to be opened? Linking would also have to fail if we later tried to link one of these groupids to a different super group.
Again, I think some confusion is coming in here from calling both the hardware determined thing and the admin determined thing a "group". So for now I'm going to call the first a "group" and the second a "predomain" (because once it's viable and the right conditions are set up it will become an iommu domain).
So another option is that "groups" *only* participate in the merging interface; getting iommu and device handles occurs only on a predomain. Therefore there would be no /dev/vfio/$group, you would have to configure a predomain with at least one group before you had a device file.
Quoted 20 lines
Now we want to give
my_groupto a user, so we have to go back to /dev andchown $user
/dev/vfio/$bus_type.name/my_groupAt this point
my_groupwould have the existing set of group ioctls sans {UN}MERGE, of course.So $user can use the super group, but not manipulate it's members. Do we then allow:
chown $user /config/vfio/$bus_type.name/my_group
If so, what does it imply about the user then doing:
ln -s /config/vfio/$bus_type.name/$groupidC /config/vfio/$bus_type.name/my_group/stolen_group
Would we instead need to chown the configfs groups as well as the super group?
Quoted 8 lines
chown $user /config/vfio/$bus_type.name/my_group
chown $user /config/vfio/$bus_type.name/$groupidA
chown $user /config/vfio/$bus_type.name/$groupidBie:
# chown $user:$user /config/vfio/$bus_type.name/$groupC $ ln -s /config/vfio/$bus_type.name/$groupidC /config/vfio/$bus_type.name/my_group/given_group
This is not the only option. We could also do:
cd /config/vfio
mkdir new_predomain
echo $groupid > new_predomain/addgroup
chown $user /dev/vfio/new_predomain
This is assuming that configuration of predomains is a root only operation, which seems reasonable to me.
Quoted 2 lines
(linking has to look at the permissions of the target as well as the link name)
Which would be unexpected and therefore a bad idea.
Quoted 10 lines
Now we've introduced that we have ownership of configfs entries, what does that imply about the char dev entries? For instance, can $userA own
/dev/vfio/$bus_type.name/$groupidA, but $userB own the configfs file? We also have another security consideration that an exploit on the host might allow a 3rd party to insert a device into a group.This is where I start to get lost in the complexity versus simply giving the user permissions for the char dev and allowing them to stick groups together so long as the have permissions for the group.
Quoted 6 lines
We also add an entire filesystem to the interface that already spans sysfs, dev, eventfds and potentially netlink.
If terminology is the complaint against the {UN}MERGE ioctl interface, I'm still not sold that configfs is the answer. /me goes to the thesaurus... amalgamate? blend? combine? cement? unite? join?
A thesaurus won't help, my point is you want something with a *different* meaning to merge, which implies a symmetry not present in this operation.
[snip]
Quoted 29 lines
Quoted 15 lines
Hrm. "ANY" just really bothers me because "any iova" is not as clear a concept as it first appears. For starters it's actually "any page aligned" at the very least. But then it's only any 64-bit address for busses which have full 64-bit addressing (and I do wonder if there are any north bridges out there that forgot to implement some of the upper PCI address bits properly, given that 64-bit CPUs rarely actually implement more than 40-something physical address bits in practice).
I'd prefer to see at least something to advertise min and max IOVA and IOVA alignment. That's enough to cover x86 and POWER, including possible variants with an IOMMU page size different to the system page size (note that POWER kernels can have 64k pages as a config option, which means a TCE page size different to the system page size is quite common).
Quoted 2 lines
Obviously there could be more complex constraints that we would need to advertise with option bits.
x86 has limitations as well. I don't think most x86 IOMMUs support a
full 64bit IOVA space, so point take.struct vfio_iommu_info { __u64 len; /* or structlen/arglen */ __u64 flags; /* replaces VFIO_IOMMU_GET_FLAGS, none defined yet */ __u64 iova_max; __u64 iova_min; __u64 granularity; };
Quoted 1 line
#define
VFIO_IOMMU_GET_INFO_IOR(';', xxx, struct vfio_iommu_info)
Yeah, this looks like what I was after.
Quoted 4 lines
Is granularity the minimum granularity, typically
PAGE_SIZEbarring special configurations noted above, or is it a bitmap of supported granularities? Ex. If we support 4k normal pages and 2M large pages, we might set bits 12 and 21.
Just minimum, I think. I'd prefer 'alignment' to 'granularity' I think, but I don't care that much.
Quoted 37 lines
Quoted 13 lines
Quoted 13 lines
Quoted 12 lines
Documentation/vfio.txt line 120
Quoted 6 lines
Documentation/vfio.txt new file +6
-0+ +The (UN)MAP_DMA commands make use of struct vfio_dma_map for mapping +and unmapping IOVAs to process virtual addresses: + +struct vfio_dma_map { + __u64 len; /* length of structure */Thanks for adding these structure length fields. But I think they should be called something other than 'len', which is likely to be confused with size (or some other length that's actually related to the operation's parameters). Better to call it 'structlen' or 'argslen' or something.
Quoted 7 lines
Quoted 2 lines
Ok. As Scott noted, I've failed to implement these in a way that actually allows extension, but I'll work on it.
Right. I had failed to realise quite how the encoding of structure size into the ioctl worked. With that in place, arguably we don't really need the size in the structure itself, because we can still have multiple sized versions of the ioctl. Still, whichever.
Hmm, that might be cleaner than eliminating the size with just using
_IO(). So we might have something like:#define
VFIO_IOMMU_MAP_DMA_IOWR(';', 106, struct vfio_dma_map)
#defineVFIO_IOMMU_MAP_DMA_V2_IOWR(';', 106, struct vfio_dma_map_v2)For which the driver might do:
case
VFIO_IOMMU_MAP_DMA:
caseVFIO_IOMMU_MAP_DMA_V2:{ struct vfio_dma_map map; /* We don't care about the extra v2 bits */ if (copy_from_user(&map, (void __user *)arg, sizeof map)) return -EFAULT;
Quoted 3 lines
...
That presumes v2 is compatible other than extra fields.
Right, as does having the length in the structure itself.
Quoted 2 lines
Any objections
(this gets rid of length from all ioctl passed structs)?
Not from here.
[snip]
Quoted 11 lines
Quoted 8 lines
No, my concept was that NONE would be used for the indexes where there is no valid BAR. I'll buy your argument on why not to include the PCI (or whatever) address space type here.
What I'm just a bit concerned by is whether we could have a case (not for PCI) of a real resource that still has size 0 - e.g. maybe some sort of doorbell that can't be read or written, but can be triggered some other way. I guess that's probably unlikely though.
Right, and if somehow you had such a region where the size is zero, but allowed some kind of operation on it, we could define a flag for it.
Hrm, I guess.
[snip]
Quoted 9 lines
Quoted 8 lines
Quoted 4 lines
Other devices could certainly have multiple level interrupts, and if grouping them as we do with MSI on PCI makes sense, please let me know. I just didn't see the value in making the unmask operations handle sub-indexes if it's not needed.
I don't know of anything off hand. But I can't see any consideration that would make it unlikely either. I generally don't trust anything *not* to exist in embedded space.
Quoted 6 lines
Fair enough. Level IRQs are still triggered individually, so unmasking is too, which means
UNMASK_IRQtakes something like { int index; int subindex }.
SET_UNMASK_IRQ_EVENTFDSshould followSET_IRQ_EVENTFDSand take { int index; int count; int fds[] }.
Ok.
[snip]
Quoted 10 lines
Quoted 9 lines
Quoted 7 lines
Quoted 5 lines
Use of "read" and "write" in DMA can often be confusing, since it's not always clear if you're talking from the perspective of the CPU or the device (_writing_ data to a device will usually involve it doing DMA _reads_ from memory). It's often best to express things as DMA direction, 'to device', and 'from device' instead.
Good point.
This, of course, potentially affects many areas of the code and doco.
Quoted 7 lines
I've changed
vfio_iommuto use <linux/dma-direction.h> definitions internally. For the ioctl I've so far simply included WRITE and READ flags, which I can clarify are from the device perspective. Flags like VFIO_DMA_MAP_FLAG_TO_DEVICE/FROM_DEVICE are actually more confusing to me at this interface level. We also have IOMMU_READ/IOMMU_WRITE which makes me question usingdma-direction.hand if we shouldn't just define everything as from the device perspective.
Ok, sounds like a good start. In some contexts read/write are clear, in others they're not. Just something to keep in mind.
[snip]
Quoted 6 lines
Quoted 5 lines
Right, but I'm not just talking about the current map/unmap calls themselves. This infrastructure for tracking it looks like it's intended to be generic for all mapping methods. If not, I can't see the reason for it, because I don't think the current interface requires such tracking inherently.
Quoted 7 lines
It does seem that way, but there is a purpose. We need to unmap everything on release. It's easy to assume that
iommu_domain_free()will unmap everything from the IOMMU, which it does, but we've also done aget_user_pageson each of those in vfio, which we need to cleanup. We can't rely on userspace to do this since they might have been SIGKILL'd. Making it generic with coalescing of adjacent regions and such is primarily for space efficiency.
Ah, I see. Much as generic infrastructure is nice when we can do it, I think this consideration will have to be pushed down to the iommu driver layer. For e.g. on power, we have all the information we need to do the page tracking; any write to a TCE put()s the page that was previously in that entry (if any) as well as get()ing the one that's going in (if any). It's just that we don't want to keep track in this generic data structure _as well as_ the one that's natural for the hardware.
Quoted 14 lines
<snip>
Quoted 13 lines
Quoted 12 lines
Quoted 9 lines
drivers/vfio/vfio_iommu.c line 519
Quoted 6 lines
drivers/vfio/vfio_iommu.c new file +6
-0+#ifdef CONFIG_COMPAT +static long vfio_iommu_compat_ioctl (struct file *filep, +unsigned int cmd,unsigned long arg) +{ + arg = (unsigned long )compat_ptr (arg); +return vfio_iommu_unl_ioctl (filep, cmd, arg);Um, this only works if the structures are exactly compatible between 32-bit and 64-bit ABIs. I don't think that is always true.
I think all our structure sizes are independent of host width. If I'm missing something, let me know.
Quoted 6 lines
Quoted 2 lines
Ah, for structures, that might be true. I was seeing the bunch of ioctl()s that take ints.
Ugh, I suppose you're thinking of an ILP64 platform with ILP32 compat mode. Darn it, guess we need to make everything 64bit, including file descriptors.
Well, we don't _have_ to, but if we don't then we have to implement compat wrappers for every non explicit width thing we pass through.
Quoted 16 lines
<snip>
Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
drivers/vfio/vfio_main.c line 632
Quoted 3 lines
drivers/vfio/vfio_main.c new file +3
-0+ +/* Get a new iommu file descriptor. This will open the iommu, setting +* the current->mm ownership if it's not already set. */ I know I've had this explained to me several times before, but I've forgotten again. Why do we need to wire the iommu to an mm?
Quoted 7 lines
Quoted 4 lines
We're mapping process virtual addresses into the IOMMU, so it makes sense to restrict ourselves to a single virtual address space. It also enforces the ownership, that only a single mm is in control of the group.
Neither of those seems conclusive to me, but I remember that I saw a strong reason earlier, even if I can't remember it now.
Quoted 7 lines
The point of the group is to provide a unit of ownership. We can't let $userA open $groupid and fetch a device, then have $userB do the same, grabbing a different device. The mappings will step on each other and the devices have no isolation. We can't restrict that purely by file permissions or we'll have the same problem with sudo. At one point we discussed a single open instance, but that unnecessarily limits the user, so we settled on the mm. Thanks,
Hm, ok.
Fyi, I'll be kind of slow in responses for the next while. I broke a bone in my hand on Friday :(.
Signature · 4 lines
David Gibson | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you. NOT _the_ _other_ | _way_ _around_! http://www.ozlabs.org/~dgibson
Quoted 5 lines · David Gibson
Quoted 4 lines · Alex Williamson
Quoted 3 lines · David Gibson
Quoted 2 lines · Alex Williamson
Quoted 1 line · David Gibson
On Thu, Nov 03, 2011 at 02:12:24PM -0600, Alex Williamson wrote:
<snip>
Quoted 16 lines
Quoted 16 lines
Quoted 16 lines
Quoted 3 lines
As we've discussed previously, configfs provides part of this, but has no ioctl support. It doesn't make sense to me to go play with groups in configfs, but then still interact with them via a char dev.
Why not? You configure, say, loopback devices with losetup, then use them as a block device. Similar with nbd. You can configure serial devices with setserial, then use them as a char dev.
Quoted 2 lines
It also
splits the ownership modelI'm not even sure what that means.
Quoted 2 lines
and makes it harder to enforce who gets to interact with the devices vs who gets to manipulate groups.
Quoted 6 lines
Quoted 4 lines
Quoted 1 line
How so.
Let's map out what a configfs interface would look like, maybe I'll convince myself it's on the table. We'd probably start with
Hrm, assumin we used configfs, which is not the only option.
I'm not writing vfiofs, configfs seems most like what we'd need. If there are others we should consider, please note them.
Quoted 17 lines
Quoted 17 lines
/config/vfio/$bus_type.name/
That would probably be pre-populated with a bunch of $groupid files, matching
/dev/vfio/$bus_type.name/$groupidchar dev files (assuming configfs can pre-populate files). To make a user defined group, we might then do:mkdir /config/vfio/$bus_type.name/my_group
That would generate a
/dev/vfio/$bus_type.name/my_groupchar dev. To add groups to the newmy_group"super group", we'd need to do something like:ln -s /config/vfio/$bus_type.name/$groupidA /config/vfio/$bus_type.name/my_group/nic_group
I might then add a second group as:
Quoted 7 lines
Quoted 3 lines
ln -s /config/vfio/$bus_type.name/$groupidB /config/vfio/$bus_type.name/my_group/hba_group
Either link could fail if the target group is not viable,
The link op shouldn't fail because the subgroup isn't viable. Instead, the supergroup jusy won't be viable until all devices in all subgroups are bound to vfio.
The supergroup may already be in use if it's a hotplug. What does it mean to have an incompatible group linked into the supergroup? When does the subgroup actually become part of the supergroup? Does the userspace driver using the supergroup get notified somehow? Does the vfio driver get notified independently? This example continues to show what an administration nightmare it becomes when we split management from usage.
Quoted 15 lines
Quoted 8 lines
the group is
already in use, or the second link could fail if the iommu domains were incompatible.Do these links cause
/dev/vfio/$bus_type.name/{$groupidA,$groupidB}to disappear? If not, do we allow them to be opened? Linking would also have to fail if we later tried to link one of these groupids to a different super group.Again, I think some confusion is coming in here from calling both the hardware determined thing and the admin determined thing a "group". So for now I'm going to call the first a "group" and the second a "predomain" (because once it's viable and the right conditions are set up it will become an iommu domain).
Quoted 5 lines
So another option is that "groups" *only* participate in the merging interface; getting iommu and device handles occurs only on a predomain. Therefore there would be no
/dev/vfio/$group, you would have to configure a predomain with at least one group before you had a device file.
I think this actually leads to a more complicated, more difficult to use interface that interposes an unnecessary administration layer into a driver's decisions about how to manage the iommu.
Quoted 29 lines
Quoted 20 lines
Now we want to give
my_groupto a user, so we have to go back to /dev andchown $user
/dev/vfio/$bus_type.name/my_groupAt this point
my_groupwould have the existing set of group ioctls sans {UN}MERGE, of course.So $user can use the super group, but not manipulate it's members. Do we then allow:
chown $user /config/vfio/$bus_type.name/my_group
If so, what does it imply about the user then doing:
ln -s /config/vfio/$bus_type.name/$groupidC /config/vfio/$bus_type.name/my_group/stolen_group
Would we instead need to chown the configfs groups as well as the super group?
Quoted 8 lines
chown $user /config/vfio/$bus_type.name/my_group
chown $user /config/vfio/$bus_type.name/$groupidA
chown $user /config/vfio/$bus_type.name/$groupidBie:
# chown $user:$user /config/vfio/$bus_type.name/$groupC $ ln -s /config/vfio/$bus_type.name/$groupidC /config/vfio/$bus_type.name/my_group/given_group
Quoted 6 lines
This is not the only option. We could also do:
cd /config/vfio
mkdirnew_predomain
echo $groupid > new_predomain/addgroup
chown $user/dev/vfio/new_predomain
echo $groupid > new_predomain/delgroup
SEGV... Now we've included yet another admin path in the hotplug case as the userspace driver needs to coordinate removal of groups with some other entity.
Quoted 2 lines
This is assuming that configuration of predomains is a root only operation, which seems reasonable to me.
I think it should be a driver decision. Let's go back to the purpose of this interface. We want to give *devices* to userspace drivers. Groups are any unfortunate side-effect of hardware topology, so instead of giving the user a device, we give it a group that contains the device. It's a driver optimization that they can say "oh, I wonder if I can use the same iommu descriptor to drive both of these, let me try to merge them...". That results in "worked, yay" skip initializing a new iommu object OR "nope, oh well". Adding an admin layer that presupposes that they should be merged and does it adds nothing for the better.
Quoted 4 lines
Quoted 2 lines
(linking has to look at the permissions of the target as well as the link name)
Which would be unexpected and therefore a bad idea.
Another indication that this is the wrong interface.
Quoted 13 lines
Quoted 13 lines
Now we've introduced that we have ownership of configfs entries, what does that imply about the char dev entries? For instance, can $userA own
/dev/vfio/$bus_type.name/$groupidA, but $userB own the configfs file? We also have another security consideration that an exploit on the host might allow a 3rd party to insert a device into a group.This is where I start to get lost in the complexity versus simply giving the user permissions for the char dev and allowing them to stick groups together so long as the have permissions for the group.
We also add an entire filesystem to the interface that already spans sysfs, dev, eventfds and potentially netlink.
Quoted 7 lines
Quoted 3 lines
If terminology is the complaint against the {UN}MERGE ioctl interface, I'm still not sold that configfs is the answer. /me goes to the thesaurus... amalgamate? blend? combine? cement? unite? join?
A thesaurus won't help, my point is you want something with a *different* meaning to merge, which implies a symmetry not present in this operation.
But there is symmetry in a merged group, let's look at the operations on a group (note I've updated some of the ioctls since last posting):
VFIO_GROUP_GET_INFO
This returns a structure containing flags for the group, when merged it represents the merged group.
VFIO_GROUP_GET_DEVICE_FD
This returns a file descriptor for the device described by the given char*, when merged it operates across all groups within the merged set.
VFIO_GROUP_GET_IOMMU_FD
Return a file descriptor for the iommu, when merged there's a single iommu across the merged group.
VFIO_GROUP_MERGE
Pull a singleton group into a merge. This can be called on any member of a merged group to pull a singleton group into the merged set.
VFIO_GROUP_UNMERGE
Extract the group from the merged set.
Where is the discontinuity with calling this symmetric? Is it simply that we have an entry point to the supergroup at each subgroup? Forming a new node when groups are merged is a limitation, not a feature, and imposes a number of administration issues (ownership, creation, deletion, addition, subtraction, notifications, etc). Is it that we can only merge singletons? This is an implementation restriction, not an API restriction. If you want to go to the trouble of determining that the existing IOMMU mappings are compatible and can atomically merge them, the singleton could instead be a member of another supergroup. We currently can't do this atomically, and as merging is an optimization, I leave the burden on userspace to split supergroups if they want to merge with another group.
I'm not sure why this is such a thorn since aiu the power iommu topology, you're going to have IOVA windows per group that really can't make use of the merge interface. This is mostly useful for "MAP_ANY" style IOMMUs. Do you really want to impose the administrative overhead of predomains for a feature you're not likely to use?
<snip>
Quoted 16 lines
[snip]
Quoted 6 lines
Quoted 5 lines
Right, but I'm not just talking about the current map/unmap calls themselves. This infrastructure for tracking it looks like it's intended to be generic for all mapping methods. If not, I can't see the reason for it, because I don't think the current interface requires such tracking inherently.
Quoted 7 lines
It does seem that way, but there is a purpose. We need to unmap everything on release. It's easy to assume that
iommu_domain_free()will unmap everything from the IOMMU, which it does, but we've also done aget_user_pageson each of those in vfio, which we need to cleanup. We can't rely on userspace to do this since they might have been SIGKILL'd. Making it generic with coalescing of adjacent regions and such is primarily for space efficiency.
Quoted 8 lines
Ah, I see. Much as generic infrastructure is nice when we can do it, I think this consideration will have to be pushed down to the iommu driver layer. For e.g. on power, we have all the information we need to do the page tracking; any write to a TCE put()s the page that was previously in that entry (if any) as well as get()ing the one that's going in (if any). It's just that we don't want to keep track in this generic data structure
_aswellas_the one that's natural for the hardware.
There are few users of the IOMMU API, maybe we can negotiate this. I also expect as power gets added, we'll need to make the vfio_iommu layer more modular. It's possible you won't make use of this iommu object and can leave page tracking to the iommu. I think that can be done within the existing API though. Thanks,
Alex
Quoted 7 lines · David Gibson
I think we need to pin exactly what "
MAP_ANY" means down better. Now, VFIO is pretty much a lost cause if you can't map any normal process memory page into the IOMMU, so I think the only thing that is really covered is IOVAs. But saying "can map any IOVA" is not clear, because if you can't map it, it's not a (valid) IOVA. Better to say that IOVAs can be any 64-bit value, which I think is what you really mean here.
It also means that there are no restrictions on what the IOVA can be within that range (other than page alignment), which isn't true on our IOMMU.
We'll also need a way to communicate the desired geometry of the overall IOMMU table (for this group) to the kernel, which determines what the restrictions will be (we can't determine it automatically until we know what all the translation requests will be, and even then it's awkward).
Quoted 10 lines · Alex Williamson
Documentation/vfio.txt line 209
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+When a level triggered interrupt is signaled, the interrupt is masked +on the host. This prevents an unresponsive userspace driver from +continuing to interrupt the host system. After servicing the interrupt, +UNMASK_IRQ is used to allow the interrupt to retrigger. Note that level +triggered interrupts implicitly have a count of 1 per index.This is a silly restriction. Even PCI devices can have up to 4 LSIs on a function in theory, though no-one ever does. Embedded devices can and do have multiple level interrupts.
Those interrupts would each have their own index. This is necessary for level-triggered interrupts since they'll need to be individually identifiable to VFIO_DEVICE_UNMASK_IRQ -- doesn't seem worth adding another parameter to UNMASK.
Quoted 9 lines
drivers/vfio/vfio_iommu.c line 519
Quoted 6 lines
drivers/vfio/vfio_iommu.c new file +6
-0+#ifdef CONFIG_COMPAT +static long vfio_iommu_compat_ioctl (struct file *filep, +unsigned int cmd,unsigned long arg) +{ + arg = (unsigned long )compat_ptr (arg); +return vfio_iommu_unl_ioctl (filep, cmd, arg);Um, this only works if the structures are exactly compatible between 32-bit and 64-bit ABIs. I don't think that is always true.
These are new structs, we can make it true.
Quoted 10 lines
drivers/vfio/vfio_main.c line 41
Quoted 4 lines
drivers/vfio/vfio_main.c new file +4
-0+static int allow_unsafe_intrs; +module_param (allow_unsafe_intrs, int,0 ); +MODULE_PARM_DESC (allow_unsafe_intrs, +"Allow use of IOMMUs which do not support interrupt remapping" );This should not be a global option, but part of the AMD/Intel IOMMU specific code. In general it's a question of how strict the IOMMU driver is about isolation when it determines what the groups are, and only the IOMMU driver can know what the possibilities are for its class of hardware.
It's also a concern that is specific to MSIs. In any case, I'm not sure that the ability to cause a spurious IRQ is bad enough to warrant disabling the entire subsystem by default on certain hardware.
Probably best to just print a warning on module init if there are any known isolation holes, and let the admin decide whom (if anyone) to let use this. If the hole is bad enough that it must be confirmed, it should require at most a sysfs poke.
-Scott
Quoted 1 line · Scott Wood
On 11/15/2011 12:34 AM, David Gibson wrote:
<snip>
Quoted 11 lines
Quoted 10 lines
drivers/vfio/vfio_main.c line 41
Quoted 4 lines
drivers/vfio/vfio_main.c new file +4
-0+static int allow_unsafe_intrs; +module_param (allow_unsafe_intrs, int,0 ); +MODULE_PARM_DESC (allow_unsafe_intrs, +"Allow use of IOMMUs which do not support interrupt remapping" );This should not be a global option, but part of the AMD/Intel IOMMU specific code. In general it's a question of how strict the IOMMU driver is about isolation when it determines what the groups are, and only the IOMMU driver can know what the possibilities are for its class of hardware.
Quoted 3 lines
It's also a concern that is specific to MSIs. In any case, I'm not sure that the ability to cause a spurious IRQ is bad enough to warrant disabling the entire subsystem by default on certain hardware.
I think the issue is more that the ability to create fake MSI interrupts can lead to bigger exploits.
Originally we didn't have this parameter. It was added it to reflect the fact that MSI's triggered by guests are dangerous without the isolation that interrupt remapping provides.
That is, it *should* be inconvenient to run without interrupt mapping HW support.
-Aaron
Quoted 7 lines
Probably best to just print a warning on module init if there are any known isolation holes, and let the admin decide whom (if anyone) to let use this. If the hole is bad enough that it must be confirmed, it should require at most a sysfs poke.
-Scott
Quoted 25 lines · Aaron Fabbri
Quoted 1 line · Scott Wood
On 11/15/2011 12:34 AM, David Gibson wrote:
<snip>
Quoted 11 lines
Quoted 10 lines
drivers/vfio/vfio_main.c line 41
Quoted 4 lines
drivers/vfio/vfio_main.c new file +4
-0+static int allow_unsafe_intrs; +module_param (allow_unsafe_intrs, int,0 ); +MODULE_PARM_DESC (allow_unsafe_intrs, +"Allow use of IOMMUs which do not support interrupt remapping" );This should not be a global option, but part of the AMD/Intel IOMMU specific code. In general it's a question of how strict the IOMMU driver is about isolation when it determines what the groups are, and only the IOMMU driver can know what the possibilities are for its class of hardware.
Quoted 3 lines
It's also a concern that is specific to MSIs. In any case, I'm not sure that the ability to cause a spurious IRQ is bad enough to warrant disabling the entire subsystem by default on certain hardware.
I think the issue is more that the ability to create fake MSI interrupts can lead to bigger exploits.
Quoted 6 lines
Originally we didn't have this parameter. It was added it to reflect the fact that MSI's triggered by guests are dangerous without the isolation that interrupt remapping provides.
That is, it *should* be inconvenient to run without interrupt mapping HW support.
A sysfs knob is sufficient inconvenience. It should only affect whether you can use MSIs, and the relevant issue shouldn't be "has interrupt remapping" but "is there a hole".
Some systems might address the issue in ways other than IOMMU-level MSI translation. Our interrupt controller provides enough separate 4K pages for MSI interrupt delivery for each PCIe IOMMU group to get its own (we currently only have 3, one per root complex) -- no special IOMMU feature required.
It doesn't help that the semantics of IOMMU_CAP_INTR_REMAP are undefined. I shouldn't have to know how x86 IOMMUs work when implementing a driver for different hardware, just to know what the generic code is expecting.
As David suggests, if you want to do this it should be the x86 IOMMU driver that has a knob that controls how it forms groups in the absence of this support.
-Scott
Quoted 43 lines · Scott Wood
Quoted 25 lines · Aaron Fabbri
Quoted 1 line · Scott Wood
On 11/15/2011 12:34 AM, David Gibson wrote:
<snip>
Quoted 11 lines
Quoted 10 lines
drivers/vfio/vfio_main.c line 41
Quoted 4 lines
drivers/vfio/vfio_main.c new file +4
-0+static int allow_unsafe_intrs; +module_param (allow_unsafe_intrs, int,0 ); +MODULE_PARM_DESC (allow_unsafe_intrs, +"Allow use of IOMMUs which do not support interrupt remapping" );This should not be a global option, but part of the AMD/Intel IOMMU specific code. In general it's a question of how strict the IOMMU driver is about isolation when it determines what the groups are, and only the IOMMU driver can know what the possibilities are for its class of hardware.
Quoted 3 lines
It's also a concern that is specific to MSIs. In any case, I'm not sure that the ability to cause a spurious IRQ is bad enough to warrant disabling the entire subsystem by default on certain hardware.
I think the issue is more that the ability to create fake MSI interrupts can lead to bigger exploits.
Quoted 6 lines
Originally we didn't have this parameter. It was added it to reflect the fact that MSI's triggered by guests are dangerous without the isolation that interrupt remapping provides.
That is, it *should* be inconvenient to run without interrupt mapping HW support.
A sysfs knob is sufficient inconvenience. It should only affect whether you can use MSIs, and the relevant issue shouldn't be "has interrupt remapping" but "is there a hole".
Some systems might address the issue in ways other than IOMMU-level MSI translation. Our interrupt controller provides enough separate 4K pages for MSI interrupt delivery for each PCIe IOMMU group to get its own (we currently only have 3, one per root complex) -- no special IOMMU feature required.
Quoted 8 lines
It doesn't help that the semantics of
IOMMU_CAP_INTR_REMAPare undefined. I shouldn't have to know how x86 IOMMUs work when implementing a driver for different hardware, just to know what the generic code is expecting.As David suggests, if you want to do this it should be the x86 IOMMU driver that has a knob that controls how it forms groups in the absence of this support.
That is a possibility, we could push it down to the iommu driver which could simply lump everything into a single groupid when interrupt remapping is not supported. Or more directly, when there is an exposure that devices can trigger random MSIs in the host. Then we wouldn't need an option to override this in vfio, you'd just be stuck not being able to use any devices if you can't bind everything to vfio. That also eliminates the possibility of flipping it on dynamically since we can't handle groupids changing. Then we'd need an iommu=group_unsafe_msi flag to enable it. Ok? Thanks,
Alex
Quoted 7 lines · David Gibson
I think we need to pin exactly what "
MAP_ANY" means down better. Now, VFIO is pretty much a lost cause if you can't map any normal process memory page into the IOMMU, so I think the only thing that is really covered is IOVAs. But saying "can map any IOVA" is not clear, because if you can't map it, it's not a (valid) IOVA. Better to say that IOVAs can be any 64-bit value, which I think is what you really mean here.
It also means that there are no restrictions on what the IOVA can be within that range (other than page alignment), which isn't true on our IOMMU.
We'll also need a way to communicate the desired geometry of the overall IOMMU table (for this group) to the kernel, which determines what the restrictions will be (we can't determine it automatically until we know what all the translation requests will be, and even then it's awkward).
Quoted 10 lines · Alex Williamson
Documentation/vfio.txt line 209
Quoted 5 lines
Documentation/vfio.txt new file +5
-0+When a level triggered interrupt is signaled, the interrupt is masked +on the host. This prevents an unresponsive userspace driver from +continuing to interrupt the host system. After servicing the interrupt, +UNMASK_IRQ is used to allow the interrupt to retrigger. Note that level +triggered interrupts implicitly have a count of 1 per index.This is a silly restriction. Even PCI devices can have up to 4 LSIs on a function in theory, though no-one ever does. Embedded devices can and do have multiple level interrupts.
Those interrupts would each have their own index. This is necessary for level-triggered interrupts since they'll need to be individually identifiable to VFIO_DEVICE_UNMASK_IRQ -- doesn't seem worth adding another parameter to UNMASK.
Quoted 9 lines
drivers/vfio/vfio_iommu.c line 519
Quoted 6 lines
drivers/vfio/vfio_iommu.c new file +6
-0+#ifdef CONFIG_COMPAT +static long vfio_iommu_compat_ioctl (struct file *filep, +unsigned int cmd,unsigned long arg) +{ + arg = (unsigned long )compat_ptr (arg); +return vfio_iommu_unl_ioctl (filep, cmd, arg);Um, this only works if the structures are exactly compatible between 32-bit and 64-bit ABIs. I don't think that is always true.
These are new structs, we can make it true.
Quoted 10 lines
drivers/vfio/vfio_main.c line 41
Quoted 4 lines
drivers/vfio/vfio_main.c new file +4
-0+static int allow_unsafe_intrs; +module_param (allow_unsafe_intrs, int,0 ); +MODULE_PARM_DESC (allow_unsafe_intrs, +"Allow use of IOMMUs which do not support interrupt remapping" );This should not be a global option, but part of the AMD/Intel IOMMU specific code. In general it's a question of how strict the IOMMU driver is about isolation when it determines what the groups are, and only the IOMMU driver can know what the possibilities are for its class of hardware.
It's also a concern that is specific to MSIs. In any case, I'm not sure that the ability to cause a spurious IRQ is bad enough to warrant disabling the entire subsystem by default on certain hardware.
Probably best to just print a warning on module init if there are any known isolation holes, and let the admin decide whom (if anyone) to let use this. If the hole is bad enough that it must be confirmed, it should require at most a sysfs poke.
-Scott
Hi!
I tried (successfully) to run it on POWER and while doing that I found some issues. I'll try to explain them in separate mails.
IOMMU domain setup. On POWER, the linux drivers capable of DMA transfer want to know a DMA window, i.e. its start and length in the PHB address space. This comes from hardware. On X86 (correct if I am wrong), every device driver in the guest allocates memory from the same pool. On POWER, device drivers get DMA window and allocate pages for DMA within this window. In the case of VFIO, that means that QEMU has to preallocate this DMA window before running a quest, pass it to a guest (via device tree) and then a guest tells the host what pages are taken/released by calling map/unmap callbacks of iommu_ops. Deallocation is made in a device detach callback as I did not want to add more ioctls.
So, there are 2 patches:
- new VFIO_IOMMU_SETUP ioctl introduced which allocates a DMA window via IOMMU API on POWER.
btw do we need an additional capability bit for it?
KERNEL PATCH:
drivers/iommu/iommu.c +9 -0
@@ -247,3 +247,12 @@ int iommu_device_group(struct device *dev, unsigned int *groupid)return -ENODEV ; }EXPORT_SYMBOL_GPL (iommu_device_group); + +int iommu_setup (struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address) +{ +return domain->ops->setup (domain, requested_size, allocated_size, + start_address); +} +EXPORT_SYMBOL_GPL (iommu_setup);
drivers/vfio/vfio_iommu.c +17 -0
@@ -507,6 +507,23 @@ static long vfio_iommu_unl_ioctl(struct file *filep,if (!ret &©_to_user ((void __user *)arg, &dm,sizeof dm)) ret = -EFAULT ; + + }else if (cmd ==VFIO_IOMMU_SETUP ) { +struct vfio_setup setup; +size_t allocated_size =0 ; +phys_addr_t start_address =0 ; + +if (copy_from_user (&setup, (void __user *)arg,sizeof setup)) +return -EFAULT ; + +printk ("udomain %p, priv=%p\n" , iommu->domain, iommu->domain->priv); + ret =iommu_setup (iommu->domain, setup.requested_size, + &allocated_size, &start_address); + setup.allocated_size = allocated_size; + setup.start_address = start_address; + +if (!ret &©_to_user ((void __user *)arg, &setup,sizeof setup)) + ret = -EFAULT ; }return ret; }
include/linux/iommu.h +7 -0
@@ -45,6 +45,7 @@ struct iommu_domain {#define IOMMU_CAP_CACHE_COHERENCY 0x1#define IOMMU_CAP_INTR_REMAP 0x2/* isolates device intrs */ +#define IOMMU_CAP_SETUP_REQUIRED 0x3/* requires setup to be called */ #ifdef CONFIG_IOMMU_API
@@ -62,6 +63,9 @@ struct iommu_ops {int (*domain_has_cap)(struct iommu_domain *domain,unsigned long cap);int (*device_group)(struct device *dev,unsigned int *groupid); +int (*setup)(struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address); };extern int bus_set_iommu (struct bus_type *bus,struct iommu_ops *ops);
@@ -80,6 +84,9 @@ extern phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, unsigned long iova);extern int iommu_domain_has_cap (struct iommu_domain *domain,unsigned long cap); +extern int iommu_setup (struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address);extern void iommu_set_fault_handler (struct iommu_domain *domain,iommu_fault_handler_t handler);extern int iommu_device_group (struct device *dev,unsigned int *groupid);
include/linux/vfio.h +10 -0
@@ -26,6 +26,7 @@* Author: Michael S. Tsirkin <[email protected]> */ #include <linux/types.h> +#include <linux/ioctl.h> #ifndef VFIO_H #define VFIO_H
@@ -172,4 +173,13 @@ enum {VFIO_PCI_NUM_IRQS }; +/* Setup domain */ +#define VFIO_IOMMU_SETUP _IOWR(';', 150, struct vfio_setup) + +struct vfio_setup { +__u64 requested_size; +__u64 allocated_size; +__u64 start_address; +}; +#endif /* VFIO_H */
=== end ===
QEMU PATCH:
hw/linux-vfio.h +9 -0
@@ -172,4 +172,13 @@ enum {VFIO_PCI_NUM_IRQS }; +/* Setup domain */ +#define VFIO_IOMMU_SETUP _IOWR(';', 150, struct vfio_setup) + +struct vfio_setup { +__u64 requested_size; +__u64 allocated_size; +__u64 start_address; +}; +#endif /* VFIO_H */
hw/vfio_pci.c +11 -0
@@ -1501,6 +1503,17 @@ static int vfio_initfn(struct PCIDevice *pdev)if (vfio_map_resources (vdev)) goto out_disable_msi; +struct vfio_setup setup = {1 <<26 ,0 ,0 }; +if ((ret =ioctl (vdev->group->iommu->fd,VFIO_IOMMU_SETUP , &setup))) { +return ret; + } +printf ("SETUP: requested %lluMB, allocated %lluMB at %llx\n" , + (unsigned long long )setup.requested_size, + (unsigned long long )setup.allocated_size, + (unsigned long long )setup.start_address); + vdev->start_address = setup.start_address; + vdev->window_size = setup.allocated_size; +if (vfio_enable_intx (vdev)) goto out_unmap_resources;
hw/vfio_pci.h +4 -0
@@ -79,6 +79,10 @@ typedef struct VFIODevice {bool msix;uint8_t msix_bar;uint16_t msix_entries; +#ifdef TARGET_PPC +uint64_t start_address; +uint32_t window_size; +#endif } VFIODevice; typedef struct VFIOGroup {
=== end ===
- changed __vfio_close_iommu function to do unmapall first and detach devices then as actual deallocation happens on device detach callback of IOMMU ops.
drivers/vfio/vfio_main.c +9 -1
@@ -28,6 +28,7 @@#include <linux/uaccess.h> #include <linux/vfio.h> #include <linux/wait.h> +#include <linux/pci.h> #include "vfio_private.h"
@@ -242,6 +243,13 @@ static void __vfio_close_iommu(struct vfio_iommu *iommu)if (!iommu->domain)return ; +/* +* On POWER, device detaching (which is done by __vfio_iommu_detach_group) +* should happen after all pages unmapped because +* the only way to do actual iommu_unmap_page a device detach callback +*/ +vfio_iommu_unmapall (iommu); +list_for_each (pos, &iommu->group_list) {struct vfio_group *group; group = list_entry(pos, struct vfio_group, iommu_next);
@@ -249,7 +257,7 @@ static void __vfio_close_iommu(struct vfio_iommu *iommu)__vfio_iommu_detach_group (iommu, group); } -vfio_iommu_unmapall (iommu); +/* vfio_iommu_unmapall(iommu); */ iommu_domain_free (iommu->domain); iommu->domain =NULL ;
Quoted 46 lines · Alex Williamson
VFIO provides a secure, IOMMU based interface for user space drivers, including device assignment to virtual machines. This provides the base management of IOMMU groups, devices, and IOMMU objects. See
Documentation/vfio.txtincluded in this patch for user and kernel API description.Note, this implements the new API discussed at KVM Forum 2011, as represented by the drvier version 0.2. It's hoped that this provides a modular enough interface to support PCI and non-PCI userspace drivers across various architectures and IOMMU implementations.
Signed-off-by Alex Williamson <[email protected]>---
Fingers crossed, this is the last RFC for VFIO, but we need the iommu group support before this can go upstream
(http://lkml.indiana.edu/hypermail/linux/kernel/1110.2/02303.html),
hoping this helps push that along.Since the last posting, this version completely modularizes the device backends and better defines the APIs between the core VFIO code and the device backends. I expect that we might also adopt a modular IOMMU interface as
iommu_opslearns about different types of hardware. Also many, many cleanups. Check the complete git history for details:
git://github.com/awilliam/linux-vfio.gitvfio-ng(matching qemu tree:
git://github.com/awilliam/qemu-vfio.git)This version, along with the supporting VFIO PCI backend can be found here:
git://github.com/awilliam/linux-vfio.gitvfio-next-20111103I've held off on implementing a
kernel->usersignaling mechanism for now since the previous netlink version produced too many gag reflexes. It's easy enough to set a bit in the group flags too indicate such support in the future, so I think we can move ahead without it.Appreciate any feedback or suggestions. Thanks,
Alex
Signature · 5 lines
Alexey Kardashevskiy IBM OzLabs, LTC Team e-mail: [email protected] notes: Alexey Kardashevskiy/Australia/IBM
Hi all,
Another problem I hit on POWER - MSI interrupts allocation. The existing VFIO does not expect a PBH to support less interrupts that a device might request. In my case, PHB's limit is 8 interrupts while my test card (10Gb ethernet CXGB3) wants 9. Below are the patches to demonstrate the idea.
KERNEL patch:
drivers/vfio/pci/vfio_pci_intrs.c +24 -9
@@ -458,17 +458,32 @@ int vfio_pci_setup_msix(struct vfio_pci_device *vdev, int nvec, int __user *inta vdev->msix[i].entry = i; vdev->ev_msix[i] = ctx; } -if (!ret) +if (!ret) { ret =pci_enable_msix (pdev, vdev->msix, nvec); +/* +The kernel is unable to allocate requested number of IRQs +and returned the available number. +*/ +if (0 < ret) { + ret =pci_enable_msix (pdev, vdev->msix, ret); + } + } vdev->msix_nvec =0 ; -for (i =0 ; i < nvec && !ret; i++) { - ret =request_irq (vdev->msix[i].vector, msihandler,0 , -"vfio" , vdev->ev_msix[i]); -if (ret) -break ; - vdev->msix_nvec = i+1 ; +if (0 == ret) { + vdev->msix_nvec =0 ; + ret =0 ; +for (i =0 ; i < nvec && !ret; i++) { + ret =request_irq (vdev->msix[i].vector, msihandler,0 , +"vfio" , vdev->ev_msix[i]); +if (ret) +break ; + vdev->msix_nvec = i+1 ; + } +if ((0 == vdev->msix_nvec) && (0 != ret)) +vfio_pci_drop_msix (vdev); +else + ret = vdev->msix_nvec; } -if (ret) -vfio_pci_drop_msix (vdev); +return ret; }
=== end ===
QEMU patch:
hw/vfio_pci.c +4 -1
@@ -341,7 +341,8 @@ static void vfio_enable_msi(VFIODevice *vdev, bool msix) } } -if (ioctl (vdev->fd,VFIO_DEVICE_SET_IRQ_EVENTFDS , fds)) { + ret =ioctl (vdev->fd,VFIO_DEVICE_SET_IRQ_EVENTFDS , fds); +if (0 > ret) {fprintf (stderr,"vfio: Error: Failed to setup MSI/X fds %s\n" ,strerror (errno));for (i =0 ; i < vdev->nr_vectors; i++) {
@@ -355,6 +356,8 @@ static void vfio_enable_msi(VFIODevice *vdev, bool msix)qemu_free (vdev->msi_vectors); vdev->nr_vectors =0 ;return ; + }else if (0 < ret) { + vdev->nr_vectors = ret; } vdev->interrupt = msix ?INT_MSIX :INT_MSI ;
=== end ===
Quoted 56 lines · Alexey Kardashevskiy
Hi!
I tried (successfully) to run it on POWER and while doing that I found some issues. I'll try to explain them in separate mails.
Quoted 46 lines · Alex Williamson
VFIO provides a secure, IOMMU based interface for user space drivers, including device assignment to virtual machines. This provides the base management of IOMMU groups, devices, and IOMMU objects. See
Documentation/vfio.txtincluded in this patch for user and kernel API description.Note, this implements the new API discussed at KVM Forum 2011, as represented by the drvier version 0.2. It's hoped that this provides a modular enough interface to support PCI and non-PCI userspace drivers across various architectures and IOMMU implementations.
Signed-off-by Alex Williamson <[email protected]>---
Fingers crossed, this is the last RFC for VFIO, but we need the iommu group support before this can go upstream
(http://lkml.indiana.edu/hypermail/linux/kernel/1110.2/02303.html),
hoping this helps push that along.Since the last posting, this version completely modularizes the device backends and better defines the APIs between the core VFIO code and the device backends. I expect that we might also adopt a modular IOMMU interface as
iommu_opslearns about different types of hardware. Also many, many cleanups. Check the complete git history for details:
git://github.com/awilliam/linux-vfio.gitvfio-ng(matching qemu tree:
git://github.com/awilliam/qemu-vfio.git)This version, along with the supporting VFIO PCI backend can be found here:
git://github.com/awilliam/linux-vfio.gitvfio-next-20111103I've held off on implementing a
kernel->usersignaling mechanism for now since the previous netlink version produced too many gag reflexes. It's easy enough to set a bit in the group flags too indicate such support in the future, so I think we can move ahead without it.Appreciate any feedback or suggestions. Thanks,
Alex
Signature · 5 lines
Alexey Kardashevskiy IBM OzLabs, LTC Team e-mail: [email protected] notes: Alexey Kardashevskiy/Australia/IBM
Hi all again,
It was actually the very first problem - endianess :-)
I am still not sure what format is better for cached config space or whether we should cache it all.
Also, as Benh already mentioned, vfio_virt_init reads a config space to a cache by pci_read_config_dword for the whole space while some devices may not like it as they might distinguish length of PCI transactions.
KERNEL patch:
drivers/vfio/pci/vfio_pci_config.c +17 -7
@@ -757,6 +757,16 @@ static int vfio_virt_init(struct vfio_pci_device *vdev) vdev->rbar[5 ] = *(u32 *)&vdev->vconfig[PCI_BASE_ADDRESS_5 ]; vdev->rbar[6 ] = *(u32 *)&vdev->vconfig[PCI_ROM_ADDRESS ]; +/* +* As pci_read_config_XXXX returns data in native format, +* and the cached copy is used in assumption that it is +* native PCI format, fix endianness in the cached copy. +*/ + lp = (u32 *)vdev->vconfig; +for (i =0 ; i < pdev->cfg_size/sizeof (u32); i++, lp++) { + *lp =cpu_to_le32 (*lp); + } +/* for sr-iov devices */ vdev->vconfig[PCI_VENDOR_ID ] = pdev->vendor &0xFF ; vdev->vconfig[PCI_VENDOR_ID +1 ] = pdev->vendor >>8 ;
@@ -807,18 +817,18 @@ static void vfio_bar_fixup(struct vfio_pci_device *vdev)else mask =0 ; lp = (u32 *)(vdev->vconfig +PCI_BASE_ADDRESS_0 +4 *bar); - *lp &= (u32 )mask; + *lp &=cpu_to_le32 ((u32 )mask);if (pci_resource_flags (pdev, bar) &IORESOURCE_IO ) - *lp |=PCI_BASE_ADDRESS_SPACE_IO ; + *lp |=cpu_to_le32 (PCI_BASE_ADDRESS_SPACE_IO );else if (pci_resource_flags (pdev, bar) &IORESOURCE_MEM ) { - *lp |=PCI_BASE_ADDRESS_SPACE_MEMORY ; + *lp |=cpu_to_le32 (PCI_BASE_ADDRESS_SPACE_MEMORY );if (pci_resource_flags (pdev, bar) &IORESOURCE_PREFETCH ) - *lp |=PCI_BASE_ADDRESS_MEM_PREFETCH ; + *lp |=cpu_to_le32 (PCI_BASE_ADDRESS_MEM_PREFETCH );if (pci_resource_flags (pdev, bar) &IORESOURCE_MEM_64 ) { - *lp |=PCI_BASE_ADDRESS_MEM_TYPE_64 ; + *lp |=cpu_to_le32 (PCI_BASE_ADDRESS_MEM_TYPE_64 ); lp++; - *lp &= (u32)(mask >>32 ); + *lp &=cpu_to_le32 ((u32)(mask >>32 )); bar++; } }
@@ -830,7 +840,7 @@ static void vfio_bar_fixup(struct vfio_pci_device *vdev) }else mask =0 ; lp = (u32 *)(vdev->vconfig +PCI_ROM_ADDRESS ); - *lp &= (u32 )mask; + *lp &=cpu_to_le32 ((u32 )mask); vdev->bardirty =0 ; }
=== end ===
QEMU patch:
hw/vfio_pci.c +32 -2
@@ -405,6 +405,8 @@ static void vfio_resource_write(void *opaque, target_phys_addr_t addr, {PCIResource *res = opaque; +fprintf (stderr,"change endianness????\n" ); +if (pwrite (res->fd, &data, size, res->offset + addr) != size) {fprintf (stderr,"%s(,0x%" PRIx64", 0x%" PRIx64", %d) failed: %s\n" , __FUNCTION__, addr, data, size,strerror (errno));
@@ -429,6 +431,9 @@ static uint64_t vfio_resource_read(void *opaque,DPRINTF ("%s(BAR%d+0x%" PRIx64", %d) = 0x%" PRIx64"\n" , __FUNCTION__, res->bar, addr, size, data); + data =le32_to_cpu (data); +DPRINTF ("%s(BAR%d+0x%" PRIx64", %d) = 0x%" PRIx64" --- CPU\n" , + __FUNCTION__, res->bar, addr, size, data);return data; }
@@ -454,13 +459,25 @@ static uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len) val =pci_default_read_config (pdev, addr, len); }else { -if (pread (vdev->fd, &val, len, vdev->config_offset + addr) != len) { +u8 buf[4 ] = {0 }; +if (pread (vdev->fd, buf, len, vdev->config_offset + addr) != len) {fprintf (stderr,"%s(%04x:%02x:%02x.%x, 0x%x, 0x%x) failed: %s\n" , __FUNCTION__, vdev->host.seg, vdev->host.bus, vdev->host.dev, vdev->host.func, addr, len,strerror (errno));return -1 ; } +switch (len) { +case 1 : val = buf[0 ];break ; +case 2 : val =le16_to_cpupu ((uint16_t *)buf);break ; +case 4 : val =le32_to_cpupu ((uint32_t *)buf);break ; +default : +fprintf (stderr,"%s(%04x:%02x:%02x.%x, 0x%x, 0x%x) failed: %s\n" , + __FUNCTION__, vdev->host.seg, vdev->host.bus, + vdev->host.dev, vdev->host.func, addr, len, +strerror (errno)); +break ; + } } DPRINTF("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x) %x\n", __FUNCTION__, vdev->host.seg, vdev->host.bus, vdev->host.dev,
@@ -477,8 +494,20 @@ static void vfio_pci_write_config(PCIDevice *pdev, uint32_t addr, vdev->host.seg, vdev->host.bus, vdev->host.dev, vdev->host.func, addr, val, len); +u8 buf[4 ] = {0 }; +switch (len) { +case 1 : buf[0 ] = val &0xFF ;break ; +case 2 :cpu_to_le16wu ((uint16_t *)buf, val);break ; +case 4 :cpu_to_le32wu ((uint32_t *)buf, val);break ; +default : +fprintf (stderr,"%s(%04x:%02x:%02x.%x, 0x%x, 0x%x, 0x%x) failed: %s\n" , + __FUNCTION__, vdev->host.seg, vdev->host.bus, vdev->host.dev, + vdev->host.func, addr, val, len,strerror (errno)); +return ; + } +/* Write everything to VFIO, let it filter out what we can't write */ -if (pwrite (vdev->fd, &val, len, vdev->config_offset + addr) != len) { +if (pwrite (vdev->fd, buf, len, vdev->config_offset + addr) != len) {fprintf (stderr,"%s(%04x:%02x:%02x.%x, 0x%x, 0x%x, 0x%x) failed: %s\n" , __FUNCTION__, vdev->host.seg, vdev->host.bus, vdev->host.dev, vdev->host.func, addr, val, len,strerror (errno));
@@ -675,6 +704,7 @@ static int vfio_setup_msi(VFIODevice *vdev) vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {return -1 ; } + ctrl =le16_to_cpu (ctrl); msi_64bit = !!(ctrl &PCI_MSI_FLAGS_64BIT ); msi_maskbit = !!(ctrl &PCI_MSI_FLAGS_MASKBIT );
=== end ===
Quoted 69 lines · Alexey Kardashevskiy
Hi all,
Another problem I hit on POWER - MSI interrupts allocation. The existing VFIO does not expect a PBH to support less interrupts that a device might request. In my case, PHB's limit is 8 interrupts while my test card (10Gb ethernet CXGB3) wants 9. Below are the patches to demonstrate the idea.
Quoted 56 lines · Alexey Kardashevskiy
Hi!
I tried (successfully) to run it on POWER and while doing that I found some issues. I'll try to explain them in separate mails.
Quoted 46 lines · Alex Williamson
VFIO provides a secure, IOMMU based interface for user space drivers, including device assignment to virtual machines. This provides the base management of IOMMU groups, devices, and IOMMU objects. See
Documentation/vfio.txtincluded in this patch for user and kernel API description.Note, this implements the new API discussed at KVM Forum 2011, as represented by the drvier version 0.2. It's hoped that this provides a modular enough interface to support PCI and non-PCI userspace drivers across various architectures and IOMMU implementations.
Signed-off-by Alex Williamson <[email protected]>---
Fingers crossed, this is the last RFC for VFIO, but we need the iommu group support before this can go upstream
(http://lkml.indiana.edu/hypermail/linux/kernel/1110.2/02303.html),
hoping this helps push that along.Since the last posting, this version completely modularizes the device backends and better defines the APIs between the core VFIO code and the device backends. I expect that we might also adopt a modular IOMMU interface as
iommu_opslearns about different types of hardware. Also many, many cleanups. Check the complete git history for details:
git://github.com/awilliam/linux-vfio.gitvfio-ng(matching qemu tree:
git://github.com/awilliam/qemu-vfio.git)This version, along with the supporting VFIO PCI backend can be found here:
git://github.com/awilliam/linux-vfio.gitvfio-next-20111103I've held off on implementing a
kernel->usersignaling mechanism for now since the previous netlink version produced too many gag reflexes. It's easy enough to set a bit in the group flags too indicate such support in the future, so I think we can move ahead without it.Appreciate any feedback or suggestions. Thanks,
Alex
Signature · 5 lines
Alexey Kardashevskiy IBM OzLabs, LTC Team e-mail: [email protected] notes: Alexey Kardashevskiy/Australia/IBM
Quoted 5 lines · Alexey Kardashevskiy
Hi all,
Another problem I hit on POWER - MSI interrupts allocation. The existing VFIO does not expect a PBH to support less interrupts that a device might request. In my case, PHB's limit is 8 interrupts while my test card (10Gb ethernet CXGB3) wants 9. Below are the patches to demonstrate the idea.
Seems reasonable. I assume we'd need similar for vfio_pci_setup_msi, though I haven't seen anything use more than a single MSI interrupt. Thanks,
Alex
Quoted 80 lines
KERNEL patch:
drivers/vfio/pci/vfio_pci_intrs.c +24
-9@@ -458,17 +458,32 @@ int vfio_pci_setup_msix(struct vfio_pci_device *vdev, int nvec, int __user *inta vdev->msix[i].entry = i; vdev->ev_msix[i] = ctx; } -if (!ret) +if (!ret) { ret =pci_enable_msix (pdev, vdev->msix, nvec); +/* +The kernel is unable to allocate requested number of IRQs +and returned the available number. +*/ +if (0 < ret) { + ret =pci_enable_msix (pdev, vdev->msix, ret); + } + } vdev->msix_nvec =0 ; -for (i =0 ; i < nvec && !ret; i++) { - ret =request_irq (vdev->msix[i].vector, msihandler,0 , -"vfio" , vdev->ev_msix[i]); -if (ret) -break ; - vdev->msix_nvec = i+1 ; +if (0 == ret) { + vdev->msix_nvec =0 ; + ret =0 ; +for (i =0 ; i < nvec && !ret; i++) { + ret =request_irq (vdev->msix[i].vector, msihandler,0 , +"vfio" , vdev->ev_msix[i]); +if (ret) +break ; + vdev->msix_nvec = i+1 ; + } +if ((0 == vdev->msix_nvec) && (0 != ret)) +vfio_pci_drop_msix (vdev); +else + ret = vdev->msix_nvec; } -if (ret) -vfio_pci_drop_msix (vdev); +return ret; }=== end ===
QEMU patch:
hw/vfio_pci.c +4
-1@@ -341,7 +341,8 @@ static void vfio_enable_msi(VFIODevice *vdev, bool msix) } } -if (ioctl (vdev->fd,VFIO_DEVICE_SET_IRQ_EVENTFDS , fds)) { + ret =ioctl (vdev->fd,VFIO_DEVICE_SET_IRQ_EVENTFDS , fds); +if (0 > ret) {fprintf (stderr,"vfio: Error: Failed to setup MSI/X fds %s\n" ,strerror (errno));for (i =0 ; i < vdev->nr_vectors; i++) {@@ -355,6 +356,8 @@ static void vfio_enable_msi(VFIODevice *vdev, bool msix)qemu_free (vdev->msi_vectors); vdev->nr_vectors =0 ;return ; + }else if (0 < ret) { + vdev->nr_vectors = ret; } vdev->interrupt = msix ?INT_MSIX :INT_MSI ;=== end ===
Quoted 10 lines · Alex Williamson
Quoted 5 lines · Alexey Kardashevskiy
Hi all,
Another problem I hit on POWER - MSI interrupts allocation. The existing VFIO does not expect a PBH to support less interrupts that a device might request. In my case, PHB's limit is 8 interrupts while my test card (10Gb ethernet CXGB3) wants 9. Below are the patches to demonstrate the idea.
Seems reasonable. I assume we'd need similar for
vfio_pci_setup_msi, though I haven't seen anything use more than a single MSI interrupt. Thanks,
Hmm, I'm thinking maybe we should reflect the pci_enable_msix() behavior directly and let the caller decide if they want to make do with fewer MSI vectors. So the ioctl will return <0: error, 0:success, >0: number of MSIs we think we can setup, without actually setting them. Sound good?
BTW, github now has updated trees:
git://github.com/awilliam/linux-vfio.git vfio-next-20111129git://github.com/awilliam/qemu-vfio.git vfio-ng
Thanks,
Alex
Quoted 81 lines
Quoted 80 lines
KERNEL patch:
drivers/vfio/pci/vfio_pci_intrs.c +24
-9@@ -458,17 +458,32 @@ int vfio_pci_setup_msix(struct vfio_pci_device *vdev, int nvec, int __user *inta vdev->msix[i].entry = i; vdev->ev_msix[i] = ctx; } -if (!ret) +if (!ret) { ret =pci_enable_msix (pdev, vdev->msix, nvec); +/* +The kernel is unable to allocate requested number of IRQs +and returned the available number. +*/ +if (0 < ret) { + ret =pci_enable_msix (pdev, vdev->msix, ret); + } + } vdev->msix_nvec =0 ; -for (i =0 ; i < nvec && !ret; i++) { - ret =request_irq (vdev->msix[i].vector, msihandler,0 , -"vfio" , vdev->ev_msix[i]); -if (ret) -break ; - vdev->msix_nvec = i+1 ; +if (0 == ret) { + vdev->msix_nvec =0 ; + ret =0 ; +for (i =0 ; i < nvec && !ret; i++) { + ret =request_irq (vdev->msix[i].vector, msihandler,0 , +"vfio" , vdev->ev_msix[i]); +if (ret) +break ; + vdev->msix_nvec = i+1 ; + } +if ((0 == vdev->msix_nvec) && (0 != ret)) +vfio_pci_drop_msix (vdev); +else + ret = vdev->msix_nvec; } -if (ret) -vfio_pci_drop_msix (vdev); +return ret; }=== end ===
QEMU patch:
hw/vfio_pci.c +4
-1@@ -341,7 +341,8 @@ static void vfio_enable_msi(VFIODevice *vdev, bool msix) } } -if (ioctl (vdev->fd,VFIO_DEVICE_SET_IRQ_EVENTFDS , fds)) { + ret =ioctl (vdev->fd,VFIO_DEVICE_SET_IRQ_EVENTFDS , fds); +if (0 > ret) {fprintf (stderr,"vfio: Error: Failed to setup MSI/X fds %s\n" ,strerror (errno));for (i =0 ; i < vdev->nr_vectors; i++) {@@ -355,6 +356,8 @@ static void vfio_enable_msi(VFIODevice *vdev, bool msix)qemu_free (vdev->msi_vectors); vdev->nr_vectors =0 ;return ; + }else if (0 < ret) { + vdev->nr_vectors = ret; } vdev->interrupt = msix ?INT_MSIX :INT_MSI ;=== end ===
Quoted 5 lines
BTW, github now has updated trees:
git://github.com/awilliam/linux-vfio.gitvfio-next-20111129git://github.com/awilliam/qemu-vfio.gitvfio-ng
Hi Alex,
Have been looking at vfio a bit. A few observations and things
we'll need to figure out as it relates to the Freescale iommu.
__vfio_dma_map() assumes that mappings are broken into
4KB pages. That will not be true for us. We normally will be mapping
much larger physically contiguous chunks for our guests. Guests will get hugetlbfs backed memory with very large pages (e.g. 16MB, 64MB) or very large chunks allocated by some proprietary means.
Also, mappings will have additional Freescale-specific attributes
that need to get passed through to dma_map somehow. For
example, the iommu can stash directly into a CPU's cache and we have iommu mapping properties like the cache stash target id and an operation mapping attribute.
How do you envision handling proprietary attributes in struct vfio_dma_map?
Stuart
Quoted 11 lines · Stuart Yoder
Quoted 5 lines
BTW, github now has updated trees:
git://github.com/awilliam/linux-vfio.gitvfio-next-20111129git://github.com/awilliam/qemu-vfio.gitvfio-ngHi Alex,
Have been looking at vfio a bit. A few observations and things
we'll need to figure out as it relates to the Freescale iommu.
Quoted 6 lines
__vfio_dma_map()assumes that mappings are broken into
4KB pages. That will not be true for us. We normally will be mapping
much larger physically contiguous chunks for our guests. Guests will get hugetlbfs backed memory with very large pages (e.g. 16MB, 64MB) or very large chunks allocated by some proprietary means.
Hi Stuart,
I think practically everyone has commented on the 4k mappings ;) There are a few problems around this. The first is that iommu drivers don't necessarily support sub-region unmapping, so if we map 1GB and later want to unmap 4k, we can't do it atomically. 4k gives us the most flexibility for supporting fine granularities. Another problem is that we're using get_user_pages to pin memory. It's been suggested that we should use mlock for this, but I can't find anything that prevents a user from later munlock'ing the memory and then getting access to memory they shouldn't have. Those kind of limit us, but I don't see it being an API problem for VFIO, just implementation.
Quoted 8 lines
Also, mappings will have additional Freescale-specific attributes
that need to get passed through todma_mapsomehow. For
example, the iommu can stash directly into a CPU's cache and we have iommu mapping properties like the cache stash target id and an operation mapping attribute.How do you envision handling proprietary attributes in struct
vfio_dma_map?
Let me turn the question around, how do you plan to support proprietary attributes in the IOMMU API? Is the user level the appropriate place to specify them, or are they an intrinsic feature of the domain? We've designed struct vfio_dma_map for extension, so depending on how many bits you need, we can make a conduit using the flags directly or setting a new flag to indicate presence of an arch specific attributes field. Thanks,
Alex
Quoted 21 lines · Alex Williamson
Quoted 11 lines · Stuart Yoder
Quoted 5 lines
BTW, github now has updated trees:
git://github.com/awilliam/linux-vfio.gitvfio-next-20111129git://github.com/awilliam/qemu-vfio.gitvfio-ngHi Alex,
Have been looking at vfio a bit. A few observations and things we'll need to figure out as it relates to the Freescale iommu.
Quoted 6 lines
__vfio_dma_map()assumes that mappings are broken into
4KB pages. That will not be true for us. We normally will be mapping much larger physically contiguous chunks for our guests. Guests will get hugetlbfs backed memory with very large pages (e.g. 16MB, 64MB) or very large chunks allocated by some proprietary means.Hi Stuart,
Quoted 10 lines
I think practically everyone has commented on the 4k mappings ;) There are a few problems around this. The first is that iommu drivers don't necessarily support sub-region unmapping, so if we map 1GB and later want to unmap 4k, we can't do it atomically. 4k gives us the most flexibility for supporting fine granularities. Another problem is that we're using
get_user_pagesto pin memory. It's been suggested that we should use mlock for this, but I can't find anything that prevents a user from later munlock'ing the memory and then getting access to memory they shouldn't have. Those kind of limit us, but I don't see it being an API problem for VFIO, just implementation.
Ok.
Quoted 9 lines
Quoted 8 lines
Also, mappings will have additional Freescale-specific attributes that need to get passed through to
dma_mapsomehow. For example, the iommu can stash directly into a CPU's cache and we have iommu mapping properties like the cache stash target id and an operation mapping attribute.How do you envision handling proprietary attributes in struct
vfio_dma_map?
Quoted 6 lines
Let me turn the question around, how do you plan to support proprietary attributes in the IOMMU API? Is the user level the appropriate place to specify them, or are they an intrinsic feature of the domain? We've designed struct
vfio_dma_mapfor extension, so depending on how many bits you need, we can make a conduit using the flags directly or setting a new flag to indicate presence of an arch specific attributes field.
The attributes are not intrinsic features of the domain. User space will need to set them. But in thinking about it a bit more I think the attributes are more properties of the domain rather than a per map() operation characteristic. I think a separate API might be appropriate. Define a
new set_domain_attrs() op in the iommu_ops. In user space, perhaps
a new vfio group API-- VFIO_GROUP_SET_ATTRS,VFIO_GROUP_GET_ATTRS.
Stuart
Quoted 52 lines · Stuart Yoder
Quoted 21 lines · Alex Williamson
Quoted 11 lines · Stuart Yoder
Quoted 5 lines
BTW, github now has updated trees:
git://github.com/awilliam/linux-vfio.gitvfio-next-20111129git://github.com/awilliam/qemu-vfio.gitvfio-ngHi Alex,
Have been looking at vfio a bit. A few observations and things
we'll need to figure out as it relates to the Freescale iommu.Quoted 6 lines
__vfio_dma_map()assumes that mappings are broken into
4KB pages. That will not be true for us. We normally will be mapping
much larger physically contiguous chunks for our guests. Guests will get hugetlbfs backed memory with very large pages (e.g. 16MB, 64MB) or very large chunks allocated by some proprietary means.Hi Stuart,
Quoted 10 lines
I think practically everyone has commented on the 4k mappings ;) There are a few problems around this. The first is that iommu drivers don't necessarily support sub-region unmapping, so if we map 1GB and later want to unmap 4k, we can't do it atomically. 4k gives us the most flexibility for supporting fine granularities. Another problem is that we're using
get_user_pagesto pin memory. It's been suggested that we should use mlock for this, but I can't find anything that prevents a user from later munlock'ing the memory and then getting access to memory they shouldn't have. Those kind of limit us, but I don't see it being an API problem for VFIO, just implementation.Ok.
Quoted 9 lines
Quoted 8 lines
Also, mappings will have additional Freescale-specific attributes
that need to get passed through todma_mapsomehow. For
example, the iommu can stash directly into a CPU's cache and we have iommu mapping properties like the cache stash target id and an operation mapping attribute.How do you envision handling proprietary attributes in struct
vfio_dma_map?Quoted 6 lines
Let me turn the question around, how do you plan to support proprietary attributes in the IOMMU API? Is the user level the appropriate place to specify them, or are they an intrinsic feature of the domain? We've designed struct
vfio_dma_mapfor extension, so depending on how many bits you need, we can make a conduit using the flags directly or setting a new flag to indicate presence of an arch specific attributes field.
Quoted 7 lines
The attributes are not intrinsic features of the domain. User space will need to set them. But in thinking about it a bit more I think the attributes are more properties of the domain rather than a per
map()operation characteristic. I think a separate API might be appropriate. Define a
newset_domain_attrs()op in theiommu_ops. In user space, perhaps
a new vfio group API--VFIO_GROUP_SET_ATTRS,VFIO_GROUP_GET_ATTRS.
In that case, you should definitely be following what Alexey is thinking about with an iommu_setup IOMMU API callback. I think it's shaping up to do:
x86:
- Report any IOVA range restrictions imposed by hw implementation
POWER:
- Request IOVA window size, report size and base
powerpc:
- Set domain attributes, probably report range as well.
Thanks,
Alex
Quoted 12 lines
Quoted 7 lines
The attributes are not intrinsic features of the domain. User space will need to set them. But in thinking about it a bit more I think the attributes are more properties of the domain rather than a per
map()operation characteristic. I think a separate API might be appropriate. Define a newset_domain_attrs()op in theiommu_ops. In user space, perhaps a new vfio group API--VFIO_GROUP_SET_ATTRS,VFIO_GROUP_GET_ATTRS.In that case, you should definitely be following what Alexey is thinking about with an
iommu_setupIOMMU API callback. I think it's shaping up to do:
Quoted 6 lines
x86:
- Report any IOVA range restrictions imposed by hw implementation POWER:
- Request IOVA window size, report size and base powerpc:
- Set domain attributes, probably report range as well.
One other mechanism we need as well is the ability to enable/disable a domain.
For example-- suppose a device is assigned to a VM, the device is in use when the VM is abruptly terminated. The VM terminate would shut off DMA at the IOMMU, but now
the device is in an indeterminate state. Some devices
have no simple reset bit and getting the device back into a sane state could be complicated-- something the hypervisor doesn't want to do.
So now KVM restarts the VM, vfio init happens for the device and the IOMMU for that device is re-configured,
etc, but we really can't re-enable DMA until the guest OS tells us
(via an hcall) that it is ready. The guest needs to get the
assigned device in a sane state before DMA is enabled.
Does this warrant a new domain enable/disable API, or should we make this part of the setup API we are discussing here?
Stuart
Quoted 30 lines · Stuart Yoder
Quoted 12 lines
Quoted 7 lines
The attributes are not intrinsic features of the domain. User space will need to set them. But in thinking about it a bit more I think the attributes are more properties of the domain rather than a per
map()operation characteristic. I think a separate API might be appropriate. Define a
newset_domain_attrs()op in theiommu_ops. In user space, perhaps
a new vfio group API--VFIO_GROUP_SET_ATTRS,VFIO_GROUP_GET_ATTRS.In that case, you should definitely be following what Alexey is thinking about with an
iommu_setupIOMMU API callback. I think it's shaping up to do:Quoted 6 lines
x86:
- Report any IOVA range restrictions imposed by hw implementation
POWER:
- Request IOVA window size, report size and base
powerpc:
- Set domain attributes, probably report range as well.One other mechanism we need as well is the ability to enable/disable a domain.
For example-- suppose a device is assigned to a VM, the device is in use when the VM is abruptly terminated. The VM terminate would shut off DMA at the IOMMU, but now
the device is in an indeterminate state. Some devices
have no simple reset bit and getting the device back into a sane state could be complicated-- something the hypervisor doesn't want to do.
Quoted 5 lines
So now KVM restarts the VM, vfio init happens for the device and the IOMMU for that device is re-configured,
etc, but we really can't re-enable DMA until the guest OS tells us
(via an hcall) that it is ready. The guest needs to get the
assigned device in a sane state before DMA is enabled.
Giant red flag. We need to paravirtualize the guest? Not on x86. Some devices are better for assignment than others. PCI devices are moving towards supporting standard reset mechanisms.
Quoted 3 lines
Does this warrant a new domain enable/disable API, or should we make this part of the setup API we are discussing here?
What's wrong with simply not adding any DMA mapping entries until you think your guest is ready? Isn't that effectively the same thing? Unmap ~= disable. If the IOMMU API had a mechanism to toggle the iommu domain on and off, I wouldn't be opposed to adding an ioctl to do it, but it really seems like just a shortcut vs map/unmap. Thanks,
Alex
Quoted 12 lines · Alex Williamson
Quoted 11 lines · Stuart Yoder
One other mechanism we need as well is the ability to enable/disable a domain.
For example-- suppose a device is assigned to a VM, the device is in use when the VM is abruptly terminated. The VM terminate would shut off DMA at the IOMMU, but now the device is in an indeterminate state. Some devices have no simple reset bit and getting the device back into a sane state could be complicated-- something the hypervisor doesn't want to do.
Quoted 7 lines
Quoted 5 lines
So now KVM restarts the VM, vfio init happens for the device and the IOMMU for that device is re-configured,
etc, but we really can't re-enable DMA until the guest OS tells us (via an hcall) that it is ready. The guest needs to get the assigned device in a sane state before DMA is enabled.Giant red flag. We need to paravirtualize the guest? Not on x86.
It's the reality we have to deal with, but doing this would obviously only apply to platforms that need it.
Quoted 8 lines
Some
devices are better for assignment than others. PCI devices are moving towards supporting standard reset mechanisms.Quoted 3 lines
Does this warrant a new domain enable/disable API, or should we make this part of the setup API we are discussing here?
Quoted 5 lines
What's wrong with simply not adding any DMA mapping entries until you think your guest is ready? Isn't that effectively the same thing? Unmap ~= disable. If the IOMMU API had a mechanism to toggle the iommu domain on and off, I wouldn't be opposed to adding an ioctl to do it, but it really seems like just a shortcut vs map/unmap. Thanks,
Yes, we could do something like that I guess.
Stuart
Quoted 46 lines
-----Original Message-----
From: [email protected] [mailto:[email protected]] On Behalf Of Stuart Yoder
Sent: Friday, December 02, 2011 8:11 PM
To: Alex Williamson
Cc: Alexey Kardashevskiy; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; chrisw@sous- sol.org; Yoder Stuart-B08248; [email protected]; [email protected]; [email protected]; Wood Scott-B07421; [email protected]
Subject: Re: [Qemu-devel] [RFC PATCH] vfio: VFIO Driver core frameworkQuoted 11 lines · Alex Williamson
Quoted 10 lines · Stuart Yoder
One other mechanism we need as well is the ability to enable/disable a domain.
For example-- suppose a device is assigned to a VM, the device is in use when the VM is abruptly terminated. The VM terminate would shut off DMA at the IOMMU, but now the device is in an indeterminate state. Some devices have no simple reset bit and getting the device back into a sane state could be complicated-- something the hypervisor doesn't want to do.
Quoted 7 lines
Quoted 5 lines
So now KVM restarts the VM, vfio init happens for the device and the IOMMU for that device is re-configured, etc, but we really can't re-enable DMA until the guest OS tells us (via an hcall) that it is ready. The guest needs to get the assigned device in a sane state before DMA is enabled.
Giant red flag. We need to paravirtualize the guest? Not on x86.
It's the reality we have to deal with, but doing this would obviously only apply to platforms that need it.
Quoted 7 lines
Some
devices are better for assignment than others. PCI devices are moving towards supporting standard reset mechanisms.Quoted 2 lines
Does this warrant a new domain enable/disable API, or should we make this part of the setup API we are discussing here?
Quoted 7 lines
Quoted 5 lines
What's wrong with simply not adding any DMA mapping entries until you think your guest is ready? Isn't that effectively the same thing? Unmap ~= disable. If the IOMMU API had a mechanism to toggle the iommu domain on and off, I wouldn't be opposed to adding an ioctl to do it, but it really seems like just a shortcut vs map/unmap. Thanks,
Yes, we could do something like that I guess.
How do we determine whether guest is ready or not? There can be multiple device get ready at different time.
Further if guest have given the device to it user level process or its guest. Should not there be some mechanism for a guest to enable/disable on per device or group?
Thanks
-Bharat
Quoted 1 line · On 12/02/2011 12:11 PM, Bhushan Bharat-R65777 wrote:
How do we determine whether guest is ready or not? There can be multiple device get ready at different time.
The guest makes a hypercall with a device handle -- at least that's how we do it in Topaz.
Quoted 1 line
Further if guest have given the device to it user level process or its guest. Should not there be some mechanism for a guest to enable/disable on per device or group?
Yes, the same mechanism can be used for that -- though in that case we'll also want the ability for the guest to be able to control another layer of mapping (which will get quite tricky with PAMU's limitations).
This isn't really VFIO's concern, though (unless you're talking about
the VFIO implementation in the guest).
-Scott
Quoted 14 lines
-----Original Message-----
From: Wood Scott-B07421
Sent: Friday, December 02, 2011 11:57 PM
To: Bhushan Bharat-R65777
Cc: Stuart Yoder; Alex Williamson; Alexey Kardashevskiy; [email protected]; [email protected]; [email protected]; qemu- [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; Yoder Stuart-B08248; [email protected]; [email protected]; linux- [email protected]; Wood Scott-B07421; [email protected]
Subject: Re: [Qemu-devel] [RFC PATCH] vfio: VFIO Driver core framework
Quoted 6 lines
Quoted 1 line · On 12/02/2011 12:11 PM, Bhushan Bharat-R65777 wrote:
How do we determine whether guest is ready or not? There can be
multiple device get ready at different time.
The guest makes a hypercall with a device handle -- at least that's how we do it in Topaz.
Yes, it is ok from hcall with device handle perspective.
But I could not understood how cleanly this can be handled with the idea of enabling iommu when guest is ready.
Thanks
-Bharat
Quoted 10 lines
Quoted 2 lines
Further if guest have given the device to it user level process or its
guest. Should not there be some mechanism for a guest to enable/disable on per device or group?
Yes, the same mechanism can be used for that -- though in that case we'll also want the ability for the guest to be able to control another layer of mapping (which will get quite tricky with PAMU's limitations).
This isn't really VFIO's concern, though (unless you're talking about
the VFIO implementation in the guest).
May be thinking too ahead, but will not something like this will be needed for nested virtualization?
Thanks
-Bharat
Quoted 22 lines
-----Original Message-----
From: Wood Scott-B07421
Sent: Friday, December 02, 2011 11:57 PM
To: Bhushan Bharat-R65777
Cc: Stuart Yoder; Alex Williamson; Alexey Kardashevskiy; [email protected]; [email protected]; [email protected]; qemu- [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; Yoder Stuart-B08248; [email protected]; [email protected]; linux- [email protected]; Wood Scott-B07421; [email protected]
Subject: Re: [Qemu-devel] [RFC PATCH] vfio: VFIO Driver core frameworkQuoted 1 line · On 12/02/2011 12:11 PM, Bhushan Bharat-R65777 wrote:
How do we determine whether guest is ready or not? There can be
multiple device get ready at different time.
The guest makes a hypercall with a device handle -- at least that's how we do it in Topaz.
Quoted 1 line
Further if guest have given the device to it user level process or its
Quoted 8 lines
guest. Should not there be some mechanism for a guest to enable/disable on per device or group?
Yes, the same mechanism can be used for that -- though in that case we'll also want the ability for the guest to be able to control another layer of mapping (which will get quite tricky with PAMU's limitations).
This isn't really VFIO's concern, though (unless you're talking about
the VFIO implementation in the guest).
Scott, I am not sure if there is any real use case where device needed to assigned beyond 2 level (host + immediate guest) in nested virtualization.
But if there any exists then will not it be better to virtualizes the iommu (PAMU for Freescale)?
Thanks
-Bharat
Quoted 1 line · On 12/02/2011 12:45 PM, Bhushan Bharat-R65777 wrote:
Scott, I am not sure if there is any real use case where device needed to assigned beyond 2 level (host + immediate guest) in nested virtualization.
Userspace drivers in the guest is a more likely scenario than nested virtualization, at least for us. Our hardware doesn't support nested virtualization, so it would have to be some slow emulation-based approach (worse than e500v2, since we don't have multiple PID registers).
Quoted 1 line
But if there any exists then will not it be better to virtualizes the iommu (PAMU for Freescale)?
We can't virtualize the PAMU in any sort of transparent manner. It's not flexible enough to handle arbitrary mappings. The guest will need to cooperate with the host to figure out what mappings it can do.
-Scott
Quoted 20 lines · Stuart Yoder
Quoted 18 lines · Alex Williamson
Quoted 16 lines · Stuart Yoder
One other mechanism we need as well is the ability to enable/disable a domain.
For example-- suppose a device is assigned to a VM, the device is in use when the VM is abruptly terminated. The VM terminate would shut off DMA at the IOMMU, but now
the device is in an indeterminate state. Some devices
have no simple reset bit and getting the device back into a sane state could be complicated-- something the hypervisor doesn't want to do.So now KVM restarts the VM, vfio init happens for the device and the IOMMU for that device is re-configured,
etc, but we really can't re-enable DMA until the guest OS tells us
(via an hcall) that it is ready. The guest needs to get the
assigned device in a sane state before DMA is enabled.
Quoted 4 lines
Quoted 1 line
Giant red flag. We need to paravirtualize the guest? Not on x86.
It's the reality we have to deal with, but doing this would obviously only apply to platforms that need it.
By "x86" I assume you mean "PCI" and thus a bus-master enable flag that you rely on the guest not setting until the device has been reset or otherwise quiesced from any previous activity, in the absence of function-level reset.
We don't have such a thing on our non-PCI devices.
Quoted 8 lines
Quoted 8 lines
Some
devices are better for assignment than others. PCI devices are moving towards supporting standard reset mechanisms.Quoted 3 lines
Does this warrant a new domain enable/disable API, or should we make this part of the setup API we are discussing here?
Quoted 7 lines
Quoted 5 lines
What's wrong with simply not adding any DMA mapping entries until you think your guest is ready? Isn't that effectively the same thing? Unmap ~= disable. If the IOMMU API had a mechanism to toggle the iommu domain on and off, I wouldn't be opposed to adding an ioctl to do it, but it really seems like just a shortcut vs map/unmap. Thanks,
Yes, we could do something like that I guess.
It would mean that we don't see any errors relating to impossible map requests until after the guest is running and decides to enable DMA. Depending on how PAMU table allocation is handled, it could introduce a risk of failing even later when a guest reboots and we need to temporarily disable DMA (e.g. if another vfio user consumes the same table space for another group in the meantime).
It would add latency to failovers -- some customers have somewhat tight requirements there.
-Scott
Quoted 4 lines · Alexey Kardashevskiy
Hi!
I tried (successfully) to run it on POWER and while doing that I found some issues. I'll try to explain them in separate mails.
Great!
Quoted 4 lines
IOMMU domain setup. On POWER, the linux drivers capable of DMA transfer want to know a DMA window, i.e. its start and length in the PHB address space. This comes from hardware. On X86 (correct if I am wrong), every device driver in the guest allocates memory from the same pool.
Yes, current VT-d/AMD-Vi provide independent IOVA spaces for each device.
Quoted 21 lines
On POWER, device drivers get DMA window and allocate pages
for DMA within this window. In the case of VFIO, that means that QEMU has to preallocate this DMA window before running a quest, pass it to a guest (via device tree) and then a guest tells the host what pages are taken/released by calling map/unmap callbacks ofiommu_ops. Deallocation is made in a device detach callback as I did not want to add more ioctls.
So, there are 2 patches:- new
VFIO_IOMMU_SETUPioctl introduced which allocates a DMA window via IOMMU API on POWER.
btw do we need an additional capability bit for it?KERNEL PATCH:
drivers/iommu/iommu.c +0
-0@@ -247,3 +247,12 @@ int iommu_device_group(struct device *dev, unsigned int *groupid)return -ENODEV ; }
drivers/iommu/iommu.c int iommu_device_group(struct device *dev, unsigned int *groupid) · line 258
Quoted 10 lines
drivers/iommu/iommu.c +9
-0EXPORT_SYMBOL_GPL (iommu_device_group); + +int iommu_setup (struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address) +{ +return domain->ops->setup (domain, requested_size, allocated_size, + start_address); +} +EXPORT_SYMBOL_GPL (iommu_setup);
requested_size seems redundant both here and in struct vfio_setup. We can just pre-load size/start with desired values. I assume x86 IOMMUs would ignore requested values and return start = 0 and size = hardware decoder address bits. The IOMMU API currently allows:
iommu_domain_alloc
[iommu_attach_device]
[iommu_map]
[iommu_unmap]
[iommu_detach_device]iommu_domain_free
where everything between alloc and free can be called in any order. How does setup fit into that model? For this it seems like we'd almost want to combine alloc, setup, and the first attach into a single call (ie. create a domain with this initial device and these parameters), then subsequent attaches would only allow compatible devices.
I'm a little confused though, is the window determined by hardware or is it configurable via requested_size? David had suggested that we could implement a VFIO_IOMMU_GET_INFO ioctl that returns something like:
struct vfio_iommu_info {
__u32 argsz;
__u32 flags;
__u64 iova_max; /* Maximum IOVA address */
__u64 iova_min; /* Minimum IOVA address */
__u64 pgsize_bitmap; /* Bitmap of supported page sizes */};
The thought being a TBD IOMMU API interface reports the hardware determined IOVA range and we could fudge it on x86 for now reporting 0/~0. Maybe we should replace iova_max/iova_min with iova_base/iova_size and allow the caller to request a size by setting iova_size and matching bit in the flags.
Quoted 115 lines
drivers/vfio/vfio_iommu.c +17
-0@@ -507,6 +507,23 @@ static long vfio_iommu_unl_ioctl(struct file *filep,if (!ret &©_to_user ((void __user *)arg, &dm,sizeof dm)) ret = -EFAULT ; + + }else if (cmd ==VFIO_IOMMU_SETUP ) { +struct vfio_setup setup; +size_t allocated_size =0 ; +phys_addr_t start_address =0 ; + +if (copy_from_user (&setup, (void __user *)arg,sizeof setup)) +return -EFAULT ; + +printk ("udomain %p, priv=%p\n" , iommu->domain, iommu->domain->priv); + ret =iommu_setup (iommu->domain, setup.requested_size, + &allocated_size, &start_address); + setup.allocated_size = allocated_size; + setup.start_address = start_address; + +if (!ret &©_to_user ((void __user *)arg, &setup,sizeof setup)) + ret = -EFAULT ; }return ret; }include/linux/iommu.h +7
-0@@ -45,6 +45,7 @@ struct iommu_domain {#define IOMMU_CAP_CACHE_COHERENCY 0x1#define IOMMU_CAP_INTR_REMAP 0x2/* isolates device intrs */ +#define IOMMU_CAP_SETUP_REQUIRED 0x3/* requires setup to be called */ #ifdef CONFIG_IOMMU_API @@ -62,6 +63,9 @@ struct iommu_ops {int (*domain_has_cap)(struct iommu_domain *domain,unsigned long cap);int (*device_group)(struct device *dev,unsigned int *groupid); +int (*setup)(struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address); };extern int bus_set_iommu (struct bus_type *bus,struct iommu_ops *ops);@@ -80,6 +84,9 @@ extern phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, unsigned long iova);extern int iommu_domain_has_cap (struct iommu_domain *domain,unsigned long cap); +extern int iommu_setup (struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address);extern void iommu_set_fault_handler (struct iommu_domain *domain,iommu_fault_handler_t handler);extern int iommu_device_group (struct device *dev,unsigned int *groupid);include/linux/vfio.h +10
-0@@ -26,6 +26,7 @@* Author: Michael S. Tsirkin <[email protected]> */ #include <linux/types.h> +#include <linux/ioctl.h> #ifndef VFIO_H #define VFIO_H @@ -172,4 +173,13 @@ enum {VFIO_PCI_NUM_IRQS }; +/* Setup domain */ +#define VFIO_IOMMU_SETUP _IOWR(';', 150, struct vfio_setup) + +struct vfio_setup { +__u64 requested_size; +__u64 allocated_size; +__u64 start_address; +}; +#endif /* VFIO_H */ === end ===
QEMU PATCH:
hw/linux-vfio.h +9
-0@@ -172,4 +172,13 @@ enum {VFIO_PCI_NUM_IRQS }; +/* Setup domain */ +#define VFIO_IOMMU_SETUP _IOWR(';', 150, struct vfio_setup) + +struct vfio_setup { +__u64 requested_size; +__u64 allocated_size; +__u64 start_address; +}; +#endif /* VFIO_H */ hw/vfio_pci.c +0
-0
hw/vfio_pci.c static int vfio_initfn(struct PCIDevice *pdev) · line 1506
Quoted 4 lines
hw/vfio_pci.c +1
-0@@ -1501,6 +1503,17 @@ static int vfio_initfn(struct PCIDevice *pdev)if (vfio_map_resources (vdev)) goto out_disable_msi; +struct vfio_setup setup = {1 <<26 ,0 ,0 };
How will qemu decide how much to ask for?
Quoted 49 lines
hw/vfio_pci.c +10
-0+if ((ret =ioctl (vdev->group->iommu->fd,VFIO_IOMMU_SETUP , &setup))) { +return ret; + } +printf ("SETUP: requested %lluMB, allocated %lluMB at %llx\n" , + (unsigned long long )setup.requested_size, + (unsigned long long )setup.allocated_size, + (unsigned long long )setup.start_address); + vdev->start_address = setup.start_address; + vdev->window_size = setup.allocated_size; +if (vfio_enable_intx (vdev)) goto out_unmap_resources;hw/vfio_pci.h +4
-0@@ -79,6 +79,10 @@ typedef struct VFIODevice {bool msix;uint8_t msix_bar;uint16_t msix_entries; +#ifdef TARGET_PPC +uint64_t start_address; +uint32_t window_size; +#endif } VFIODevice; typedef struct VFIOGroup {=== end ===
- changed
__vfio_close_iommufunction to do unmapall first and detach devices then as actual deallocation happens on device detach callback of IOMMU ops.drivers/vfio/vfio_main.c +1
-0@@ -28,6 +28,7 @@#include <linux/uaccess.h> #include <linux/vfio.h> #include <linux/wait.h> +#include <linux/pci.h> #include "vfio_private.h"
drivers/vfio/vfio_main.c static void __vfio_close_iommu(struct vfio_iommu *iommu) · line 252
Quoted 10 lines
drivers/vfio/vfio_main.c +7
-0@@ -242,6 +243,13 @@ static void __vfio_close_iommu(struct vfio_iommu *iommu)if (!iommu->domain)return ; +/* +* On POWER, device detaching (which is done by __vfio_iommu_detach_group) +* should happen after all pages unmapped because +* the only way to do actual iommu_unmap_page a device detach callback +*/ +vfio_iommu_unmapall (iommu); +
The unmapall/detach vs detach/unmapall shouldn't matter for x86. Though I wonder if we should be proactively resetting devices before either to avoid spurious IOVA faults.
drivers/vfio/vfio_main.c static void __vfio_close_iommu(struct vfio_iommu *iommu) · line 263
Quoted 12 lines
drivers/vfio/vfio_main.c +1
-1list_for_each (pos, &iommu->group_list) {struct vfio_group *group; group = list_entry(pos, struct vfio_group, iommu_next);@@ -249,7 +257,7 @@ static void __vfio_close_iommu(struct vfio_iommu *iommu)__vfio_iommu_detach_group (iommu, group); } -vfio_iommu_unmapall (iommu); +/* vfio_iommu_unmapall(iommu); */ iommu_domain_free (iommu->domain); iommu->domain =NULL ;
Thanks,
Alex
Hi!
Quoted 60 lines · Alex Williamson
Quoted 4 lines · Alexey Kardashevskiy
Hi!
I tried (successfully) to run it on POWER and while doing that I found some issues. I'll try to explain them in separate mails.
Great!
Quoted 4 lines
IOMMU domain setup. On POWER, the linux drivers capable of DMA transfer want to know a DMA window, i.e. its start and length in the PHB address space. This comes from hardware. On X86 (correct if I am wrong), every device driver in the guest allocates memory from the same pool.
Yes, current VT-d/AMD-Vi provide independent IOVA spaces for each device.
Quoted 21 lines
On POWER, device drivers get DMA window and allocate pages
for DMA within this window. In the case of VFIO, that means that QEMU has to preallocate this DMA window before running a quest, pass it to a guest (via device tree) and then a guest tells the host what pages are taken/released by calling map/unmap callbacks ofiommu_ops. Deallocation is made in a device detach callback as I did not want to add more ioctls.
So, there are 2 patches:- new
VFIO_IOMMU_SETUPioctl introduced which allocates a DMA window via IOMMU API on POWER.
btw do we need an additional capability bit for it?KERNEL PATCH:
drivers/iommu/iommu.c +0
-0@@ -247,3 +247,12 @@ int iommu_device_group(struct device *dev, unsigned int *groupid)return -ENODEV ; }drivers/iommu/iommu.c int iommu_device_group(struct device *dev, unsigned int *groupid) · line 258
Quoted 10 lines
drivers/iommu/iommu.c +9
-0EXPORT_SYMBOL_GPL (iommu_device_group); + +int iommu_setup (struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address) +{ +return domain->ops->setup (domain, requested_size, allocated_size, + start_address); +} +EXPORT_SYMBOL_GPL (iommu_setup);
requested_sizeseems redundant both here and in structvfio_setup. We can just pre-load size/start with desired values. I assume x86 IOMMUs would ignore requested values and return start = 0 and size = hardware decoder address bits. The IOMMU API currently allows:
iommu_domain_alloc
[iommu_attach_device]
[iommu_map]
[iommu_unmap]
[iommu_detach_device]iommu_domain_free
Quoted 2 lines
where everything between alloc and free can be called in any order. How does setup fit into that model?
This is why I posted a QEMU patch :)
Quoted 4 lines
For this it seems like we'd almost want
to combine alloc, setup, and the first attach into a single call (ie. create a domain with this initial device and these parameters), then subsequent attaches would only allow compatible devices.
Not exactly. This setup is more likely to get combined with domain alloc only. On POWER, we have iommu_table per DMA window which can be or can be not shared between devices. At the moment there is one window per PCIe _device_ (so multiple functions of multiport network adapter share one DMA window) and one window for all the devices behind PCIe-to-PCI bridge. It is more or less so.
Quoted 2 lines
I'm a little confused though, is the window determined by hardware or is it configurable via
requested_size?
The window parameters are calculated by software and then written to hardware so hardware does filtering and prevents bad devices from memory corruption.
Quoted 9 lines
David had suggested that we could
implement aVFIO_IOMMU_GET_INFOioctl that returns something like:struct
vfio_iommu_info{__u32 argsz; __u32 flags; __u64 iova_max; /* Maximum IOVA address */ __u64 iova_min; /* Minimum IOVA address */ __u64 pgsize_bitmap; /* Bitmap of supported page sizes */
Quoted 7 lines
};
The thought being a TBD IOMMU API interface reports the hardware determined IOVA range and we could fudge it on x86 for now reporting 0/~0. Maybe we should replace iova_max/iova_min with iova_base/iova_size and allow the caller to request a size by setting
iova_sizeand matching bit in the flags.
No, we need some sort of SET_INFO, not GET as we want QEMU to decide on a DMA window size.
Or simply add these parameters to domain allocation callback.
Quoted 118 lines
Quoted 118 lines
drivers/vfio/vfio_iommu.c +17
-0@@ -507,6 +507,23 @@ static long vfio_iommu_unl_ioctl(struct file *filep,if (!ret &©_to_user ((void __user *)arg, &dm,sizeof dm)) ret = -EFAULT ; + + }else if (cmd ==VFIO_IOMMU_SETUP ) { +struct vfio_setup setup; +size_t allocated_size =0 ; +phys_addr_t start_address =0 ; + +if (copy_from_user (&setup, (void __user *)arg,sizeof setup)) +return -EFAULT ; + +printk ("udomain %p, priv=%p\n" , iommu->domain, iommu->domain->priv); + ret =iommu_setup (iommu->domain, setup.requested_size, + &allocated_size, &start_address); + setup.allocated_size = allocated_size; + setup.start_address = start_address; + +if (!ret &©_to_user ((void __user *)arg, &setup,sizeof setup)) + ret = -EFAULT ; }return ret; }include/linux/iommu.h +7
-0@@ -45,6 +45,7 @@ struct iommu_domain {#define IOMMU_CAP_CACHE_COHERENCY 0x1#define IOMMU_CAP_INTR_REMAP 0x2/* isolates device intrs */ +#define IOMMU_CAP_SETUP_REQUIRED 0x3/* requires setup to be called */ #ifdef CONFIG_IOMMU_API @@ -62,6 +63,9 @@ struct iommu_ops {int (*domain_has_cap)(struct iommu_domain *domain,unsigned long cap);int (*device_group)(struct device *dev,unsigned int *groupid); +int (*setup)(struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address); };extern int bus_set_iommu (struct bus_type *bus,struct iommu_ops *ops);@@ -80,6 +84,9 @@ extern phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, unsigned long iova);extern int iommu_domain_has_cap (struct iommu_domain *domain,unsigned long cap); +extern int iommu_setup (struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address);extern void iommu_set_fault_handler (struct iommu_domain *domain,iommu_fault_handler_t handler);extern int iommu_device_group (struct device *dev,unsigned int *groupid);include/linux/vfio.h +10
-0@@ -26,6 +26,7 @@* Author: Michael S. Tsirkin <[email protected]> */ #include <linux/types.h> +#include <linux/ioctl.h> #ifndef VFIO_H #define VFIO_H @@ -172,4 +173,13 @@ enum {VFIO_PCI_NUM_IRQS }; +/* Setup domain */ +#define VFIO_IOMMU_SETUP _IOWR(';', 150, struct vfio_setup) + +struct vfio_setup { +__u64 requested_size; +__u64 allocated_size; +__u64 start_address; +}; +#endif /* VFIO_H */ === end ===
QEMU PATCH:
hw/linux-vfio.h +9
-0@@ -172,4 +172,13 @@ enum {VFIO_PCI_NUM_IRQS }; +/* Setup domain */ +#define VFIO_IOMMU_SETUP _IOWR(';', 150, struct vfio_setup) + +struct vfio_setup { +__u64 requested_size; +__u64 allocated_size; +__u64 start_address; +}; +#endif /* VFIO_H */ hw/vfio_pci.c +0
-0@@ -1501,6 +1503,17 @@ static int vfio_initfn(struct PCIDevice *pdev)if (vfio_map_resources (vdev)) goto out_disable_msi;
Quoted 3 lines
hw/vfio_pci.c static int vfio_initfn(struct PCIDevice *pdev) · line 1506
Quoted 1 line
hw/vfio_pci.c +1
-0+struct vfio_setup setup = {1 <<26 ,0 ,0 };How will qemu decide how much to ask for?
It is done by some heuristic. Like "usb controller needs 16mb" and "10Gb card needs more than 100mbit". I'd think that POWER-specific code in QEMU would decide. As POWER supports multiple PCI domains, it can afford spending addresses :)
Quoted 52 lines
Quoted 52 lines
hw/vfio_pci.c +10
-0+if ((ret =ioctl (vdev->group->iommu->fd,VFIO_IOMMU_SETUP , &setup))) { +return ret; + } +printf ("SETUP: requested %lluMB, allocated %lluMB at %llx\n" , + (unsigned long long )setup.requested_size, + (unsigned long long )setup.allocated_size, + (unsigned long long )setup.start_address); + vdev->start_address = setup.start_address; + vdev->window_size = setup.allocated_size; +if (vfio_enable_intx (vdev)) goto out_unmap_resources;hw/vfio_pci.h +4
-0@@ -79,6 +79,10 @@ typedef struct VFIODevice {bool msix;uint8_t msix_bar;uint16_t msix_entries; +#ifdef TARGET_PPC +uint64_t start_address; +uint32_t window_size; +#endif } VFIODevice; typedef struct VFIOGroup {=== end ===
- changed
__vfio_close_iommufunction to do unmapall first and detach devices then as actual deallocation happens on device detach callback of IOMMU ops.drivers/vfio/vfio_main.c +1
-0@@ -28,6 +28,7 @@#include <linux/uaccess.h> #include <linux/vfio.h> #include <linux/wait.h> +#include <linux/pci.h> #include "vfio_private.h" @@ -242,6 +243,13 @@ static void __vfio_close_iommu(struct vfio_iommu *iommu)if (!iommu->domain)return ;
Quoted 11 lines
drivers/vfio/vfio_main.c static void __vfio_close_iommu(struct vfio_iommu *iommu) · line 252
Quoted 7 lines
drivers/vfio/vfio_main.c +7
-0+/* +* On POWER, device detaching (which is done by __vfio_iommu_detach_group) +* should happen after all pages unmapped because +* the only way to do actual iommu_unmap_page a device detach callback +*/ +vfio_iommu_unmapall (iommu); +The unmapall/detach vs detach/unmapall shouldn't matter for x86. Though I wonder if we should be proactively resetting devices before either to avoid spurious IOVA faults.
Then we need some to "shutdown" a device.
I am not sure about x86, but on POWER a host allocates DMA window (SETUP does iommu_alloc so the _whole_ DMA window gets allocated), and then a guest allocates pages within this window itself but it only updates the host's IOMMU table with pairs of addresses, a host does not do any no actual map/unmap while guest is running.
Oooor, we could release the whole window in the domain close callback of iommu_ops...
Quoted 16 lines
drivers/vfio/vfio_main.c static void __vfio_close_iommu(struct vfio_iommu *iommu) · line 263
Quoted 12 lines
drivers/vfio/vfio_main.c +1
-1list_for_each (pos, &iommu->group_list) {struct vfio_group *group; group = list_entry(pos, struct vfio_group, iommu_next);@@ -249,7 +257,7 @@ static void __vfio_close_iommu(struct vfio_iommu *iommu)__vfio_iommu_detach_group (iommu, group); } -vfio_iommu_unmapall (iommu); +/* vfio_iommu_unmapall(iommu); */ iommu_domain_free (iommu->domain); iommu->domain =NULL ;Thanks,
Alex
Signature · 5 lines
Alexey Kardashevskiy IBM OzLabs, LTC Team e-mail: [email protected] notes: Alexey Kardashevskiy/Australia/IBM
Quoted 63 lines · Alexey Kardashevskiy
Hi!
Quoted 60 lines · Alex Williamson
Quoted 4 lines · Alexey Kardashevskiy
Hi!
I tried (successfully) to run it on POWER and while doing that I found some issues. I'll try to explain them in separate mails.
Great!
Quoted 4 lines
IOMMU domain setup. On POWER, the linux drivers capable of DMA transfer want to know a DMA window, i.e. its start and length in the PHB address space. This comes from hardware. On X86 (correct if I am wrong), every device driver in the guest allocates memory from the same pool.
Yes, current VT-d/AMD-Vi provide independent IOVA spaces for each device.
Quoted 21 lines
On POWER, device drivers get DMA window and allocate pages
for DMA within this window. In the case of VFIO, that means that QEMU has to preallocate this DMA window before running a quest, pass it to a guest (via device tree) and then a guest tells the host what pages are taken/released by calling map/unmap callbacks ofiommu_ops. Deallocation is made in a device detach callback as I did not want to add more ioctls.
So, there are 2 patches:- new
VFIO_IOMMU_SETUPioctl introduced which allocates a DMA window via IOMMU API on POWER.
btw do we need an additional capability bit for it?KERNEL PATCH:
drivers/iommu/iommu.c +0
-0@@ -247,3 +247,12 @@ int iommu_device_group(struct device *dev, unsigned int *groupid)return -ENODEV ; }drivers/iommu/iommu.c int iommu_device_group(struct device *dev, unsigned int *groupid) · line 258
Quoted 10 lines
drivers/iommu/iommu.c +9
-0EXPORT_SYMBOL_GPL (iommu_device_group); + +int iommu_setup (struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address) +{ +return domain->ops->setup (domain, requested_size, allocated_size, + start_address); +} +EXPORT_SYMBOL_GPL (iommu_setup);
requested_sizeseems redundant both here and in structvfio_setup. We can just pre-load size/start with desired values. I assume x86 IOMMUs would ignore requested values and return start = 0 and size = hardware decoder address bits. The IOMMU API currently allows:
iommu_domain_alloc
[iommu_attach_device]
[iommu_map]
[iommu_unmap]
[iommu_detach_device]iommu_domain_free
Quoted 4 lines
Quoted 2 lines
where everything between alloc and free can be called in any order. How does setup fit into that model?
This is why I posted a QEMU patch :)
Right, but qemu/vfio is by no means the defacto standard of how one must use the IOMMU API. KVM currently orders the map vs attach differently. When is it valid to call setup when factoring in hot attached/detached devices?
Quoted 7 lines
Quoted 4 lines
For this it seems like we'd almost want
to combine alloc, setup, and the first attach into a single call (ie. create a domain with this initial device and these parameters), then subsequent attaches would only allow compatible devices.Not exactly. This setup is more likely to get combined with domain alloc only.
At domain_alloc we don't have any association to actual hardware other than a bus_type, how would you know which iommu is being setup?
Quoted 32 lines
On POWER, we have
iommu_tableper DMA window which can be or can be not shared between devices. At the moment there is one window per PCIe _device_ (so multiple functions of multiport network adapter share one DMA window) and one window for all the devices behind PCIe-to-PCI bridge. It is more or less so.Quoted 2 lines
I'm a little confused though, is the window determined by hardware or is it configurable via
requested_size?The window parameters are calculated by software and then written to hardware so hardware does filtering and prevents bad devices from memory corruption.
Quoted 9 lines
David had suggested that we could
implement aVFIO_IOMMU_GET_INFOioctl that returns something like:struct
vfio_iommu_info{__u32 argsz; __u32 flags; __u64 iova_max; /* Maximum IOVA address */ __u64 iova_min; /* Minimum IOVA address */ __u64 pgsize_bitmap; /* Bitmap of supported page sizes */Quoted 7 lines
};
The thought being a TBD IOMMU API interface reports the hardware determined IOVA range and we could fudge it on x86 for now reporting 0/~0. Maybe we should replace iova_max/iova_min with iova_base/iova_size and allow the caller to request a size by setting
iova_sizeand matching bit in the flags.
Quoted 2 lines
No, we need some sort of
SET_INFO, not GET as we want QEMU to decide on a DMA window size.
Right, GET_INFO is no longer the right name if we're really passing in requests. Maybe it becomes VFIO_IOMMU_SETUP as you suggest and it really is a bidirectional ioctl.
Quoted 1 line
Or simply add these parameters to domain allocation callback.
Except alloc only specifies a bus_type, not a specific iommu, which is why we might need to think about combining {alloc, attach, setup}...
struct iommu_domain *iommu_create_domain(int nr_devs,
struct device **devs, dma_addr_t *iova_start, size_t *iova_size)
But then we have trouble when vfio needs to prevent device access until the iommu domain is setup which means that our only opportunity to specify iommu parameters might be to add a struct to GROUP_GET_IOMMU_FD, but without device access, how does qemu know how large of a window to request?
BTW, domain_has_cap() might be a way to advertise if the domain supports/requires a setup callback.
Quoted 194 lines
Quoted 118 lines
Quoted 118 lines
drivers/vfio/vfio_iommu.c +17
-0@@ -507,6 +507,23 @@ static long vfio_iommu_unl_ioctl(struct file *filep,if (!ret &©_to_user ((void __user *)arg, &dm,sizeof dm)) ret = -EFAULT ; + + }else if (cmd ==VFIO_IOMMU_SETUP ) { +struct vfio_setup setup; +size_t allocated_size =0 ; +phys_addr_t start_address =0 ; + +if (copy_from_user (&setup, (void __user *)arg,sizeof setup)) +return -EFAULT ; + +printk ("udomain %p, priv=%p\n" , iommu->domain, iommu->domain->priv); + ret =iommu_setup (iommu->domain, setup.requested_size, + &allocated_size, &start_address); + setup.allocated_size = allocated_size; + setup.start_address = start_address; + +if (!ret &©_to_user ((void __user *)arg, &setup,sizeof setup)) + ret = -EFAULT ; }return ret; }include/linux/iommu.h +7
-0@@ -45,6 +45,7 @@ struct iommu_domain {#define IOMMU_CAP_CACHE_COHERENCY 0x1#define IOMMU_CAP_INTR_REMAP 0x2/* isolates device intrs */ +#define IOMMU_CAP_SETUP_REQUIRED 0x3/* requires setup to be called */ #ifdef CONFIG_IOMMU_API @@ -62,6 +63,9 @@ struct iommu_ops {int (*domain_has_cap)(struct iommu_domain *domain,unsigned long cap);int (*device_group)(struct device *dev,unsigned int *groupid); +int (*setup)(struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address); };extern int bus_set_iommu (struct bus_type *bus,struct iommu_ops *ops);@@ -80,6 +84,9 @@ extern phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, unsigned long iova);extern int iommu_domain_has_cap (struct iommu_domain *domain,unsigned long cap); +extern int iommu_setup (struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address);extern void iommu_set_fault_handler (struct iommu_domain *domain,iommu_fault_handler_t handler);extern int iommu_device_group (struct device *dev,unsigned int *groupid);include/linux/vfio.h +10
-0@@ -26,6 +26,7 @@* Author: Michael S. Tsirkin <[email protected]> */ #include <linux/types.h> +#include <linux/ioctl.h> #ifndef VFIO_H #define VFIO_H @@ -172,4 +173,13 @@ enum {VFIO_PCI_NUM_IRQS }; +/* Setup domain */ +#define VFIO_IOMMU_SETUP _IOWR(';', 150, struct vfio_setup) + +struct vfio_setup { +__u64 requested_size; +__u64 allocated_size; +__u64 start_address; +}; +#endif /* VFIO_H */ === end ===
QEMU PATCH:
hw/linux-vfio.h +9
-0@@ -172,4 +172,13 @@ enum {VFIO_PCI_NUM_IRQS }; +/* Setup domain */ +#define VFIO_IOMMU_SETUP _IOWR(';', 150, struct vfio_setup) + +struct vfio_setup { +__u64 requested_size; +__u64 allocated_size; +__u64 start_address; +}; +#endif /* VFIO_H */ hw/vfio_pci.c +0
-0@@ -1501,6 +1503,17 @@ static int vfio_initfn(struct PCIDevice *pdev)if (vfio_map_resources (vdev)) goto out_disable_msi;Quoted 3 lines
hw/vfio_pci.c static int vfio_initfn(struct PCIDevice *pdev) · line 1506
Quoted 1 line
hw/vfio_pci.c +1
-0+struct vfio_setup setup = {1 <<26 ,0 ,0 };How will qemu decide how much to ask for?
It is done by some heuristic. Like "usb controller needs 16mb" and "10Gb card needs more than 100mbit". I'd think that POWER-specific code in QEMU would decide. As POWER supports multiple PCI domains, it can afford spending addresses :)
Quoted 52 lines
Quoted 52 lines
hw/vfio_pci.c +10
-0+if ((ret =ioctl (vdev->group->iommu->fd,VFIO_IOMMU_SETUP , &setup))) { +return ret; + } +printf ("SETUP: requested %lluMB, allocated %lluMB at %llx\n" , + (unsigned long long )setup.requested_size, + (unsigned long long )setup.allocated_size, + (unsigned long long )setup.start_address); + vdev->start_address = setup.start_address; + vdev->window_size = setup.allocated_size; +if (vfio_enable_intx (vdev)) goto out_unmap_resources;hw/vfio_pci.h +4
-0@@ -79,6 +79,10 @@ typedef struct VFIODevice {bool msix;uint8_t msix_bar;uint16_t msix_entries; +#ifdef TARGET_PPC +uint64_t start_address; +uint32_t window_size; +#endif } VFIODevice; typedef struct VFIOGroup {=== end ===
- changed
__vfio_close_iommufunction to do unmapall first and detach devices then as actual deallocation happens on device detach callback of IOMMU ops.drivers/vfio/vfio_main.c +1
-0@@ -28,6 +28,7 @@#include <linux/uaccess.h> #include <linux/vfio.h> #include <linux/wait.h> +#include <linux/pci.h> #include "vfio_private.h" @@ -242,6 +243,13 @@ static void __vfio_close_iommu(struct vfio_iommu *iommu)if (!iommu->domain)return ;Quoted 11 lines
drivers/vfio/vfio_main.c static void __vfio_close_iommu(struct vfio_iommu *iommu) · line 252
Quoted 7 lines
drivers/vfio/vfio_main.c +7
-0+/* +* On POWER, device detaching (which is done by __vfio_iommu_detach_group) +* should happen after all pages unmapped because +* the only way to do actual iommu_unmap_page a device detach callback +*/ +vfio_iommu_unmapall (iommu); +The unmapall/detach vs detach/unmapall shouldn't matter for x86. Though I wonder if we should be proactively resetting devices before either to avoid spurious IOVA faults.
Quoted 1 line
Then we need some to "shutdown" a device.
VFIO Devices expose the DEVICE_RESET ioctl, which could be exposed to the group via vfio_device_ops. pci_reset_function() does a pretty good job of quiescing devices when it works. I've also been wondering if we need a VFIO_GROUP_RESET which can call reset on each device, but also allow things like PCI secondary bus resets when all the devices behind a bridge are in a group. For now I've deferred it as a possible future extension.
Quoted 4 lines
I am not sure about x86, but on POWER a host allocates DMA window (SETUP does
iommu_allocso the _whole_ DMA window gets allocated), and then a guest allocates pages within this window itself but it only updates the host's IOMMU table with pairs of addresses, a host does not do any no actual map/unmap while guest is running.
What's the difference between "updates the host's IOMMU table with pairs of addresses" and map/unmap? Your DMA window is static, but what each IOVA within the window points to is not, correct? I would have assumed you do unmap/map to update each of those (at least David seemed to care about map/unmap latency).
x86 maps the entire guest, so the only runtime map/unmaps would be when the memory map changes. Typically this only happens for MMIO regions and odd chipset specific regions that switch between being memory backed or ROM backed (which we really don't care about for DMA), and theoretically for future memory hotplug. At some point we're supposed to have devices and IOMMUs that support IO page faults, so a device can request an IOVA and we'd probably register a page fault handler for the domain to dynamically pin and map pages.
Quoted 1 line
Oooor, we could release the whole window in the domain close callback of
iommu_ops...
AIUI, the iommu driver will destroy all the mappings in a domain when we call iommu_domain_free, but the real need for unmapall is to unpin all the memory. David was suggesting maybe the pinning should happen in the iommu driver, which could then handle unpinning on release. I kinda doubt iommu drivers want to get into the business of pinning memory though. I'd actually like VFIO to get out of this business as well and was thinking about requiring mapped pages to be mlocked by the user, but it appears we have no way to later prevent or detect that the user munlocked the pages and might then have access to random host memory. Thanks,
Alex
Quoted 82 lines · Alex Williamson
Quoted 63 lines · Alexey Kardashevskiy
Hi!
Quoted 60 lines · Alex Williamson
Quoted 4 lines · Alexey Kardashevskiy
Hi!
I tried (successfully) to run it on POWER and while doing that I found some issues. I'll try to explain them in separate mails.
Great!
Quoted 4 lines
IOMMU domain setup. On POWER, the linux drivers capable of DMA transfer want to know a DMA window, i.e. its start and length in the PHB address space. This comes from hardware. On X86 (correct if I am wrong), every device driver in the guest allocates memory from the same pool.
Yes, current VT-d/AMD-Vi provide independent IOVA spaces for each device.
Quoted 21 lines
On POWER, device drivers get DMA window and allocate pages
for DMA within this window. In the case of VFIO, that means that QEMU has to preallocate this DMA window before running a quest, pass it to a guest (via device tree) and then a guest tells the host what pages are taken/released by calling map/unmap callbacks ofiommu_ops. Deallocation is made in a device detach callback as I did not want to add more ioctls.
So, there are 2 patches:- new
VFIO_IOMMU_SETUPioctl introduced which allocates a DMA window via IOMMU API on POWER.
btw do we need an additional capability bit for it?KERNEL PATCH:
drivers/iommu/iommu.c +0
-0@@ -247,3 +247,12 @@ int iommu_device_group(struct device *dev, unsigned int *groupid)return -ENODEV ; }drivers/iommu/iommu.c int iommu_device_group(struct device *dev, unsigned int *groupid) · line 258
Quoted 10 lines
drivers/iommu/iommu.c +9
-0EXPORT_SYMBOL_GPL (iommu_device_group); + +int iommu_setup (struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address) +{ +return domain->ops->setup (domain, requested_size, allocated_size, + start_address); +} +EXPORT_SYMBOL_GPL (iommu_setup);
requested_sizeseems redundant both here and in structvfio_setup. We can just pre-load size/start with desired values. I assume x86 IOMMUs would ignore requested values and return start = 0 and size = hardware decoder address bits. The IOMMU API currently allows:
iommu_domain_alloc
[iommu_attach_device]
[iommu_map]
[iommu_unmap]
[iommu_detach_device]iommu_domain_freeQuoted 4 lines
Quoted 2 lines
where everything between alloc and free can be called in any order. How does setup fit into that model?
This is why I posted a QEMU patch :)
Right, but qemu/vfio is by no means the defacto standard of how one must use the IOMMU API. KVM currently orders the map vs attach differently. When is it valid to call setup when factoring in hot attached/detached devices?
Quoted 6 lines
Quoted 4 lines
For this it seems like we'd almost want
to combine alloc, setup, and the first attach into a single call (ie. create a domain with this initial device and these parameters), then subsequent attaches would only allow compatible devices.
Quoted 4 lines
Quoted 1 line
Not exactly. This setup is more likely to get combined with domain alloc only.
At
domain_allocwe don't have any association to actual hardware other than abus_type, how would you know which iommu is being setup?
Yes. This is exact problem. We do have preallocated PEs (aka groups) on POWER but cannot use this information during setup until the first device is attached.
Generally speaking, we should not be adding devices to an IOMMU domain, we should be adding groups instead as it is the smallest entity which IOMMU can handle. At least in API, it is better to have as simple as the idea it is implementing.
For example, we could implement a tool to put devices into a group (at the moment on POWER it would check that a domain has no more than just a single group in it). We could pass this group ID to QEMU instead of passing "-device vfio-pci ..." (as we still must pass _all_ devices of a group to QEMU).
Sure, we'll have change VFIO to tell QEMU what devices are included in what group, quite easy to do.
It is a tree: domain -> group -> device. Lets reflect it in the API.
Quoted 32 lines
Quoted 32 lines
On POWER, we have
iommu_tableper DMA window which can be or can be not shared between devices. At the moment there is one window per PCIe _device_ (so multiple functions of multiport network adapter share one DMA window) and one window for all the devices behind PCIe-to-PCI bridge. It is more or less so.Quoted 2 lines
I'm a little confused though, is the window determined by hardware or is it configurable via
requested_size?The window parameters are calculated by software and then written to hardware so hardware does filtering and prevents bad devices from memory corruption.
Quoted 16 lines
David had suggested that we could
implement aVFIO_IOMMU_GET_INFOioctl that returns something like:struct
vfio_iommu_info{__u32 argsz; __u32 flags; __u64 iova_max; /* Maximum IOVA address */ __u64 iova_min; /* Minimum IOVA address */ __u64 pgsize_bitmap; /* Bitmap of supported page sizes */};
The thought being a TBD IOMMU API interface reports the hardware determined IOVA range and we could fudge it on x86 for now reporting 0/~0. Maybe we should replace iova_max/iova_min with iova_base/iova_size and allow the caller to request a size by setting
iova_sizeand matching bit in the flags.
Quoted 6 lines
Quoted 2 lines
No, we need some sort of
SET_INFO, not GET as we want QEMU to decide on a DMA window size.Right,
GET_INFOis no longer the right name if we're really passing in requests. Maybe it becomesVFIO_IOMMU_SETUPas you suggest and it really is a bidirectional ioctl.
Actually these are a group properties, not of device or iommu, at least now for POWER it is so. And they are predefined for every group. We would need "GET_INFO" for them if we had a group-based API but we do not have it.
Quoted 10 lines
Quoted 1 line
Or simply add these parameters to domain allocation callback.
Except alloc only specifies a
bus_type, not a specific iommu, which is why we might need to think about combining {alloc, attach, setup}...struct
iommu_domain*iommu_create_domain(intnr_devs,
struct device **devs,dma_addr_t*iova_start,size_t*iova_size)
Quoted 5 lines
But then we have trouble when vfio needs to prevent device access until the iommu domain is setup which means that our only opportunity to specify iommu parameters might be to add a struct to
GROUP_GET_IOMMU_FD, but without device access, how does qemu know how large of a window to request?
Somehow. Everyone gets 64mb in the simplest case or somehow more tricky.
There is a difference. On x86 you really create a new domain. On POWER (again, currently) we create a domain which corresponds to an existing group, one group per domain, domains cannot consist of 2 or more groups (will be fixed in hardware later though).
Quoted 200 lines
BTW,
domain_has_cap()might be a way to advertise if the domain supports/requires a setup callback.Quoted 194 lines
Quoted 118 lines
Quoted 118 lines
drivers/vfio/vfio_iommu.c +17
-0@@ -507,6 +507,23 @@ static long vfio_iommu_unl_ioctl(struct file *filep,if (!ret &©_to_user ((void __user *)arg, &dm,sizeof dm)) ret = -EFAULT ; + + }else if (cmd ==VFIO_IOMMU_SETUP ) { +struct vfio_setup setup; +size_t allocated_size =0 ; +phys_addr_t start_address =0 ; + +if (copy_from_user (&setup, (void __user *)arg,sizeof setup)) +return -EFAULT ; + +printk ("udomain %p, priv=%p\n" , iommu->domain, iommu->domain->priv); + ret =iommu_setup (iommu->domain, setup.requested_size, + &allocated_size, &start_address); + setup.allocated_size = allocated_size; + setup.start_address = start_address; + +if (!ret &©_to_user ((void __user *)arg, &setup,sizeof setup)) + ret = -EFAULT ; }return ret; }include/linux/iommu.h +7
-0@@ -45,6 +45,7 @@ struct iommu_domain {#define IOMMU_CAP_CACHE_COHERENCY 0x1#define IOMMU_CAP_INTR_REMAP 0x2/* isolates device intrs */ +#define IOMMU_CAP_SETUP_REQUIRED 0x3/* requires setup to be called */ #ifdef CONFIG_IOMMU_API @@ -62,6 +63,9 @@ struct iommu_ops {int (*domain_has_cap)(struct iommu_domain *domain,unsigned long cap);int (*device_group)(struct device *dev,unsigned int *groupid); +int (*setup)(struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address); };extern int bus_set_iommu (struct bus_type *bus,struct iommu_ops *ops);@@ -80,6 +84,9 @@ extern phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, unsigned long iova);extern int iommu_domain_has_cap (struct iommu_domain *domain,unsigned long cap); +extern int iommu_setup (struct iommu_domain *domain, +size_t requested_size,size_t *allocated_size, +phys_addr_t *start_address);extern void iommu_set_fault_handler (struct iommu_domain *domain,iommu_fault_handler_t handler);extern int iommu_device_group (struct device *dev,unsigned int *groupid);include/linux/vfio.h +10
-0@@ -26,6 +26,7 @@* Author: Michael S. Tsirkin <[email protected]> */ #include <linux/types.h> +#include <linux/ioctl.h> #ifndef VFIO_H #define VFIO_H @@ -172,4 +173,13 @@ enum {VFIO_PCI_NUM_IRQS }; +/* Setup domain */ +#define VFIO_IOMMU_SETUP _IOWR(';', 150, struct vfio_setup) + +struct vfio_setup { +__u64 requested_size; +__u64 allocated_size; +__u64 start_address; +}; +#endif /* VFIO_H */ === end ===
QEMU PATCH:
hw/linux-vfio.h +9
-0@@ -172,4 +172,13 @@ enum {VFIO_PCI_NUM_IRQS }; +/* Setup domain */ +#define VFIO_IOMMU_SETUP _IOWR(';', 150, struct vfio_setup) + +struct vfio_setup { +__u64 requested_size; +__u64 allocated_size; +__u64 start_address; +}; +#endif /* VFIO_H */ hw/vfio_pci.c +0
-0@@ -1501,6 +1503,17 @@ static int vfio_initfn(struct PCIDevice *pdev)if (vfio_map_resources (vdev)) goto out_disable_msi;Quoted 3 lines
hw/vfio_pci.c static int vfio_initfn(struct PCIDevice *pdev) · line 1506
Quoted 1 line
hw/vfio_pci.c +1
-0+struct vfio_setup setup = {1 <<26 ,0 ,0 };How will qemu decide how much to ask for?
It is done by some heuristic. Like "usb controller needs 16mb" and "10Gb card needs more than 100mbit". I'd think that POWER-specific code in QEMU would decide. As POWER supports multiple PCI domains, it can afford spending addresses :)
Quoted 52 lines
Quoted 52 lines
hw/vfio_pci.c +10
-0+if ((ret =ioctl (vdev->group->iommu->fd,VFIO_IOMMU_SETUP , &setup))) { +return ret; + } +printf ("SETUP: requested %lluMB, allocated %lluMB at %llx\n" , + (unsigned long long )setup.requested_size, + (unsigned long long )setup.allocated_size, + (unsigned long long )setup.start_address); + vdev->start_address = setup.start_address; + vdev->window_size = setup.allocated_size; +if (vfio_enable_intx (vdev)) goto out_unmap_resources;hw/vfio_pci.h +4
-0@@ -79,6 +79,10 @@ typedef struct VFIODevice {bool msix;uint8_t msix_bar;uint16_t msix_entries; +#ifdef TARGET_PPC +uint64_t start_address; +uint32_t window_size; +#endif } VFIODevice; typedef struct VFIOGroup {=== end ===
- changed
__vfio_close_iommufunction to do unmapall first and detach devices then as actual deallocation happens on device detach callback of IOMMU ops.drivers/vfio/vfio_main.c +1
-0@@ -28,6 +28,7 @@#include <linux/uaccess.h> #include <linux/vfio.h> #include <linux/wait.h> +#include <linux/pci.h> #include "vfio_private.h" @@ -242,6 +243,13 @@ static void __vfio_close_iommu(struct vfio_iommu *iommu)if (!iommu->domain)return ;Quoted 11 lines
drivers/vfio/vfio_main.c static void __vfio_close_iommu(struct vfio_iommu *iommu) · line 252
Quoted 7 lines
drivers/vfio/vfio_main.c +7
-0+/* +* On POWER, device detaching (which is done by __vfio_iommu_detach_group) +* should happen after all pages unmapped because +* the only way to do actual iommu_unmap_page a device detach callback +*/ +vfio_iommu_unmapall (iommu); +The unmapall/detach vs detach/unmapall shouldn't matter for x86. Though I wonder if we should be proactively resetting devices before either to avoid spurious IOVA faults.
Quoted 1 line
Then we need some to "shutdown" a device.
Quoted 7 lines
VFIO Devices expose the
DEVICE_RESETioctl, which could be exposed to the group viavfio_device_ops.pci_reset_function()does a pretty good job of quiescing devices when it works. I've also been wondering if we need aVFIO_GROUP_RESETwhich can call reset on each device, but also allow things like PCI secondary bus resets when all the devices behind a bridge are in a group. For now I've deferred it as a possible future extension.
Right, we do not need it right now.
Quoted 8 lines
Quoted 4 lines
I am not sure about x86, but on POWER a host allocates DMA window (SETUP does
iommu_allocso the _whole_ DMA window gets allocated), and then a guest allocates pages within this window itself but it only updates the host's IOMMU table with pairs of addresses, a host does not do any no actual map/unmap while guest is running.What's the difference between "updates the host's IOMMU table with pairs of addresses" and map/unmap? Your DMA window is static, but what each IOVA within the window points to is not, correct?
DMA window is configured in system firmware and is static in the host kernel - it has all DMA windows (at least 32-bit windows) defined for all PEs.
64-bit windows are dynamic (a guest may ask a kernel to allocate some) and this also needs to be taken care of (arch-specific ioctls?) but later.
Quoted 16 lines
I would have assumed
you do unmap/map to update each of those (at least David seemed to care about map/unmap latency).x86 maps the entire guest, so the only runtime map/unmaps would be when the memory map changes. Typically this only happens for MMIO regions and odd chipset specific regions that switch between being memory backed or ROM backed (which we really don't care about for DMA), and theoretically for future memory hotplug. At some point we're supposed to have devices and IOMMUs that support IO page faults, so a device can request an IOVA and we'd probably register a page fault handler for the domain to dynamically pin and map pages.
Quoted 1 line
Oooor, we could release the whole window in the domain close callback of
iommu_ops...
Quoted 9 lines
AIUI, the iommu driver will destroy all the mappings in a domain when we call
iommu_domain_free, but the real need for unmapall is to unpin all the memory. David was suggesting maybe the pinning should happen in the iommu driver, which could then handle unpinning on release. I kinda doubt iommu drivers want to get into the business of pinning memory though. I'd actually like VFIO to get out of this business as well and was thinking about requiring mapped pages to be mlocked by the user, but it appears we have no way to later prevent or detect that the user munlocked the pages and might then have access to random host memory.
aaa, I had some discussion here, my implementation was a hack so this problem has gone for now.
Signature · 5 lines
Alexey Kardashevskiy IBM OzLabs, LTC Team e-mail: [email protected] notes: Alexey Kardashevskiy/Australia/IBM