KVM: mm: fd-based approach for supporting KVM guest private memory
Subsystems (23)
Quoted 49 lines · Andy Lutomirski
Quoted 46 lines · Kirill A . Shutemov
Quoted 30 lines · Andy Lutomirski
Quoted 29 lines · Kirill A. Shutemov
Quoted 17 lines · Hugh Dickins
Quoted 7 lines · Kirill A . Shutemov
Quoted 6 lines · Hugh Dickins
If your memory could be swapped, that would be enough of a good reason to make use of
shmem.c: but it cannot be swapped; and although there are some references in the mailthreads to it perhaps being swappable in future, I get the impression that will not happen soon if ever.Quoted 8 lines
Quoted 3 lines
If your memory could be migrated, that would be some reason to use filesystem page cache (because page migration happens to understand that type of memory): but it cannot be migrated.
Migration support is in pipeline. It is part of TDX 1.5 [1]. And swapping theoretically possible, but I'm not aware of any plans as of now.
Quoted 8 lines
I always forget, migration means different things to different audiences. As an mm person, I was meaning page migration, whereas a virtualization person thinks VM live migration (which that reference appears to be about), a scheduler person task migration, an ornithologist bird migration, etc.
But you're an mm person too: you may have cited that reference in the knowledge that TDX 1.5 Live Migration will entail page migration of the kind I'm thinking of. (Anyway, it's not important to clarify that here.)
TDX 1.5 brings both.
Quoted 8 lines
Quoted 2 lines
In TDX speak, mm migration called relocation. See TDH.MEM.PAGE.RELOCATE.
This seems to be a pretty bad fit for the way that the core mm migrates pages. The core mm unmaps the page, then moves (in software) the contents to a new address, then faults it in. TDH.MEM.PAGE.RELOCATE doesn't fit into that workflow very well. I'm not saying it can't be done, but it won't just work.
Hm. From what I see we have all necessary infrastructure in place.
Unmaping is NOP for inaccessible pages as it is never mapped and we have
mapping->a_ops->migrate_folio()callback that allows to replace software copying with whatever is needed, like TDH.MEM.PAGE.RELOCATE.
Quoted 8 lines
Quoted 1 line
What do I miss?
Hmm, maybe this isn't as bad as I thought.
Right now, unless I've missed something, the migration workflow is to unmap (via
try_to_migrate) all mappings, then migrate the backing store (with ->migrate_folio(), although it seems like most callers expect the actual copy to happen outside of ->migrate_folio(),
Most? I guess you are talking about MIGRATE_SYNC_NO_COPY, right? AFAICS, it is HMM thing and not a common thing.
Quoted 4 lines
and then make new
mappings. With the *current* (vma-based, not fd-based) model for KVM memory, this won't work -- we can't unmap before calling TDH.MEM.PAGE.RELOCATE.
We don't need to unmap. The page is not mapped from core-mm PoV.
Quoted 8 lines
But maybe it's actually okay with some care or maybe mild modifications with the fd-based model. We don't have any mmaps, per se, to unmap for secret / INACCESSIBLE memory. So maybe we can get all the way to ->migrate_folio() without zapping anything in the secure EPT and just call TDH-MEM.PAGE.RELOCATE from inside
migrate_folio(). And there will be nothing to fault back in. From the core code's perspective, it's like migrating a memfd that doesn't happen to have my mappings at the time.
Modifications needed if we want to initiate migation from userspace. IIRC, we don't have any API that can initiate page migration for file ranges, without mapping the file.
But kernel can do it fine for own housekeeping, like compaction doesn't need any VMA. And we need compaction working for long term stability of the system.
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Quoted 8 lines · Hugh Dickins
tmpfs and hugetlbfs and page cache are designed around sharing memory:
TDX is designed around absolutely not sharing memory; and the further uses which Sean foresees appear not to need it as page cache either.Except perhaps for page migration reasons. It's somewhat incidental, but of course page migration knows how to migrate page cache, so masquerading as page cache will give a short cut to page migration, when page migration becomes at all possible.
I haven't read the patch series, and I'm not taking a position one way or the other on whether this is better implemented as a shmem addition or a shim that asks shmem for memory. Page migration can be done for driver memory by using PageMovable. I just rewrote how it works, so the details are top of my mind at the moment if anyone wants something explained. Commit 68f2736a8583 is the key one to look at.
Quoted 10 lines · Matthew Wilcox
Quoted 8 lines · Hugh Dickins
tmpfs and hugetlbfs and page cache are designed around sharing memory:
TDX is designed around absolutely not sharing memory; and the further uses which Sean foresees appear not to need it as page cache either.Except perhaps for page migration reasons. It's somewhat incidental, but of course page migration knows how to migrate page cache, so masquerading as page cache will give a short cut to page migration, when page migration becomes at all possible.
Quoted 6 lines
I haven't read the patch series, and I'm not taking a position one way or the other on whether this is better implemented as a shmem addition or a shim that asks shmem for memory. Page migration can be done for driver memory by using PageMovable. I just rewrote how it works, so the details are top of my mind at the moment if anyone wants something explained. Commit
68f2736a8583is the key one to look at.
Thanks Matthew. That is helpful to understand the current code.
Chao
Andy Lutomirski
maintainerQuoted 32 lines · Kirill A . Shutemov
Quoted 31 lines · Hugh Dickins
Quoted 2 lines · Chao Peng
This is the v7 of this series which tries to implement the fd-based KVM guest private memory.
Here at last are my reluctant thoughts on this patchset.
fd-based approach for supporting KVM guest private memory: fine.
Use or abuse of memfd and
shmem.c: mistaken.
memfd_create()was an excellent way to put together the initial prototype.But since then, TDX in particular has forced an effort into preventing (by flags, seals, notifiers) almost everything that makes it shmem/tmpfs.
Are any of the
shmem.cmods useful to existing users ofshmem.c? No. IsMFD_INACCESSIBLEuseful or comprehensible tomemfd_create()users? No.What use do you have for a filesystem here? Almost none. IIUC, what you want is an fd through which QEMU can allocate kernel memory, selectively free that memory, and communicate fd+offset+length to KVM. And perhaps an interface to initialize a little of that memory from a template (presumably copied from a real file on disk somewhere).
You don't need
shmem.cor a filesystem for that!If your memory could be swapped, that would be enough of a good reason to make use of
shmem.c: but it cannot be swapped; and although there are some references in the mailthreads to it perhaps being swappable in future, I get the impression that will not happen soon if ever.
Quoted 9 lines
Quoted 3 lines
If your memory could be migrated, that would be some reason to use filesystem page cache (because page migration happens to understand that type of memory): but it cannot be migrated.
Migration support is in pipeline. It is part of TDX 1.5 [1]. And swapping theoretically possible, but I'm not aware of any plans as of now.
This thing?
https://cdrdv2.intel.com/v1/dl/getContent/733578
That looks like migration between computers, not between NUMA nodes. Or am I missing something?
Christian Brauner
maintainerQuoted 75 lines · Kirill A . Shutemov
Quoted 26 lines · Hugh Dickins
Quoted 2 lines · Chao Peng
This is the v7 of this series which tries to implement the fd-based KVM guest private memory.
Here at last are my reluctant thoughts on this patchset.
fd-based approach for supporting KVM guest private memory: fine.
Use or abuse of memfd and
shmem.c: mistaken.
memfd_create()was an excellent way to put together the initial prototype.But since then, TDX in particular has forced an effort into preventing (by flags, seals, notifiers) almost everything that makes it shmem/tmpfs.
Are any of the
shmem.cmods useful to existing users ofshmem.c? No. IsMFD_INACCESSIBLEuseful or comprehensible tomemfd_create()users? No.What use do you have for a filesystem here? Almost none. IIUC, what you want is an fd through which QEMU can allocate kernel memory, selectively free that memory, and communicate fd+offset+length to KVM. And perhaps an interface to initialize a little of that memory from a template (presumably copied from a real file on disk somewhere).
You don't need
shmem.cor a filesystem for that!Quoted 8 lines
If your memory could be swapped, that would be enough of a good reason to make use of
shmem.c: but it cannot be swapped; and although there are some references in the mailthreads to it perhaps being swappable in future, I get the impression that will not happen soon if ever.If your memory could be migrated, that would be some reason to use filesystem page cache (because page migration happens to understand that type of memory): but it cannot be migrated.
Migration support is in pipeline. It is part of TDX 1.5 [1]. And swapping theoretically possible, but I'm not aware of any plans as of now.
Quoted 11 lines
Some of these impressions may come from earlier iterations of the patchset (v7 looks better in several ways than v5). I am probably underestimating the extent to which you have taken on board other usages beyond TDX and SEV private memory, and rightly want to serve them all with similar interfaces: perhaps there is enough justification for shmem there, but I don't see it. There was mention of userfaultfd in one link: does that provide the justification for using shmem?
I'm afraid of the special demands you may make of memory allocation later on - surprised that huge pages are not mentioned already; gigantic contiguous extents? secretmem removed from direct map?
The design allows for extension to hugetlbfs if needed. Combination of
MFD_INACCESSIBLE|MFD_HUGETLBshould route this way. There should be zero implications for shmem. It is going to be separate structmemfile_backing_store.I'm not sure secretmem is a fit here as we want to extend
MFD_INACCESSIBLEto be movable if platform supports it and secretmem is not migratable by design (without direct mapping fragmentations).Quoted 13 lines
Here's what I would prefer, and imagine much easier for you to maintain; but I'm no system designer, and may be misunderstanding throughout.
QEMU gets fd from opening
/dev/kvm_something, uses ioctls (or perhaps the fallocate syscall interface itself) to allocate and free the memory, ioctl for initializing some of it too. KVM in control of whether that fd can be read or written or mmap'ed or whatever, no need to prevent it inshmem.c, no need for flags, seals, notifications to and fro because KVM is already in control and knows the history. If shmem actually has value, call into it underneath - somewhat like SysV SHM, and/dev/zerommap, and i915/gem make use of it underneath. If shmem has nothing to add, just allocate and free kernel memory directly, recorded in your own xarray.
Quoted 4 lines
I guess shim layer on top of shmem *can* work. I don't see immediately why it would not. But I'm not sure it is right direction. We risk creating yet another parallel VM with own rules/locking/accounting that opaque to core-mm.
Sorry for necrobumping this thread but I've been reviewing the memfd_restricted() extension that Ackerley is currently working on. I was pointed to this thread as this is what the extension is building on but I'll reply to both threads here.
From a glance at v10, memfd_restricted() is currently implemented as an in-kernel stacking filesystem. A call to memfd_restricted() creates a new restricted memfd file and a new unlinked tmpfs file and stashes the tmpfs file into the memfd file's private data member. It then uses the tmpfs file's f_ops and i_ops to perform the relevant file and inode operations. So it has the same callstack as a general stacking filesystem like overlayfs in some cases:
memfd_restricted->getattr()
-> tmpfs->getattr()The extension that Ackerley is now proposing is to allow passing in a tmpfs file descriptor explicitly to identify the tmpfs instance in which to allocate the tmpfs file which is stashed in the memfd secret file.
So in the ->getattr() callstack I mentioned above this patchset currently does:
static int restrictedmem_getattr(struct user_namespace *mnt_userns,
const struct path *path, struct kstat stat,
u32 request_mask, unsigned int uery_flags)
{
struct inode *inode = d_inode(path->dentry);
struct restrictedmem_data *data = node->i_mapping->private_data;
struct file *memfd = data->memfd;
return memfd->f_inode->i_op->getattr(mnt_userns, path, stat,
request_mask, query_flags);
}There's a bug in here that I mentioned in another thread and I see that Ackerley has mentioned as well in
https://lore.kernel.org/lkml/[email protected]
namely that this is passing a restricted memfd struct path to a tmpfs inode operation which is very wrong.
But also in the current implementation - I mentioned this in the other thread as well - when you call stat() on a restricted memfd file descriptor you get all the information about the underlying tmpfs inode. Specifically this includes the device number and inode number.
But when you call statfs() then you get a report that this is a memfd restricted filesystem which somehow shares the device number with a tmpfs instance. That's messy.
Since you're effectively acting like a stacking filesystem you should really use the device number of your memfd restricted filesystem. IOW, sm like:
stat->dev = memfd_restricted_dentry->d_sb->s_dev;
But then you run into trouble if you want to go forward with Ackerley's extension that allows to explicitly pass in tmpfs fds to memfd_restricted(). Afaict, two tmpfs instances might allocate the same inode number. So now the inode and device number pair isn't unique anymore.
So you might best be served by allocating and reporting your own inode numbers as well.
But if you want to preserve the inode number and device number of the relevant tmpfs instance but still report memfd restricted as your filesystem type then I think it's reasonable to ask whether a stacking implementation really makes sense here.
If you extend memfd_restricted() or even consider extending it in the future to take tmpfs file descriptors as arguments to identify the tmpfs instance in which to allocate the underlying tmpfs file for the new restricted memfd file you should really consider a tmpfs based implementation.
Because at that point it just feels like a pointless wrapper to get custom f_ops and i_ops. Plus it's wasteful because you allocate dentries and inodes that you don't really care about at all.
Just off the top of my hat you might be better served:
* by a new ioctl() on tmpfs instances that
yield regular tmpfs file descriptors with restricted f_ops and i_ops. That's not that different from btrfs subvolumes which effectively are directories but are created through an ioctl().
* by a mount option to tmpfs that makes it act
in this restricted manner then you don't need an ioctl() and can get away with regular open calls. Such a tmpfs instance would only create regular, restricted memfds.
I think especially with the possibility of an extension that allows you to inherit tmpfs properties by allocating the memfd restriced file in a specific tmpfs instance the argument that you're not really making use of tmpfs things has gone out of the window.
Quoted 6 lines
Note that on machines that run TDX guests such memory would likely be the bulk of memory use. Treating it as a fringe case may bite us one day.
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Quoted 224 lines · Ackerley Tng
Thanks again for your review!
Quoted 11 lines · Christian Brauner
Quoted 10 lines · Christian Brauner
Quoted 9 lines · Ackerley Tng
...
(quoted diff) +1
-1-SYSCALL_DEFINE1(memfd_restricted, unsigned int, flags) +static int restrictedmem_create(struct vfsmount *mount) { struct file *file, *restricted_file; int fd, err;Quoted 10 lines
Quoted 10 lines
Review
Quoted 4 lines
(quoted diff) +0
-3- if (flags) - return -EINVAL; - fd = get_unused_fd_flags(0);Any reasons the file descriptors aren't
O_CLOEXECby default? I don't see any reasons why we should introduce new fdtypes that aren'tO_CLOEXECby default. The "don't mix-and-match" train has already left the station anyway as we do have seccomp noitifer fds and pidfds both of which areO_CLOEXECby default.Thanks for pointing this out. I agree with using
O_CLOEXEC, but didn’t notice this before. Let us discuss this under the original series at [1].Quoted 15 lines
Quoted 15 lines
Review
Quoted 6 lines
(quoted diff) +2
-1if (fd < 0) return fd; - file = shmem_file_setup("memfd:restrictedmem", 0, VM_NORESERVE); + if (mount) + file = shmem_file_setup_with_mnt(mount, "memfd:restrictedmem",0,
VM_NORESERVE);Review SYSCALL_DEFINE1(memfd_restricted, unsigned
Quoted 7 lines
(quoted diff) +3
-0+ else + file = shmem_file_setup("memfd:restrictedmem", 0, VM_NORESERVE); + if (IS_ERR(file)) { err = PTR_ERR(file); goto err_fd;@@ -223,6 +225,66 @@ SYSCALL_DEFINE1(memfd_restricted, unsignedint, flags)
Quoted 8 lines
Quoted 8 lines
Review SYSCALL_DEFINE1(memfd_restricted, unsigned · line 230
Quoted 6 lines
(quoted diff) +3
-0return err; } +static bool is_shmem_mount(struct vfsmount *mnt) +{ + return mnt && mnt->mnt_sb && mnt->mnt_sb->s_magic == TMPFS_MAGIC;This can just be if (
mnt->mnt_sb->s_magic==TMPFS_MAGIC).Will simplify this in the next revision.
Quoted 13 lines
Quoted 12 lines
Review SYSCALL_DEFINE1(memfd_restricted, unsigned · line 235
Quoted 5 lines
(quoted diff) +5
-0+} + +static bool is_mount_root(struct file *file) +{ + return file->f_path.dentry == file->f_path.mnt->mnt_root;mount -t tmpfs tmpfs /mnt
touch/mnt/bla
touch/mnt/ble
mount --bind/mnt/bla/mnt/ble
fd =open("/mnt/ble")fd_restricted=memfd_restricted(fd)Quoted 6 lines
Quoted 6 lines
IOW, this doesn't restrict it to the tmpfs root. It only restricts it to paths that refer to the root of any tmpfs mount. To exclude bind-mounts that aren't bind-mounts of the whole filesystem you want:
path->dentry==path->mnt->mnt_root&&path->mnt->mnt_root==path->mnt->mnt_sb->s_rootWill adopt this in the next revision and add a selftest to check this. Thanks for pointing this out!
Quoted 18 lines
Quoted 18 lines
Quoted 18 lines
(quoted diff) +18
-0+} + +static int restrictedmem_create_on_user_mount(int mount_fd) +{ + int ret; + struct fd f; + struct vfsmount *mnt; + + f = fdget_raw(mount_fd); + if (!f.file) + return -EBADF; + + ret = -EINVAL; + if (!is_mount_root(f.file)) + goto out; + + mnt = f.file->f_path.mnt; + if (!is_shmem_mount(mnt))Quoted 8 lines
Quoted 8 lines
Review SYSCALL_DEFINE1(memfd_restricted, unsigned · line 256
Quoted 3 lines
(quoted diff) +3
-0+ goto out; + + ret = file_permission(f.file, MAY_WRITE | MAY_EXEC);With the current semantics you're asking whether you have write permissions on the
/mnt/blefile in order to get answer to the question whether you're allowed to create an unlinked restricted memory file. That doesn't make much sense afaict.That's true. Since
mnt_want_write()already checks for write permissions and this syscall creates an unlinked file on the mount, we don't have to check permissions on the file then. Will remove this in the next revision!Quoted 18 lines
Quoted 18 lines
Quoted 18 lines
(quoted diff) +18
-0+ if (ret) + goto out; + + ret = mnt_want_write(mnt); + if (unlikely(ret)) + goto out; + + ret = restrictedmem_create(mnt); + + mnt_drop_write(mnt); +out: + fdput(f); + + return ret; +} + +SYSCALL_DEFINE2(memfd_restricted, unsigned int, flags, int, mount_fd) +{Quoted 8 lines
Quoted 8 lines
Review SYSCALL_DEFINE1(memfd_restricted, unsigned · line 278
Quoted 4 lines
(quoted diff) +4
-0+ if (flags & ~RMFD_USERMNT) + return -EINVAL; + + if (flags == RMFD_USERMNT) {Why do you even need this flag? It seems that @mount_fd being < 0 is sufficient to indicate that a new restricted memory fd is supposed to be created in the system instance.
I'm hoping to have this patch series merged after Chao's patch series introduces the
memfd_restricted()syscall [1].This flag is necessary to indicate the validity of the second argument.
With this flag, we can definitively return an error if the fd is invalid, which I think is a better experience for the userspace programmer than if we just silently default to the kernel mount when the fd provided is invalid.
Quoted 35 lines
Quoted 25 lines
Review SYSCALL_DEFINE1(memfd_restricted, unsigned · line 286
Quoted 8 lines
(quoted diff) +8
-0+ if (mount_fd < 0) + return -EINVAL; + + return restrictedmem_create_on_user_mount(mount_fd); + } else { + return restrictedmem_create(NULL); + } +}I have to say that I'm very confused by all of this the more I look at it.
Effectively memfd restricted functions as a wrapper filesystem around the tmpfs filesystem. This is basically a weird overlay filesystem. You're allocating tmpfs files that you stash in restrictedmem files. I have to say that this seems very hacky. I didn't get this at all at first.
So what does the caller get if they call
statx()on a restricted memfd? Do they get the device number of the tmpfs mount and the inode numbers of the tmpfs mount? Because it looks like they would:static int restrictedmem_getattr(struct
user_namespace*mnt_userns,
const struct path *path, struct kstat *stat, u32request_mask, unsigned intquery_flags)Quoted 6 lines
{ struct inode *inode = d_inode(path->dentry); struct restrictedmem *rm = inode->i_mapping->private_data; struct file *memfd = rm->memfd; return memfd->f_inode->i_op->getattr(mnt_userns, path, stat,This is pretty broken btw, because @path refers to a restrictedmem path which you're passing to a tmpfs iop...
Quoted 6 lines
I see that in
return memfd->f_inode->i_op->getattr(mnt_userns, &memfd->f_path, stat, request_mask, query_flags);this if fixed but still, this is... not great.
Thanks, this will be fixed in the next revision by rebasing on Chao's latest code.
Quoted 9 lines
Quoted 8 lines
request_mask, query_flags);That @memfd would be a struct file allocated in a tmpfs instance, no? So you'd be calling the inode operation of the tmpfs file meaning that struct kstat will be filled up with the info from the tmpfs instance.
But then if I call
statfs()and check the fstype I would getRESTRICTEDMEM_MAGIC, no? This is... unorthodox?Quoted 7 lines
Quoted 7 lines
I'm honestly puzzled and this sounds really strange. There must be a better way to implement all of this.
Shouldn't you try and make this a part of tmpfs proper? Make a really separate filesystem and add a memfs library that both tmpfs and restrictedmemfs can use? Add a mount option to tmpfs that makes it a restricted tmpfs?
This was discussed earlier in the patch series introducing
memfd_restrictedand this approach was taken to better manage ownership of required functionalities between two subsystems. Please see discussion beginning [2][1] -> https://lore.kernel.org/lkml/[email protected]/T/.
[2] ->
https://lore.kernel.org/lkml/[email protected]/
Quoted 598 lines · Chao Peng
From: "Kirill A. Shutemov" <[email protected]>
Introduce '
memfd_restricted' system call with the ability to create memory areas that are restricted from userspace access through ordinary MMU operations (e.g. read/write/mmap). The memory content is expected to be used through the new in-kernel interface by a third kernel module.
memfd_restricted()is useful for scenarios where a file descriptor(fd) can be used as an interface into mm but want to restrict userspace's ability on the fd. Initially it is designed to provide protections for KVM encrypted guest memory.Normally KVM uses memfd memory via mmapping the memfd into KVM userspace (e.g. QEMU) and then using the mmaped virtual address to setup the mapping in the KVM secondary page table (e.g. EPT). With confidential computing technologies like Intel TDX, the memfd memory may be encrypted with special key for special software domain (e.g. KVM guest) and is not expected to be directly accessed by userspace. Precisely, userspace access to such encrypted memory may lead to host crash so should be prevented.
memfd_restricted()provides semantics required for KVM guest encrypted memory support that a fd created withmemfd_restricted()is going to be used as the source of guest memory in confidential computing environment and KVM can directly interact with core-mm without the need to expose the memoy content into KVM userspace.KVM userspace is still in charge of the lifecycle of the fd. It should pass the created fd to KVM. KVM uses the new
restrictedmem_get_page()to obtain the physical memory page and then uses it to populate the KVM secondary page table entries.The userspace restricted memfd can be fallocate-ed or hole-punched from userspace. When hole-punched, KVM can get notified through invalidate_start/invalidate_end() callbacks, KVM then gets chance to remove any mapped entries of the range in the secondary page tables.
Machine check can happen for memory pages in the restricted memfd, instead of routing this directly to userspace, we call the
error()callback that KVM registered. KVM then gets chance to handle it correctly.
memfd_restricted()itself is implemented as a shim layer on top of real memory file systems (currently tmpfs). Pages in restrictedmem are marked as unmovable and unevictable, this is required for current confidential usage. But in future this might be changed.By default
memfd_restricted()prevents userspace read, write and mmap. By defining new bit in the 'flags', it can be extended to support other restricted semantics in the future.The system call is currently wired up for x86 arch.
Signed-off-by Kirill A. Shutemov <[email protected]>Signed-off-by Chao Peng <[email protected]>--- arch/x86/entry/syscalls/syscall_32.tbl | 1 + arch/x86/entry/syscalls/syscall_64.tbl | 1 + include/linux/restrictedmem.h | 71 ++++++ include/linux/syscalls.h | 1 + include/uapi/asm-generic/unistd.h | 5 +- include/uapi/linux/magic.h | 1 + kernel/sys_ni.c | 3 + mm/Kconfig | 4 + mm/Makefile | 1 + mm/memory-failure.c | 3 + mm/restrictedmem.c | 318 +++++++++++++++++++++++++ 11 files changed, 408 insertions(+), 1 deletion(-) create mode 100644 include/linux/restrictedmem.h create mode 100644 mm/restrictedmem.carch/x86/entry/syscalls/syscall_32.tbl +1
-0@@ -455,3 +455,4 @@ 448 i386 process_mrelease sys_process_mrelease 449 i386 futex_waitv sys_futex_waitv 450 i386 set_mempolicy_home_node sys_set_mempolicy_home_node +451 i386 memfd_restricted sys_memfd_restrictedarch/x86/entry/syscalls/syscall_64.tbl +1
-0@@ -372,6 +372,7 @@ 448 common process_mrelease sys_process_mrelease 449 common futex_waitv sys_futex_waitv 450 common set_mempolicy_home_node sys_set_mempolicy_home_node +451 common memfd_restricted sys_memfd_restricted # # Due to a historical design error, certain syscalls are numbered differentlyinclude/linux/restrictedmem.h new file +71
-0@@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _LINUX_RESTRICTEDMEM_H + +#include <linux/file.h> +#include <linux/magic.h> +#include <linux/pfn_t.h> + +struct restrictedmem_notifier ; + +struct restrictedmem_notifier_ops { +void (*invalidate_start)(struct restrictedmem_notifier *notifier, +pgoff_t start,pgoff_t end); +void (*invalidate_end)(struct restrictedmem_notifier *notifier, +pgoff_t start,pgoff_t end); +void (*error)(struct restrictedmem_notifier *notifier, +pgoff_t start,pgoff_t end); +}; + +struct restrictedmem_notifier { +struct list_head list; +const struct restrictedmem_notifier_ops *ops; +}; + +#ifdef CONFIG_RESTRICTEDMEM + +void restrictedmem_register_notifier (struct file *file, +struct restrictedmem_notifier *notifier); +void restrictedmem_unregister_notifier (struct file *file, +struct restrictedmem_notifier *notifier); + +int restrictedmem_get_page (struct file *file,pgoff_t offset, +struct page **pagep,int *order); + +static inline bool file_is_restrictedmem (struct file *file) +{ +return file->f_inode->i_sb->s_magic ==RESTRICTEDMEM_MAGIC ; +} + +void restrictedmem_error_page (struct page *page,struct address_space *mapping); + +#else + +static inline void restrictedmem_register_notifier (struct file *file, +struct restrictedmem_notifier *notifier) +{ +} + +static inline void restrictedmem_unregister_notifier (struct file *file, +struct restrictedmem_notifier *notifier) +{ +} + +static inline int restrictedmem_get_page (struct file *file,pgoff_t offset, +struct page **pagep,int *order) +{ +return -1 ; +} + +static inline bool file_is_restrictedmem (struct file *file) +{ +return false; +} + +static inline void restrictedmem_error_page (struct page *page, +struct address_space *mapping) +{ +} + +#endif /* CONFIG_RESTRICTEDMEM */ + +#endif /* _LINUX_RESTRICTEDMEM_H */ include/linux/syscalls.h +1
-0@@ -1056,6 +1056,7 @@ asmlinkage long sys_memfd_secret(unsigned int flags);asmlinkage long sys_set_mempolicy_home_node (unsigned long start,unsigned long len,unsigned long home_node,unsigned long flags); +asmlinkage long sys_memfd_restricted (unsigned int flags);/* * Architecture-specific system calls include/uapi/asm-generic/unistd.h +4
-1@@ -886,8 +886,11 @@ __SYSCALL(__NR_futex_waitv, sys_futex_waitv)#define __NR_set_mempolicy_home_node 450 __SYSCALL(__NR_set_mempolicy_home_node, sys_set_mempolicy_home_node) +#define __NR_memfd_restricted 451 +__SYSCALL(__NR_memfd_restricted, sys_memfd_restricted) +#undef __NR_syscalls -#define __NR_syscalls 451 +#define __NR_syscalls 452/* * 32 bit systems traditionally used different include/uapi/linux/magic.h +1
-0@@ -101,5 +101,6 @@#define DMA_BUF_MAGIC 0x444d4142/* "DMAB" */ #define DEVMEM_MAGIC 0x454d444d/* "DMEM" */ #define SECRETMEM_MAGIC 0x5345434d/* "SECM" */ +#define RESTRICTEDMEM_MAGIC 0x5245534d/* "RESM" */ #endif /* __LINUX_MAGIC_H__ */ kernel/sys_ni.c +3
-0@@ -360,6 +360,9 @@ COND_SYSCALL(pkey_free);/* memfd_secret */ COND_SYSCALL (memfd_secret); +/* memfd_restricted */ +COND_SYSCALL (memfd_restricted); +/* * Architecture specific weak syscall entries. */ mm/Kconfig +4
-0@@ -1076,6 +1076,10 @@ config IO_MAPPING config SECRETMEM def_bool ARCH_HAS_SET_DIRECT_MAP && !EMBEDDED +config RESTRICTEDMEM + bool + depends on TMPFS + config ANON_VMA_NAME bool "Anonymous VMA name support" depends on PROC_FS && ADVISE_SYSCALLS && MMUmm/Makefile +1
-0@@ -121,6 +121,7 @@ obj-$(CONFIG_PAGE_EXTENSION) += page_ext.o obj-$(CONFIG_PAGE_TABLE_CHECK) += page_table_check.o obj-$(CONFIG_CMA_DEBUGFS) += cma_debug.o obj-$(CONFIG_SECRETMEM) += secretmem.o +obj-$(CONFIG_RESTRICTEDMEM) += restrictedmem.o obj-$(CONFIG_CMA_SYSFS) += cma_sysfs.o obj-$(CONFIG_USERFAULTFD) += userfaultfd.o obj-$(CONFIG_IDLE_PAGE_TRACKING) += page_idle.omm/memory-failure.c +3
-0@@ -62,6 +62,7 @@#include <linux/page-isolation.h> #include <linux/pagewalk.h> #include <linux/shmem_fs.h> +#include <linux/restrictedmem.h> #include "swap.h" #include "internal.h" #include "ras/ras_event.h" @@ -940,6 +941,8 @@ static int me_pagecache_clean(struct page_state *ps, struct page *p) goto out; } +restrictedmem_error_page (p, mapping); +/* * The shmem page is kept in page cache instead of truncating * so is expected to have an extra refcount after error-handling. mm/restrictedmem.c new file +318
-0@@ -0,0 +1,318 @@ +// SPDX-License-Identifier: GPL-2.0 +#include "linux/sbitmap.h" +#include <linux/pagemap.h> +#include <linux/pseudo_fs.h> +#include <linux/shmem_fs.h> +#include <linux/syscalls.h> +#include <uapi/linux/falloc.h> +#include <uapi/linux/magic.h> +#include <linux/restrictedmem.h> + +struct restrictedmem_data { +struct mutex lock; +struct file *memfd; +struct list_head notifiers; +}; + +static void restrictedmem_invalidate_start (struct restrictedmem_data *data, +pgoff_t start,pgoff_t end) +{ +struct restrictedmem_notifier *notifier; + +mutex_lock (&data->lock); +list_for_each_entry (notifier, &data->notifiers, list) { + notifier->ops->invalidate_start (notifier, start, end); + } +mutex_unlock (&data->lock); +} + +static void restrictedmem_invalidate_end (struct restrictedmem_data *data, +pgoff_t start,pgoff_t end) +{ +struct restrictedmem_notifier *notifier; + +mutex_lock (&data->lock); +list_for_each_entry (notifier, &data->notifiers, list) { + notifier->ops->invalidate_end (notifier, start, end); + } +mutex_unlock (&data->lock); +} + +static void restrictedmem_notifier_error (struct restrictedmem_data *data, +pgoff_t start,pgoff_t end) +{ +struct restrictedmem_notifier *notifier; + +mutex_lock (&data->lock); +list_for_each_entry (notifier, &data->notifiers, list) { + notifier->ops->error (notifier, start, end); + } +mutex_unlock (&data->lock); +} + +static int restrictedmem_release (struct inode *inode,struct file *file) +{ +struct restrictedmem_data *data = inode->i_mapping->private_data; + +fput (data->memfd); +kfree (data); +return 0 ; +} + +static long restrictedmem_punch_hole (struct restrictedmem_data *data,int mode, +loff_t offset,loff_t len) +{ +int ret; +pgoff_t start, end; +struct file *memfd = data->memfd; + +if (!PAGE_ALIGNED (offset) || !PAGE_ALIGNED (len)) +return -EINVAL ; + + start = offset >>PAGE_SHIFT ; + end = (offset + len) >>PAGE_SHIFT ; + +restrictedmem_invalidate_start (data, start, end); + ret = memfd->f_op->fallocate (memfd, mode, offset, len); +restrictedmem_invalidate_end (data, start, end); + +return ret; +} + +static long restrictedmem_fallocate (struct file *file,int mode, +loff_t offset,loff_t len) +{ +struct restrictedmem_data *data = file->f_mapping->private_data; +struct file *memfd = data->memfd; + +if (mode &FALLOC_FL_PUNCH_HOLE ) +return restrictedmem_punch_hole (data, mode, offset, len); + +return memfd->f_op->fallocate (memfd, mode, offset, len); +} + +static const struct file_operations restrictedmem_fops = { + .release = restrictedmem_release, + .fallocate = restrictedmem_fallocate, +}; + +static int restrictedmem_getattr (struct user_namespace *mnt_userns, +const struct path *path,struct kstat *stat, +u32 request_mask,unsigned int query_flags) +{ +struct inode *inode =d_inode (path->dentry); +struct restrictedmem_data *data = inode->i_mapping->private_data; +struct file *memfd = data->memfd; + +return memfd->f_inode->i_op->getattr (mnt_userns, path, stat, + request_mask, query_flags); +} + +static int restrictedmem_setattr (struct user_namespace *mnt_userns, +struct dentry *dentry,struct iattr *attr) +{ +struct inode *inode =d_inode (dentry); +struct restrictedmem_data *data = inode->i_mapping->private_data; +struct file *memfd = data->memfd; +int ret; + +if (attr->ia_valid &ATTR_SIZE ) { +if (memfd->f_inode->i_size) +return -EPERM ; + +if (!PAGE_ALIGNED (attr->ia_size)) +return -EINVAL ; + } + + ret = memfd->f_inode->i_op->setattr (mnt_userns, +file_dentry (memfd), attr); +return ret; +} + +static const struct inode_operations restrictedmem_iops = { + .getattr = restrictedmem_getattr, + .setattr = restrictedmem_setattr, +}; + +static int restrictedmem_init_fs_context (struct fs_context *fc) +{ +if (!init_pseudo (fc,RESTRICTEDMEM_MAGIC )) +return -ENOMEM ; + + fc->s_iflags |=SB_I_NOEXEC ; +return 0 ; +} + +static struct file_system_type restrictedmem_fs = { + .owner =THIS_MODULE , + .name ="memfd:restrictedmem" , + .init_fs_context = restrictedmem_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static struct vfsmount *restrictedmem_mnt; + +static __init int restrictedmem_init (void ) +{ + restrictedmem_mnt =kern_mount (&restrictedmem_fs); +if (IS_ERR (restrictedmem_mnt)) +return PTR_ERR (restrictedmem_mnt); +return 0 ; +} +fs_initcall (restrictedmem_init); + +static struct file *restrictedmem_file_create (struct file *memfd) +{ +struct restrictedmem_data *data; +struct address_space *mapping; +struct inode *inode; +struct file *file; + + data =kzalloc (sizeof (*data),GFP_KERNEL ); +if (!data) +return ERR_PTR (-ENOMEM ); + + data->memfd = memfd; +mutex_init (&data->lock); +INIT_LIST_HEAD (&data->notifiers); + + inode =alloc_anon_inode (restrictedmem_mnt->mnt_sb); +if (IS_ERR (inode)) { +kfree (data); +return ERR_CAST (inode); + } + + inode->i_mode |=S_IFREG ; + inode->i_op = &restrictedmem_iops; + inode->i_mapping->private_data = data; + + file =alloc_file_pseudo (inode, restrictedmem_mnt, +"restrictedmem" ,O_RDWR , + &restrictedmem_fops); +if (IS_ERR (file)) { +iput (inode); +kfree (data); +return ERR_CAST (file); + } + + file->f_flags |=O_LARGEFILE ; + +/* +* These pages are currently unmovable so don't place them into movable +* pageblocks (e.g. CMA and ZONE_MOVABLE). +*/ + mapping = memfd->f_mapping; +mapping_set_unevictable (mapping); +mapping_set_gfp_mask (mapping, +mapping_gfp_mask (mapping) & ~__GFP_MOVABLE); + +return file; +} + +SYSCALL_DEFINE1(memfd_restricted, unsigned int, flags) +{ +struct file *file, *restricted_file; +int fd, err; + +if (flags) +return -EINVAL ; + + fd =get_unused_fd_flags (0 ); +if (fd <0 ) +return fd; + + file =shmem_file_setup ("memfd:restrictedmem" ,0 ,VM_NORESERVE ); +if (IS_ERR (file)) { + err =PTR_ERR (file); + goto err_fd; + } + file->f_mode |=FMODE_LSEEK |FMODE_PREAD |FMODE_PWRITE ; + file->f_flags |=O_LARGEFILE ; + + restricted_file =restrictedmem_file_create (file); +if (IS_ERR (restricted_file)) { + err =PTR_ERR (restricted_file); +fput (file); + goto err_fd; + } + +fd_install (fd, restricted_file); +return fd; +err_fd: +put_unused_fd (fd); +return err; +} + +void restrictedmem_register_notifier (struct file *file, +struct restrictedmem_notifier *notifier) +{ +struct restrictedmem_data *data = file->f_mapping->private_data; + +mutex_lock (&data->lock); +list_add (¬ifier->list, &data->notifiers); +mutex_unlock (&data->lock); +} +EXPORT_SYMBOL_GPL (restrictedmem_register_notifier); + +void restrictedmem_unregister_notifier (struct file *file, +struct restrictedmem_notifier *notifier) +{ +struct restrictedmem_data *data = file->f_mapping->private_data; + +mutex_lock (&data->lock); +list_del (¬ifier->list); +mutex_unlock (&data->lock); +} +EXPORT_SYMBOL_GPL (restrictedmem_unregister_notifier); + +int restrictedmem_get_page (struct file *file,pgoff_t offset, +struct page **pagep,int *order) +{ +struct restrictedmem_data *data = file->f_mapping->private_data; +struct file *memfd = data->memfd; +struct folio *folio; +struct page *page; +int ret; + + ret =shmem_get_folio (file_inode (memfd), offset, &folio,SGP_WRITE ); +if (ret) +return ret; + + page =folio_file_page (folio, offset); + *pagep = page; +if (order) + *order =thp_order (compound_head (page)); + +SetPageUptodate (page); +unlock_page (page); + +return 0 ; +} +EXPORT_SYMBOL_GPL (restrictedmem_get_page); + +void restrictedmem_error_page (struct page *page,struct address_space *mapping) +{ +struct super_block *sb = restrictedmem_mnt->mnt_sb; +struct inode *inode, *next; + +if (!shmem_mapping (mapping)) +return ; + +spin_lock (&sb->s_inode_list_lock); +list_for_each_entry_safe (inode, next, &sb->s_inodes, i_sb_list) { +struct restrictedmem_data *data = inode->i_mapping->private_data; +struct file *memfd = data->memfd; + +if (memfd->f_mapping == mapping) { +pgoff_t start, end; + +spin_unlock (&sb->s_inode_list_lock); + + start = page->index; + end = start +thp_nr_pages (page); +restrictedmem_notifier_error (data, start, end); +return ; + } + } +spin_unlock (&sb->s_inode_list_lock); +}Signature · 1 line
2.25.1
Sean Christopherson
maintainerQuoted 16 lines · Christian Brauner
Quoted 15 lines · Kirill A . Shutemov
Quoted 13 lines · Hugh Dickins
Here's what I would prefer, and imagine much easier for you to maintain; but I'm no system designer, and may be misunderstanding throughout.
QEMU gets fd from opening
/dev/kvm_something, uses ioctls (or perhaps the fallocate syscall interface itself) to allocate and free the memory, ioctl for initializing some of it too. KVM in control of whether that fd can be read or written or mmap'ed or whatever, no need to prevent it inshmem.c, no need for flags, seals, notifications to and fro because KVM is already in control and knows the history. If shmem actually has value, call into it underneath - somewhat like SysV SHM, and/dev/zerommap, and i915/gem make use of it underneath. If shmem has nothing to add, just allocate and free kernel memory directly, recorded in your own xarray.
Quoted 6 lines
Quoted 4 lines
I guess shim layer on top of shmem *can* work. I don't see immediately why it would not. But I'm not sure it is right direction. We risk creating yet another parallel VM with own rules/locking/accounting that opaque to core-mm.
Sorry for necrobumping this thread but I've been reviewing the
No worries, I'm just stoked someone who actually knows what they're doing is chiming in :-)
Quoted 14 lines
memfd_restricted()extension that Ackerley is currently working on. I was pointed to this thread as this is what the extension is building on but I'll reply to both threads here.From a glance at v10,
memfd_restricted()is currently implemented as an in-kernel stacking filesystem. A call tomemfd_restricted()creates a new restricted memfd file and a new unlinked tmpfs file and stashes the tmpfs file into the memfd file's private data member. It then uses the tmpfs file'sf_opsandi_opsto perform the relevant file and inode operations. So it has the same callstack as a general stacking filesystem like overlayfs in some cases:memfd_restricted->getattr() -> tmpfs->getattr()
...
Quoted 12 lines
Since you're effectively acting like a stacking filesystem you should really use the device number of your memfd restricted filesystem. IOW, sm like:
stat->dev = memfd_restricted_dentry->d_sb->s_dev;But then you run into trouble if you want to go forward with Ackerley's extension that allows to explicitly pass in tmpfs fds to
memfd_restricted(). Afaict, two tmpfs instances might allocate the same inode number. So now the inode and device number pair isn't unique anymore.
Quoted 6 lines
So you might best be served by allocating and reporting your own inode numbers as well.
But if you want to preserve the inode number and device number of the relevant tmpfs instance but still report memfd restricted as your filesystem type
Unless I missed something along the way, reporting memfd_restricted as a distinct filesystem is very much a non-goal. AFAIK it's purely a side effect of the proposed implementation.
Quoted 13 lines
then I think it's reasonable to ask whether a stacking implementation really makes sense here.
If you extend
memfd_restricted()or even consider extending it in the future to take tmpfs file descriptors as arguments to identify the tmpfs instance in which to allocate the underlying tmpfs file for the new restricted memfd file you should really consider a tmpfs based implementation.Because at that point it just feels like a pointless wrapper to get custom
f_opsandi_ops. Plus it's wasteful because you allocate dentries and inodes that you don't really care about at all.
Quoted 5 lines
Just off the top of my hat you might be better served:
* by a newioctl()on tmpfs instances that
yield regular tmpfs file descriptors with restrictedf_opsandi_ops. That's not that different from btrfs subvolumes which effectively are directories but are created through anioctl().
I think this is more or less what we want to do, except via a dedicated syscall instead of an ioctl() so that the primary interface isn't strictly tied to tmpfs, e.g. so that it can be extended to other backing types in the future.
Quoted 4 lines
* by a mount option to tmpfs that makes it act
in this restricted manner then you don't need anioctl()and can get away with regular open calls. Such a tmpfs instance would only create regular, restricted memfds.
I'd prefer to not go this route, becuase IIUC, it would require relatively invasive changes to shmem code, and IIUC would require similar changes to other support backings in the future, e.g. hugetlbfs? And as above, I don't think any of the potential use cases need restrictedmem to be a uniquely identifiable mount.
One of the goals (hopefully not a pipe dream) is to design restrictmem in such a way that extending it to support other backing types isn't terribly difficult. In case it's not obvious, most of us working on this stuff aren't filesystems experts, and many of us aren't mm experts either. The more we (KVM folks for the most part) can leverage existing code to do the heavy lifting, the better.
After giving myself a bit of a crash course in file systems, would something like the below have any chance of (a) working, (b) getting merged, and (c) being maintainable?
The idea is similar to a stacking filesystem, but instead of stacking, restrictedmem hijacks a f_ops and a_ops to create a lightweight shim around tmpfs. There are undoubtedly issues and edge cases, I'm just looking for a quick "yes, this might be doable" or a "no, that's absolutely bonkers, don't try it".
Thanks!
struct restrictedmem {
struct rw_semaphore lock;
struct file *file;
const struct file_operations *backing_f_ops;
const struct address_space_operations *backing_a_ops;
struct xarray bindings;
bool exclusive;
};static int restrictedmem_release(struct inode *inode, struct file *file)
{
struct restrictedmem *rm = inode->i_mapping->private_data;
xa_destroy(&rm->bindings);
kfree(rm);
WARN_ON_ONCE(rm->backing_f_ops->release);
return 0;
}static long restrictedmem_punch_hole(struct restrictedmem *rm, int mode,
loff_t offset, loff_t len)
{
struct restrictedmem_notifier *notifier;
unsigned long index;
pgoff_t start, end;
int ret;
if (!PAGE_ALIGNED(offset) || !PAGE_ALIGNED(len))
return -EINVAL;
start = offset >> PAGE_SHIFT;
end = (offset + len) >> PAGE_SHIFT;
/*
* Bindings must be stable across invalidation to ensure the start+end
* are balanced.
*/
down_read(&rm->lock);
xa_for_each_range(&rm->bindings, index, notifier, start, end - 1)
notifier->ops->invalidate_start(notifier, start, end);
ret = rm->backing_f_ops->fallocate(rm->file, mode, offset, len);
xa_for_each_range(&rm->bindings, index, notifier, start, end - 1)
notifier->ops->invalidate_end(notifier, start, end);
up_read(&rm->lock);
return ret;
}static long restrictedmem_fallocate(struct file *file, int mode,
loff_t offset, loff_t len)
{
struct restrictedmem *rm = file->f_mapping->private_data;
if (mode & FALLOC_FL_PUNCH_HOLE)
return restrictedmem_punch_hole(rm, mode, offset, len);
return rm->backing_f_ops->fallocate(file, mode, offset, len);
}static int restrictedmem_migrate_folio(struct address_space *mapping,
struct folio *dst, struct folio *src, enum migrate_mode)
{
WARN_ON_ONCE(1);
return -EINVAL;
}static int restrictedmem_error_page(struct address_space *mapping,
struct page *page)
{
struct restrictedmem *rm = mapping->private_data;
struct restrictedmem_notifier *notifier;
unsigned long index;
pgoff_t start, end;
start = page->index;
end = start + thp_nr_pages(page);
down_read(&rm->lock);
xa_for_each_range(&rm->bindings, index, notifier, start, end - 1)
notifier->ops->error(notifier, start, end);
up_read(&rm->lock);
return rm->backing_a_ops->error_remove_page(mapping, page);
}static const struct file_operations restrictedmem_fops = {
.release = restrictedmem_release, .fallocate = restrictedmem_fallocate,
};
static const struct address_space_operations restrictedmem_aops = {
.dirty_folio = noop_dirty_folio,
#ifdef CONFIG_MIGRATION
.migrate_folio = restrictedmem_migrate_folio,
#endif
.error_remove_page = restrictedmem_error_page,
};
static int restrictedmem_file_create(struct file *file)
{
struct address_space *mapping = file->f_mapping;
struct restrictedmem *rm;
rm = kzalloc(sizeof(*rm), GFP_KERNEL);
if (!rm)
return -ENOMEM;
rm->backing_f_ops = file->f_op;
rm->backing_a_ops = mapping->a_ops;
rm->file = file;
init_rwsem(&rm->lock);
xa_init(&rm->bindings);
file->f_flags |= O_LARGEFILE;
file->f_op = &restrictedmem_fops;
mapping->a_ops = &restrictedmem_aops;
mapping_set_unevictable(mapping);
mapping_set_unmovable(mapping);
mapping_set_gfp_mask(mapping,
mapping_gfp_mask(mapping) & ~__GFP_MOVABLE);
return 0;
}static int restrictedmem_create(struct vfsmount *mount)
{
struct file *file;
int fd, err;
fd = get_unused_fd_flags(0);
if (fd < 0)
return fd;
file = shmem_file_setup_with_mnt(mount, "memfd:restrictedmem", 0, VM_NORESERVE);
if (IS_ERR(file)) {
err = PTR_ERR(file);
goto err_fd;
}
if (WARN_ON_ONCE(file->private_data)) {
err = -EEXIST;
goto err_fd;
}
file->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
file->f_flags |= O_LARGEFILE;
err = restrictedmem_file_create(file);
if (err) {
fput(file);
goto err_fd;
}
fd_install(fd, file);
return fd;
err_fd:
put_unused_fd(fd);
return err;
}SYSCALL_DEFINE2(memfd_restricted, unsigned int, flags, int, mount_fd)
{
struct vfsmount *mnt;
struct path *path;
struct fd f;
int ret;
if (flags)
return -EINVAL;
f = fdget_raw(mount_fd);
if (!f.file)
return -EBADF;
ret = -EINVAL;
path = &f.file->f_path;
if (path->dentry != path->mnt->mnt_root)
goto out;
/* Disallow bind-mounts that aren't bind-mounts of the whole filesystem. */
mnt = path->mnt;
if (mnt->mnt_root != mnt->mnt_sb->s_root)
goto out;
/*
* The filesystem must be mounted no-execute, executing from guest
* private memory in the host is nonsensical and unsafe.
*/
if (!(mnt->mnt_sb->s_iflags & SB_I_NOEXEC))
goto out;
/* Currently only TMPFS is supported as underlying storage. */
if (mnt->mnt_sb->s_magic != TMPFS_MAGIC)
goto out;
ret = mnt_want_write(mnt);
if (ret)
goto out;
ret = restrictedmem_create(mnt);
if (mnt)
mnt_drop_write(mnt);
out:
if (f.file)
fdput(f);
return ret;
}Quoted 28 lines · Sean Christopherson
Quoted 27 lines · Christian Brauner
Quoted 2 lines · Kirill A . Shutemov
Quoted 1 line · Hugh Dickins
Here's what I would prefer, and imagine much easier for you to
maintain;
Quoted 4 lines
Quoted 4 lines
but I'm no system designer, and may be misunderstanding throughout.
QEMU gets fd from opening
/dev/kvm_something, uses ioctls (or perhaps the fallocate syscall interface itself) to allocate and free thememory,
Quoted 1 line
Quoted 1 line
ioctl for initializing some of it too. KVM in control of whether
that
Quoted 1 line
Quoted 1 line
fd can be read or written or mmap'ed or whatever, no need to prevent
it
Quoted 1 line
Quoted 1 line
in
shmem.c, no need for flags, seals, notifications to and frobecause
Quoted 1 line
Quoted 1 line
KVM is already in control and knows the history. If shmem actually
has
Quoted 1 line
Quoted 1 line
value, call into it underneath - somewhat like SysV SHM, and
/dev/zeroQuoted 1 line
Quoted 1 line
mmap, and i915/gem make use of it underneath. If shmem has nothing
to
Quoted 4 lines
Quoted 2 lines
add, just allocate and free kernel memory directly, recorded in your own xarray.
I guess shim layer on top of shmem *can* work. I don't see immediately
why
Quoted 1 line
it would not. But I'm not sure it is right direction. We risk creating
Quoted 8 lines
Quoted 5 lines
yet
Quoted 2 lines
another parallel VM with own rules/locking/accounting that opaque to core-mm.
Sorry for necrobumping this thread but I've been reviewing the
No worries, I'm just stoked someone who actually knows what they're doing is chiming in :-)
+1, thanks Christian!
Quoted 68 lines
Quoted 14 lines
memfd_restricted()extension that Ackerley is currently working on. I was pointed to this thread as this is what the extension is building on but I'll reply to both threads here.From a glance at v10,
memfd_restricted()is currently implemented as an
in-kernel stacking filesystem. A call tomemfd_restricted()creates a new restricted memfd file and a new unlinked tmpfs file and stashes the tmpfs file into the memfd file's private data member. It then uses the tmpfs file'sf_opsandi_opsto perform the relevant file and inode operations. So it has the same callstack as a general stacking filesystem like overlayfs in some cases:memfd_restricted->getattr() -> tmpfs->getattr()...
Quoted 12 lines
Since you're effectively acting like a stacking filesystem you should really use the device number of your memfd restricted filesystem. IOW, sm like:
stat->dev = memfd_restricted_dentry->d_sb->s_dev;But then you run into trouble if you want to go forward with Ackerley's extension that allows to explicitly pass in tmpfs fds to
memfd_restricted(). Afaict, two tmpfs instances might allocate the same inode number. So now the inode and device number pair isn't unique anymore.Quoted 6 lines
So you might best be served by allocating and reporting your own inode numbers as well.
But if you want to preserve the inode number and device number of the relevant tmpfs instance but still report memfd restricted as your filesystem type
Unless I missed something along the way, reporting
memfd_restrictedas a distinct filesystem is very much a non-goal. AFAIK it's purely a side effect of the proposed implementation.Quoted 13 lines
then I think it's reasonable to ask whether a stacking implementation really makes sense here.
If you extend
memfd_restricted()or even consider extending it in the future to take tmpfs file descriptors as arguments to identify the tmpfs instance in which to allocate the underlying tmpfs file for the new restricted memfd file you should really consider a tmpfs based implementation.Because at that point it just feels like a pointless wrapper to get custom
f_opsandi_ops. Plus it's wasteful because you allocate dentries and inodes that you don't really care about at all.Quoted 5 lines
Just off the top of my hat you might be better served:
* by a newioctl()on tmpfs instances that
yield regular tmpfs file descriptors with restrictedf_opsandi_ops. That's not that different from btrfs subvolumes which effectively are directories but are created through anioctl().I think this is more or less what we want to do, except via a dedicated syscall instead of an
ioctl()so that the primary interface isn't strictly tied to tmpfs, e.g. so that it can be extended to other backing types in the future.Quoted 4 lines
* by a mount option to tmpfs that makes it act
in this restricted manner then you don't need anioctl()and can get away with regular open calls. Such a tmpfs instance would only create regular, restricted memfds.
Quoted 5 lines
I'd prefer to not go this route, becuase IIUC, it would require relatively invasive changes to shmem code, and IIUC would require similar changes to other support backings in the future, e.g. hugetlbfs? And as above, I don't think any of the potential use cases need restrictedmem to be a uniquely identifiable mount.
FWIW, I'm starting to look at extending restrictedmem to hugetlbfs and the separation that the current implementation has is very helpful. Also helps that hugetlbfs and tmpfs are structured similarly, I guess.
Quoted 6 lines
One of the goals (hopefully not a pipe dream) is to design restrictmem in such a way that extending it to support other backing types isn't terribly difficult. In case it's not obvious, most of us working on this stuff aren't filesystems experts, and many of us aren't mm experts either. The more we (KVM folks for the most part) can leverage existing code to do the heavy lifting, the better.
Quoted 8 lines
After giving myself a bit of a crash course in file systems, would something like the below have any chance of (a) working, (b) getting merged, and (c) being maintainable?
The idea is similar to a stacking filesystem, but instead of stacking, restrictedmem hijacks a
f_opsanda_opsto create a lightweight shim around tmpfs. There are undoubtedly issues and edge cases, I'm just looking for a quick "yes, this might be doable" or a "no, that's absolutely bonkers, don't try it".
Not an FS expert by any means, but I did think of approaching it this way as well!
"Hijacking" perhaps gives this approach a bit of a negative connotation. I thought this is pretty close to subclassing (as in Object Oriented Programming). When some methods (e.g. fallocate) are called, restrictedmem does some work, and calls the same method in the superclass.
The existing restrictedmem code is a more like instantiating an shmem object and keeping that object as a field within the restrictedmem object.
Some (maybe small) issues I can think of now:
(1)
One difficulty with this approach is that other functions may make assumptions about private_data being of a certain type, or functions may use private_data.
I checked and IIUC neither shmem nor hugetlbfs use the private_data field in the inode's i_mapping (also file's f_mapping).
But there's fs/buffer.c which uses private_data, although those functions seem to be used by FSes like ext4 and fat, not memory-backed FSes.
We can probably fix this if any backing filesystems of restrictedmem, like tmpfs and future ones use private_data.
Could the solution here be to store private_data of the superclass instance in restrictedmem, and then override every method in the superclass that uses private_data to first restore private_data before making the superclass call? Perhaps we can take private_lock to change private_data.
(2)
Perhaps there are other slightly hidden cases that might need cleaning up.
For example, one of the patches in this series amends the shmem_mapping() function from
return mapping->a_ops == &shmem_aops;
to
return mapping->host->i_sb->s_magic == TMPFS_MAGIC;
The former/original is more accurate since it checks a property of the mapping itself instead of checking a property of the mapping's host's superblock.
The impact of changing this guard is more obvious if we now override a_ops but keep the mapping's host's superblock's s_magic.
Specifically for this example, maybe we should handle restrictedmem in the caller (me_pagecache_clean()) specially, in addition to shmem.
Quoted 88 lines
Thanks!
struct restrictedmem { struct rw_semaphore lock; struct file *file; const struct file_operations *backing_f_ops; const struct address_space_operations *backing_a_ops; struct xarray bindings; bool exclusive; };static int
restrictedmem_release(struct inode *inode, struct file *file){ struct restrictedmem *rm = inode->i_mapping->private_data; xa_destroy(&rm->bindings); kfree(rm); WARN_ON_ONCE(rm->backing_f_ops->release); return 0; }static long restrictedmem_punch_hole(struct restrictedmem *rm, int mode,
loff_toffset,loff_tlen){ struct restrictedmem_notifier *notifier; unsigned long index; pgoff_t start, end; int ret; if (!PAGE_ALIGNED(offset) || !PAGE_ALIGNED(len)) return -EINVAL; start = offset >> PAGE_SHIFT; end = (offset + len) >> PAGE_SHIFT; /* * Bindings must be stable across invalidation to ensure the start+end * are balanced. */ down_read(&rm->lock); xa_for_each_range(&rm->bindings, index, notifier, start, end - 1) notifier->ops->invalidate_start(notifier, start, end); ret = rm->backing_f_ops->fallocate(rm->file, mode, offset, len); xa_for_each_range(&rm->bindings, index, notifier, start, end - 1) notifier->ops->invalidate_end(notifier, start, end); up_read(&rm->lock); return ret; }static long restrictedmem_fallocate(struct file *file, int mode,
loff_toffset,loff_tlen){ struct restrictedmem *rm = file->f_mapping->private_data; if (mode & FALLOC_FL_PUNCH_HOLE) return restrictedmem_punch_hole(rm, mode, offset, len); return rm->backing_f_ops->fallocate(file, mode, offset, len); }static int restrictedmem_migrate_folio(struct
address_space*mapping,
struct folio *dst, struct folio *src, enummigrate_mode){ WARN_ON_ONCE(1); return -EINVAL; }static int restrictedmem_error_page(struct
address_space*mapping,
struct page *page){ struct restrictedmem *rm = mapping->private_data; struct restrictedmem_notifier *notifier; unsigned long index; pgoff_t start, end; start = page->index; end = start + thp_nr_pages(page); down_read(&rm->lock);
Quoted 7 lines
xa_for_each_range(&rm->bindings, index, notifier, start, end - 1) notifier->ops->error(notifier, start, end); up_read(&rm->lock); return rm->backing_a_ops->error_remove_page(mapping, page); }
When I was thinking of this I was stuck on handling error_remove_page, because it was looking up the superblock to iterate over the inodes to find the right mapping. Glad to see that the solution is simply to use the given mapping from the arguments!
Quoted 14 lines
static const struct
file_operationsrestrictedmem_fops= {
.release =restrictedmem_release, .fallocate =restrictedmem_fallocate,
};static const struct
address_space_operationsrestrictedmem_aops= {
.dirty_folio =noop_dirty_folio,
#ifdefCONFIG_MIGRATION
.migrate_folio =restrictedmem_migrate_folio,
#endif
.error_remove_page =restrictedmem_error_page,
};static int
restrictedmem_file_create(struct file *file)
Quoted 11 lines
{
struct address_space *mapping = file->f_mapping;
struct restrictedmem *rm;
rm = kzalloc(sizeof(*rm), GFP_KERNEL);
if (!rm)
return -ENOMEM;
rm->backing_f_ops = file->f_op;
rm->backing_a_ops = mapping->a_ops;
rm->file = file;We don't really need to do this, since rm->file is already the same as file, we could just pass the file itself when it's needed
Quoted 7 lines
init_rwsem(&rm->lock); xa_init(&rm->bindings); file->f_flags |= O_LARGEFILE; file->f_op = &restrictedmem_fops; mapping->a_ops = &restrictedmem_aops;
I think we probably have to override inode_operations as well, because otherwise other methods would become available to a restrictedmem file (like link, unlink, mkdir, tmpfile). Or maybe that's a feature instead of a bug.
Quoted 19 lines
mapping_set_unevictable(mapping); mapping_set_unmovable(mapping); mapping_set_gfp_mask(mapping, mapping_gfp_mask(mapping) & ~__GFP_MOVABLE); return 0; }static int
restrictedmem_create(struct vfsmount *mount){ struct file *file; int fd, err; fd = get_unused_fd_flags(0); if (fd < 0) return fd; file = shmem_file_setup_with_mnt(mount, "memfd:restrictedmem", 0, VM_NORESERVE);
Quoted 8 lines
if (IS_ERR(file)) {
err = PTR_ERR(file);
goto err_fd;
}
if (WARN_ON_ONCE(file->private_data)) {
err = -EEXIST;
goto err_fd;
}Did you intend this as a check that the backing filesystem isn't using the private_data field in the mapping?
I think you meant file->f_mapping->private_data.
On this note, we will probably have to fix things whenever any backing filesystems need the private_data field.
Quoted 68 lines
file->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE; file->f_flags |= O_LARGEFILE; err = restrictedmem_file_create(file); if (err) { fput(file); goto err_fd; } fd_install(fd, file); return fd; err_fd: put_unused_fd(fd); return err; }
SYSCALL_DEFINE2(memfd_restricted, unsigned int, flags, int, mount_fd){ struct vfsmount *mnt; struct path *path; struct fd f; int ret; if (flags) return -EINVAL; f = fdget_raw(mount_fd); if (!f.file) return -EBADF; ret = -EINVAL; path = &f.file->f_path; if (path->dentry != path->mnt->mnt_root) goto out; /* Disallow bind-mounts that aren't bind-mounts of the whole filesystem. */ mnt = path->mnt; if (mnt->mnt_root != mnt->mnt_sb->s_root) goto out; /* * The filesystem must be mounted no-execute, executing from guest * private memory in the host is nonsensical and unsafe. */ if (!(mnt->mnt_sb->s_iflags & SB_I_NOEXEC)) goto out; /* Currently only TMPFS is supported as underlying storage. */ if (mnt->mnt_sb->s_magic != TMPFS_MAGIC) goto out; ret = mnt_want_write(mnt); if (ret) goto out; ret = restrictedmem_create(mnt); if (mnt) mnt_drop_write(mnt); out: if (f.file) fdput(f); return ret; }
Sean Christopherson
maintainerQuoted 35 lines · Ackerley Tng
Quoted 11 lines · Sean Christopherson
Quoted 4 lines · Christian Brauner
* by a mount option to tmpfs that makes it act
in this restricted manner then you don't need anioctl()and can get away with regular open calls. Such a tmpfs instance would only create regular, restricted memfds.I'd prefer to not go this route, becuase IIUC, it would require relatively invasive changes to shmem code, and IIUC would require similar changes to other support backings in the future, e.g. hugetlbfs? And as above, I don't think any of the potential use cases need restrictedmem to be a uniquely identifiable mount.
FWIW, I'm starting to look at extending restrictedmem to hugetlbfs and the separation that the current implementation has is very helpful. Also helps that hugetlbfs and tmpfs are structured similarly, I guess.
Quoted 11 lines
One of the goals (hopefully not a pipe dream) is to design restrictmem in such a way that extending it to support other backing types isn't terribly difficult. In case it's not obvious, most of us working on this stuff aren't filesystems experts, and many of us aren't mm experts either. The more we (KVM folks for the most part) can leverage existing code to do the heavy lifting, the better.
After giving myself a bit of a crash course in file systems, would something like the below have any chance of (a) working, (b) getting merged, and (c) being maintainable?
Quoted 5 lines
The idea is similar to a stacking filesystem, but instead of stacking, restrictedmem hijacks a
f_opsanda_opsto create a lightweight shim around tmpfs. There are undoubtedly issues and edge cases, I'm just looking for a quick "yes, this might be doable" or a "no, that's absolutely bonkers, don't try it".
Quoted 4 lines
Not an FS expert by any means, but I did think of approaching it this way as well!
"Hijacking" perhaps gives this approach a bit of a negative connotation.
Heh, commandeer then.
Quoted 20 lines
I thought this is pretty close to subclassing (as in Object Oriented Programming). When some methods (e.g. fallocate) are called, restrictedmem does some work, and calls the same method in the superclass.
The existing restrictedmem code is a more like instantiating an shmem object and keeping that object as a field within the restrictedmem object.
Some (maybe small) issues I can think of now:
(1)
One difficulty with this approach is that other functions may make assumptions about
private_databeing of a certain type, or functions may useprivate_data.I checked and IIUC neither shmem nor hugetlbfs use the
private_datafield in the inode'si_mapping(also file'sf_mapping).
Quoted 6 lines
But there's
fs/buffer.cwhich usesprivate_data, although those functions seem to be used by FSes like ext4 and fat, not memory-backed FSes.We can probably fix this if any backing filesystems of restrictedmem, like tmpfs and future ones use
private_data.
Ya, if we go the route of poking into f_ops and stuff, I would want to add WARN_ON_ONCE() hardening of everything that restrictemem wants to "commandeer" ;-)
Quoted 9 lines
Quoted 8 lines
static int
restrictedmem_file_create(struct file *file){ struct address_space *mapping = file->f_mapping; struct restrictedmem *rm; rm = kzalloc(sizeof(*rm), GFP_KERNEL); if (!rm) return -ENOMEM;
Quoted 6 lines
Quoted 3 lines
rm->backing_f_ops = file->f_op; rm->backing_a_ops = mapping->a_ops; rm->file = file;We don't really need to do this, since
rm->fileis already the same as file, we could just pass the file itself when it's needed
Aha! I was working on getting rid of it, but forgot to go back and do another pass.
Quoted 5 lines
Quoted 4 lines
init_rwsem(&rm->lock); xa_init(&rm->bindings); file->f_flags |= O_LARGEFILE;
Quoted 7 lines
Quoted 2 lines
file->f_op = &restrictedmem_fops; mapping->a_ops = &restrictedmem_aops;I think we probably have to override
inode_operationsas well, because otherwise other methods would become available to a restrictedmem file (like link, unlink, mkdir, tmpfile). Or maybe that's a feature instead of a bug.
I think we want those? What we want to restrict are operations that require read/write/execute access to the file, everything else should be ok. fallocate() is a special case because restrictmem needs to tell KVM to unmap the memory when a hole is punched. I assume ->setattr() needs similar treatment to handle ftruncate()?
I'd love to hear Christian's input on this aspect of things.
Quoted 9 lines
Quoted 4 lines
if (WARN_ON_ONCE(file->private_data)) { err = -EEXIST; goto err_fd; }Did you intend this as a check that the backing filesystem isn't using the
private_datafield in the mapping?I think you meant
file->f_mapping->private_data.
Ya, sounds right. I should have added disclaimers that (a) I wrote this quite quickly and (b) it's compile tested only at this point.
Quoted 2 lines
On this note, we will probably have to fix things whenever any backing filesystems need the
private_datafield.
Yep.
Quoted 3 lines
Quoted 3 lines
f = fdget_raw(mount_fd); if (!f.file) return -EBADF;
...
Quoted 6 lines
Quoted 6 lines
/* * The filesystem must be mounted no-execute, executing from guest * private memory in the host is nonsensical and unsafe. */ if (!(mnt->mnt_sb->s_iflags & SB_I_NOEXEC)) goto out;
Looking at this more closely, I don't think we need to require NOEXEC, things like like execve() should get squashed by virtue of not providing any read/write implementations. And dropping my misguided NOEXEC requirement means there's no reason to disallow using the kernel internal mount.
Sean Christopherson
maintainerQuoted 7 lines · Sean Christopherson
Quoted 6 lines · Ackerley Tng
Quoted 4 lines · Sean Christopherson
if (WARN_ON_ONCE(file->private_data)) { err = -EEXIST; goto err_fd; }
Quoted 7 lines
Quoted 4 lines
Did you intend this as a check that the backing filesystem isn't using the
private_datafield in the mapping?I think you meant
file->f_mapping->private_data.Ya, sounds right. I should have added disclaimers that (a) I wrote this quite quickly and (b) it's compile tested only at this point.
FWIW, here's a very lightly tested version that doesn't explode on a basic selftest.
Christian Brauner
maintainerQuoted 22 lines · Sean Christopherson
Quoted 21 lines · Christian Brauner
Quoted 19 lines · Kirill A . Shutemov
Quoted 13 lines · Hugh Dickins
Here's what I would prefer, and imagine much easier for you to maintain; but I'm no system designer, and may be misunderstanding throughout.
QEMU gets fd from opening
/dev/kvm_something, uses ioctls (or perhaps the fallocate syscall interface itself) to allocate and free the memory, ioctl for initializing some of it too. KVM in control of whether that fd can be read or written or mmap'ed or whatever, no need to prevent it inshmem.c, no need for flags, seals, notifications to and fro because KVM is already in control and knows the history. If shmem actually has value, call into it underneath - somewhat like SysV SHM, and/dev/zerommap, and i915/gem make use of it underneath. If shmem has nothing to add, just allocate and free kernel memory directly, recorded in your own xarray.I guess shim layer on top of shmem *can* work. I don't see immediately why it would not. But I'm not sure it is right direction. We risk creating yet another parallel VM with own rules/locking/accounting that opaque to core-mm.
Quoted 4 lines
Quoted 1 line
Sorry for necrobumping this thread but I've been reviewing the
No worries, I'm just stoked someone who actually knows what they're doing is chiming in :-)
It's a dangerous business, going out of your subsystem. You step into code, and if you don't watch your hands, there is no knowing where you might be swept off to.
That saying goes for me here specifically...
Quoted 33 lines
Quoted 15 lines
memfd_restricted()extension that Ackerley is currently working on. I was pointed to this thread as this is what the extension is building on but I'll reply to both threads here.From a glance at v10,
memfd_restricted()is currently implemented as an in-kernel stacking filesystem. A call tomemfd_restricted()creates a new restricted memfd file and a new unlinked tmpfs file and stashes the tmpfs file into the memfd file's private data member. It then uses the tmpfs file'sf_opsandi_opsto perform the relevant file and inode operations. So it has the same callstack as a general stacking filesystem like overlayfs in some cases:memfd_restricted->getattr() -> tmpfs->getattr()...
Quoted 15 lines
Since you're effectively acting like a stacking filesystem you should really use the device number of your memfd restricted filesystem. IOW, sm like:
stat->dev = memfd_restricted_dentry->d_sb->s_dev;But then you run into trouble if you want to go forward with Ackerley's extension that allows to explicitly pass in tmpfs fds to
memfd_restricted(). Afaict, two tmpfs instances might allocate the same inode number. So now the inode and device number pair isn't unique anymore.So you might best be served by allocating and reporting your own inode numbers as well.
Quoted 7 lines
Quoted 3 lines
But if you want to preserve the inode number and device number of the relevant tmpfs instance but still report memfd restricted as your filesystem type
Unless I missed something along the way, reporting
memfd_restrictedas a distinct filesystem is very much a non-goal. AFAIK it's purely a side effect of the proposed implementation.
In the current implementation you would have to put in effort to fake this. For example, you would need to also implement ->statfs super_operation where you'd need to fill in the details of the tmpfs instance. At that point all that memfd_restricted fs code that you've written is nothing but deadweight, I would reckon.
Quoted 20 lines
Quoted 14 lines
then I think it's reasonable to ask whether a stacking implementation really makes sense here.
If you extend
memfd_restricted()or even consider extending it in the future to take tmpfs file descriptors as arguments to identify the tmpfs instance in which to allocate the underlying tmpfs file for the new restricted memfd file you should really consider a tmpfs based implementation.Because at that point it just feels like a pointless wrapper to get custom
f_opsandi_ops. Plus it's wasteful because you allocate dentries and inodes that you don't really care about at all.Quoted 5 lines
Just off the top of my hat you might be better served:
* by a newioctl()on tmpfs instances that
yield regular tmpfs file descriptors with restrictedf_opsandi_ops. That's not that different from btrfs subvolumes which effectively are directories but are created through anioctl().
Quoted 3 lines
I think this is more or less what we want to do, except via a dedicated syscall instead of an
ioctl()so that the primary interface isn't strictly tied to tmpfs, e.g. so that it can be extended to other backing types in the future.
Ok. But just to point this out, this would make memfd_restricted() a multiplexer on types of memory. And my wild guess is that not all memory types you might reasonably want to use will have a filesystem like interface such. So in the future you might end up with multiple ways of specifying the type of memory:
// use tmpfs backingmemfd_restricted(fd_tmpfs, 0);
// use hugetlbfs backingmemfd_restricted(fd_hugetlbfs, 0);
// use non-fs type memory backing memfd_restricted(-EBADF, MEMFD_SUPER_FANCY_MEMORY_TYPE);
interface wise I find an unpleasant design. But that multi-memory-open goal also makes it a bit hard to come up with a clean design (On possibility would be to use an extensible struct - versioned by size - similar to openat2() and clone3() such that you can specify all types of options on the memory in the future.).
Quoted 10 lines
Quoted 5 lines
* by a mount option to tmpfs that makes it act
in this restricted manner then you don't need anioctl()and can get away with regular open calls. Such a tmpfs instance would only create regular, restricted memfds.I'd prefer to not go this route, becuase IIUC, it would require relatively invasive changes to shmem code, and IIUC would require similar changes to other support backings in the future, e.g. hugetlbfs? And as above, I don't think any of the potential use cases need restrictedmem to be a uniquely identifiable mount.
Ok, see my comment above then.
Quoted 3 lines
One of the goals (hopefully not a pipe dream) is to design restrictmem in such a way that extending it to support other backing types isn't terribly difficult.
Not necessarily difficult, just difficult to do tastefully imho. But it's not that has traditionally held people back. ;)
Quoted 3 lines
In case it's not obvious, most of us working on this stuff aren't filesystems experts, and many of us aren't mm experts either. The more we (KVM folks for the most part) can leverage existing code to do the heavy lifting, the better.
Well, hopefully we can complement each other's knowledge here.
Quoted 9 lines
After giving myself a bit of a crash course in file systems, would something like the below have any chance of (a) working, (b) getting merged, and (c) being maintainable?
The idea is similar to a stacking filesystem, but instead of stacking, restrictedmem hijacks a
f_opsanda_opsto create a lightweight shim around tmpfs. There are undoubtedly issues and edge cases, I'm just looking for a quick "yes, this might be doable" or a "no, that's absolutely bonkers, don't try it".
Maybe, but I think it's weird. _Replacing_ f_ops isn't something that's unprecedented. It happens everytime a character device is opened (see fs/char_dev.c:chrdev_open()). And debugfs does a similar (much more involved) thing where it replaces it's proxy f_ops with the relevant subsystem's f_ops. The difference is that in both cases the replace happens at ->open() time; and the replace is done once. Afterwards only the newly added f_ops are relevant.
In your case you'd be keeping two sets of {f,a}_ops; one usable by userspace and another only usable by in-kernel consumers. And there are some concerns (non-exhaustive list), I think:
* {f,a}_ops weren't designed for this. IOW, one set of {f,a}_ops is authoritative per @file and it is left to the individual subsystems to maintain driver specific ops (see the sunrpc stuff or sockets).
* lifetime management for the two sets of {f,a}_ops: If the ops belong to a module then you need to make sure that the module can't get unloaded while you're using the fops. Might not be a concern in this case.
* brittleness: Not all f_ops for example deal with userspace functionality some deal with cleanup when the file is closed like ->release(). So it's delicate to override that functionality with custom f_ops. Restricted memfds could easily forget to cleanup resources.
* Potential for confusion why there's two sets of {f,a}_ops.
* f_ops specifically are generic across a vast amount of consumers and are subject to change. If memfd_restricted() has specific requirements because of this weird double-use they won't be taken into account.
I find this hard to navigate tbh and it feels like taking a shortcut to avoid building a proper api. If you only care about a specific set of operations specific to memfd restricte that needs to be available to in-kernel consumers, I wonder if you shouldn't just go one step further then your proposal below and build a dedicated minimal ops api. Idk, sketching like a madman on a drawning board here with no claim to feasibility from a mm perspective whatsoever:
struct restrictedmem_ops {
// only contains very limited stuff you need or special stuff
// you nee, similar to struct proto_ops (sockets) and so on
};struct restrictedmem {
const struct restrictedmem_ops ops;
};This would avoid fuzzing with two different set of {f,a}_ops in this brittle way. It would force you to clarify the semantics that you need and the operations that you need or don't need implemented. And it would get rid of the ambiguity inherent to using two sets of {f,a}_ops.
Sean Christopherson
maintainerQuoted 9 lines · Christian Brauner
Quoted 7 lines · Sean Christopherson
Quoted 3 lines
But if you want to preserve the inode number and device number of the relevant tmpfs instance but still report memfd restricted as your filesystem type
Unless I missed something along the way, reporting
memfd_restrictedas a distinct filesystem is very much a non-goal. AFAIK it's purely a side effect of the proposed implementation.
Quoted 5 lines
In the current implementation you would have to put in effort to fake this. For example, you would need to also implement ->statfs
super_operationwhere you'd need to fill in the details of the tmpfs instance. At that point all thatmemfd_restrictedfs code that you've written is nothing but deadweight, I would reckon.
After digging a bit, I suspect the main reason Kirill implemented an overlay to inode_operations was to prevent modifying the file size via ->setattr(). Relying on shmem_setattr() to unmap entries in KVM's MMU wouldn't work because, by design, the memory can't be mmap()'d into host userspace.
if (attr->ia_valid & ATTR_SIZE) {
if (memfd->f_inode->i_size)
return -EPERM;
if (!PAGE_ALIGNED(attr->ia_size))
return -EINVAL;
}But I think we can solve this particular problem by using F_SEAL_{GROW,SHRINK} or SHMEM_LONGPIN. For a variety of reasons, I'm leaning more and more toward making this a KVM ioctl() instead of a dedicated syscall, at which point we can be both more flexible and more draconian, e.g. let userspace provide the file size at the time of creation, but make the size immutable, at least by default.
Quoted 10 lines
Quoted 8 lines
After giving myself a bit of a crash course in file systems, would something like the below have any chance of (a) working, (b) getting merged, and (c) being maintainable?
The idea is similar to a stacking filesystem, but instead of stacking, restrictedmem hijacks a
f_opsanda_opsto create a lightweight shim around tmpfs. There are undoubtedly issues and edge cases, I'm just looking for a quick "yes, this might be doable" or a "no, that's absolutely bonkers, don't try it".Maybe, but I think it's weird.
Yeah, agreed.
Quoted 11 lines
_Replacing_
f_opsisn't something that's unprecedented. It happens everytime a character device is opened (see fs/char_dev.c:chrdev_open()). And debugfs does a similar (much more involved) thing where it replaces it's proxyf_opswith the relevant subsystem'sf_ops. The difference is that in both cases the replace happens at ->open() time; and the replace is done once. Afterwards only the newly addedf_opsare relevant.In your case you'd be keeping two sets of {f,a}_ops; one usable by userspace and another only usable by in-kernel consumers. And there are some concerns (non-exhaustive list), I think:
Quoted 7 lines
* {f,a}_ops weren't designed for this. IOW, one set of {f,a}_ops is authoritative per @file and it is left to the individual subsystems to maintain driver specific ops (see the sunrpc stuff or sockets).
* lifetime management for the two sets of {f,a}_ops: If the ops belong to a module then you need to make sure that the module can't get unloaded while you're using the fops. Might not be a concern in this case.
Ah, whereas I assume the owner of inode_operations is pinned by ??? (dentry?) holding a reference to the inode?
Quoted 10 lines
* brittleness: Not all
f_opsfor example deal with userspace functionality some deal with cleanup when the file is closed like ->release(). So it's delicate to override that functionality with customf_ops. Restricted memfds could easily forget to cleanup resources.
* Potential for confusion why there's two sets of {f,a}_ops.
*f_opsspecifically are generic across a vast amount of consumers and are subject to change. Ifmemfd_restricted()has specific requirements because of this weird double-use they won't be taken into account.
Quoted 2 lines
I find this hard to navigate tbh and it feels like taking a shortcut to avoid building a proper api.
Agreed. At the very least, it would be better to take an explicit dependency on whatever APIs are being used instead of somewhat blindly bouncing through ->fallocate(). I think that gives us a clearer path to getting something merged too, as we'll need Acks on making specific functions visible, i.e. will give MM maintainers something concrete to react too.
Quoted 4 lines
If you only care about a specific set of operations specific to memfd restricte that needs to be available to in-kernel consumers, I wonder if you shouldn't just go one step further then your proposal below and build a dedicated minimal ops api.
This is actually very doable for shmem. Unless I'm missing something, because our use case doesn't allow mmap(), swap, or migration, a good chunk of shmem_fallocate() is simply irrelevant. The result is only ~100 lines of code, and quite straightforward.
My biggest concern, outside of missing a detail in shmem, is adding support for HugeTLBFS, which is likely going to be requested/needed sooner than later. At a glance, hugetlbfs_fallocate() is quite a bit more complex, i.e. not something I'm keen to duplicate. But that's also a future problem to some extent, as it's purely kernel internals; the uAPI side of things doesn't seem like it'll be messy at all.
Thanks again!
Christian Brauner
maintainerQuoted 67 lines · Sean Christopherson
Quoted 9 lines · Christian Brauner
Quoted 7 lines · Sean Christopherson
Quoted 3 lines
But if you want to preserve the inode number and device number of the relevant tmpfs instance but still report memfd restricted as your filesystem type
Unless I missed something along the way, reporting
memfd_restrictedas a distinct filesystem is very much a non-goal. AFAIK it's purely a side effect of the proposed implementation.Quoted 5 lines
In the current implementation you would have to put in effort to fake this. For example, you would need to also implement ->statfs
super_operationwhere you'd need to fill in the details of the tmpfs instance. At that point all thatmemfd_restrictedfs code that you've written is nothing but deadweight, I would reckon.After digging a bit, I suspect the main reason Kirill implemented an overlay to
inode_operationswas to prevent modifying the file size via ->setattr(). Relying onshmem_setattr()to unmap entries in KVM's MMU wouldn't work because, by design, the memory can't be mmap()'d into host userspace.if (attr->ia_valid & ATTR_SIZE) { if (memfd->f_inode->i_size) return -EPERM; if (!PAGE_ALIGNED(attr->ia_size)) return -EINVAL; }But I think we can solve this particular problem by using F_SEAL_{GROW,SHRINK} or
SHMEM_LONGPIN. For a variety of reasons, I'm leaning more and more toward making this a KVMioctl()instead of a dedicated syscall, at which point we can be both more flexible and more draconian, e.g. let userspace provide the file size at the time of creation, but make the size immutable, at least by default.Quoted 10 lines
Quoted 8 lines
After giving myself a bit of a crash course in file systems, would something like the below have any chance of (a) working, (b) getting merged, and (c) being maintainable?
The idea is similar to a stacking filesystem, but instead of stacking, restrictedmem hijacks a
f_opsanda_opsto create a lightweight shim around tmpfs. There are undoubtedly issues and edge cases, I'm just looking for a quick "yes, this might be doable" or a "no, that's absolutely bonkers, don't try it".Maybe, but I think it's weird.
Yeah, agreed.
Quoted 11 lines
_Replacing_
f_opsisn't something that's unprecedented. It happens everytime a character device is opened (see fs/char_dev.c:chrdev_open()). And debugfs does a similar (much more involved) thing where it replaces it's proxyf_opswith the relevant subsystem'sf_ops. The difference is that in both cases the replace happens at ->open() time; and the replace is done once. Afterwards only the newly addedf_opsare relevant.In your case you'd be keeping two sets of {f,a}_ops; one usable by userspace and another only usable by in-kernel consumers. And there are some concerns (non-exhaustive list), I think:
Quoted 7 lines
* {f,a}_ops weren't designed for this. IOW, one set of {f,a}_ops is authoritative per @file and it is left to the individual subsystems to maintain driver specific ops (see the sunrpc stuff or sockets).
* lifetime management for the two sets of {f,a}_ops: If the ops belong to a module then you need to make sure that the module can't get unloaded while you're using the fops. Might not be a concern in this case.
Quoted 2 lines
Ah, whereas I assume the owner of
inode_operationsis pinned by ??? (dentry?) holding a reference to the inode?
I don't think it would be possible to safely replace inode_operations after the inode's been made visible in caches.
It works with file_operations because when a file is opened a new struct file is allocated which isn't reachable anywhere before fd_install() is called. So it is possible to replace f_ops in the default f->f_op->open() method (which is what devices do as the inode is located on e.g., ext4/xfs/tmpfs but the functionality of the device usually provided by some driver/module through its file_operations). The default f_ops are taken from i_fop of the inode.
The lifetime of the file_/inode_operations will be aligned with the lifetime of the module they're originating from. If only file_/inode_operations are used from within the same module then there should never be any lifetime concerns.
So an inode doesn't explictly pin file_/inode_operations because there's usually no need to do that and it be weird if each new inode would take a reference on the f_ops/i_ops on the off-chance that someone _might_ open the file. Let alone the overhead of calling try_module_get() everytime a new inode is added to the cache. There are various fs objects - the superblock which is pinning the filesystem/module - that exceed the lifetime of inodes and dentries. Both also may be dropped from their respective caches and readded later.
Pinning of the module for f_ops is done because it is possible that some filesystem/driver might want to use the file_operations of some other filesystem/driver by default and they are in separate modules. So the fops_get() in do_dentry_open is there because it's not guaranteed that file_/inode_operations originate from the same module as the inode that's opened. If the module is still alive during the open then a reference to its f_ops is taken if not then the open will fail with ENODEV.
That's to the best of my knowledge.
Quoted 30 lines
Quoted 11 lines
* brittleness: Not all
f_opsfor example deal with userspace functionality some deal with cleanup when the file is closed like ->release(). So it's delicate to override that functionality with customf_ops. Restricted memfds could easily forget to cleanup resources.
* Potential for confusion why there's two sets of {f,a}_ops.
*f_opsspecifically are generic across a vast amount of consumers and are subject to change. Ifmemfd_restricted()has specific requirements because of this weird double-use they won't be taken into account.Quoted 2 lines
I find this hard to navigate tbh and it feels like taking a shortcut to avoid building a proper api.
Agreed. At the very least, it would be better to take an explicit dependency on whatever APIs are being used instead of somewhat blindly bouncing through ->fallocate(). I think that gives us a clearer path to getting something merged too, as we'll need Acks on making specific functions visible, i.e. will give MM maintainers something concrete to react too.
Quoted 4 lines
If you only care about a specific set of operations specific to memfd restricte that needs to be available to in-kernel consumers, I wonder if you shouldn't just go one step further then your proposal below and build a dedicated minimal ops api.
This is actually very doable for shmem. Unless I'm missing something, because our use case doesn't allow
mmap(), swap, or migration, a good chunk ofshmem_fallocate()is simply irrelevant. The result is only ~100 lines of code, and quite straightforward.
Quoted 8 lines
My biggest concern, outside of missing a detail in shmem, is adding support for HugeTLBFS, which is likely going to be requested/needed sooner than later. At a glance,
hugetlbfs_fallocate()is quite a bit more complex, i.e. not something I'm keen to duplicate. But that's also a future problem to some extent, as it's purely kernel internals; the uAPI side of things doesn't seem like it'll be messy at all.Thanks again!
Sure thing.
Hi,
Quoted 52 lines · Chao Peng
This is the v7 of this series which tries to implement the fd-based KVM guest private memory. The patches are based on latest kvm/queue branch commit:
b9b71f43683a(kvm/queue) KVM: x86/mmu: Buffer nested MMUsplit_desc_cacheonly by default capacityIntroduction
------------
In general this patch series introduce fd-based memslot which provides guest memory through memory file descriptor fd[offset,size] instead of hva/size. The fd can be created from a supported memory filesystem like tmpfs/hugetlbfs etc. which we refer as memory backing store. KVM and the the memory backing store exchange callbacks when such memslot gets created. At runtime KVM will call into callbacks provided by the backing store to get the pfn with the fd+offset. Memory backing store will also call into KVM callbacks when userspace punch hole on the fd to notify KVM to unmap secondary MMU page table entries.Comparing to existing hva-based memslot, this new type of memslot allows guest memory unmapped from host userspace like QEMU and even the kernel itself, therefore reduce attack surface and prevent bugs.
Based on this fd-based memslot, we can build guest private memory that is going to be used in confidential computing environments such as Intel TDX and AMD SEV. When supported, the memory backing store can provide more enforcement on the fd and KVM can use a single memslot to hold both the private and shared part of the guest memory.
mm extension
---------------------
Introduces newMFD_INACCESSIBLEflag formemfd_create(), the file created with these flags cannotread(),write()ormmap()etc via normal MMU operations. The file content can only be used with the newly introducedmemfile_notifierextension.The
memfile_notifierextension provides two sets of callbacks for KVM to interact with the memory backing store:
-memfile_notifier_ops: callbacks for memory backing store to notify KVM when memory gets invalidated.
- backing store callbacks: callbacks for KVM to call into memory backing store to request memory pages for guest private memory.The
memfile_notifierextension also provides APIs for memory backing store to register/unregister itself and to trigger the notifier when the bookmarked memory gets invalidated.The patchset also introduces a new memfd seal
F_SEAL_AUTO_ALLOCATEto prevent double allocation caused by unintentional guest when we only have a single side of the shared/private memfds effective.
Quoted 8 lines
memslot extension
-----------------
Add the private fd and the fd offset to existing 'shared' memslot so that both private/shared guest memory can live in one single memslot. A page in the memslot is either private or shared. Whether a guest page is private or shared is maintained through reusing existing SEV ioctls KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.
I'm on the Android pKVM team at Google, and we've been looking into how this approach fits with what we've been doing with pkvm/arm64. I've had a go at porting your patches, along with some fixes and additions so it would go on top of our latest pkvm patch series [1] to see how well this proposal fits with what we’re doing. You can find the ported code at this link [2].
In general, an fd-based approach fits very well with pKVM for the reasons you mention. It means that we don't necessarily need to map the guest memory, and with the new extensions it allows the host kernel to control whether to restrict migration and swapping.
For pKVM, we would also need the guest private memory not to be GUP’able by the kernel so that userspace can’t trick the kernel into accessing guest private memory in a context where it isn’t prepared to handle the fault injected by the hypervisor. We’re looking at whether we could use memfd_secret to achieve this, or maybe whether extending your work might solve the problem.
However, during the porting effort, the main issue we've encountered is that many of the details of this approach seem to be targeted at TDX/SEV and don’t readily align with the design of pKVM. My knowledge on TDX is very rudimentary, so please bear with me if I get things wrong.
The idea of the memslot having two references to the backing memory, the (new) private_fd (a file descriptor) as well as the userspace_addr (a memory address), with the meaning changing depending on whether the memory is private or shared. Both can potentially be live at the same time, but only one is used by the guest depending on whether the memory is shared or private. For pKVM, the memory region is the same, and whether the underlying physical page is shared or private is determined by the hypervisor based on the initial configuration of the VM and also in response to hypercalls from the guest. So at least from our side, having a private_fd isn't the best fit, but rather just having an fd instead of a userspace_addr.
Moreover, something which was discussed here before [3], is the ability to share in-place. For pKVM/arm64, the conversion between shared and private involves only changes to the stage-2 page tables, which are controlled by the hypervisor. Android supports this in-place conversion already, and I think that the cost of copying for many use-cases that would involve large amounts of data would be big. We will measure the relative costs in due course, but in the meantime we’re nervous about adopting a new user ABI which doesn’t appear to cater for in-place conversion; having just the fd would simplify that somewhat
In the memfd approach, what is the plan for being able to initialize guest private memory from the host? In my port of this patch series, I've added an fcntl() command that allows setting INACCESSIBLE after the memfd has been created. So the memory can be mapped, initialized, then unmapped. Of course there is no way to enforce that the memory is unmapped from userspace before being used as private memory, but the hypervisor will take care of the stage-2 mapping and so a user access to the private memory would result in a SEGV regardless of the flag
Now, moving on to implementation-specific issues in this patch series that I have encountered:
- There are a couple of small issues in porting the patches, some of which have been mentioned already by others. I will point out the rest in direct replies to these patches.
- MEMFILE_F_UNRECLAIMABLE and MEMFILE_F_UNMOVABLE are never set in this patch series. MFD_INACCESSIBLE only sets MEMFILE_F_USER_INACCESSIBLE. Is this intentional?
- Nothing in this patch series enforces that MFD_INACCESSIBLE or that any of the MEMFILE_F_* flags are set for the file descriptor to be used as a private_fd. Is this also intentional?
Most of us working on pKVM will be at KVM forum Dublin in September, so it would be great if we could have a chat (and/or beer!) face to face sometime during the conference to help us figure out an upstreamable solution for Android
Cheers,
/fuad
[1] https://lore.kernel.org/all/[email protected]/
[2] https://android-kvm.googlesource.com/linux/+/refs/heads/tabba/fdmem
[3] https://lore.kernel.org/all/[email protected]/
Quoted 133 lines
Test
----
To test the new functionalities of this patch TDX patchset is needed. Since TDX patchset has not been merged so I did two kinds of test:(quoted diff) +0
-2- Regresion test on kvm/queue (this patchset) Most new code are not covered. Code also in below repo: https://github.com/chao-p/linux/tree/privmem-v7 - New Funational test on latest TDX code The patch is rebased to latest TDX code and tested the new funcationalities. See below repos: Linux: https://github.com/chao-p/linux/tree/privmem-v7-tdx QEMU: https://github.com/chao-p/qemu/tree/privmem-v7An example QEMU command line for TDX test:
(quoted diff) +0
-4-object tdx-guest,id=tdx,debug=off,sept-ve-disable=off \ -machine confidential-guest-support=tdx \ -object memory-backend-memfd-private,id=ram1,size=${mem} \ -machine memory-backend=ram1Changelog
----------
v7:
- Move the private/shared info from backing store to KVM.
- IntroduceF_SEAL_AUTO_ALLOCATEto avoid double allocation.
- Rework on the sync mechanism between zap/page fault paths.
- Addressed other comments in v6.
v6:
- Re-organzied patch for both mm/KVM parts.
- Added flags formemfile_notifierso its consumers can state their features and memory backing store can check against these flags.
- Put a backing store reference in thememfile_notifierand movepfn_opsinto backing store.
- Only support boot time backing store register.
- Overall KVM part improvement suggested by Sean and some others.
v5:
- Removed userspace visibleF_SEAL_INACCESSIBLE, instead using an in-kernel flag (SHM_F_INACCESSIBLEfor shmem). Private fd can only be created byMFD_INACCESSIBLE.
- Introduced new APIs for backing store to register itself tomemfile_notifierinstead of direct function call.
- Added the accounting and restriction forMFD_INACCESSIBLEmemory.
- Added KVM API doc for new memslot extensions and man page for the newMFD_INACCESSIBLEflag.
- Removed the overlap check for mapping the same file+offset into multiple gfns due to perf consideration, warned in document.
- Addressed other comments in v4.
v4:
- Decoupled the callbacks between KVM/mm from memfd and use new name 'memfile_notifier'.
- Supported register multiple memslots to the same backing store.
- Added per-memslotpfn_opsinstead of per-system.
- Reworked the invalidation part.
- Improved new KVM uAPIs (private memslot extension and memory error) per Sean's suggestions.
- Addressed many other minor fixes for comments from v3.
v3:
- Added locking protection when calling invalidate_page_range/fallocate callbacks.
- Changed memslot structure to keep use useraddr for shared memory.
- Re-organizedF_SEAL_INACCESSIBLEandMEMFD_OPS.
- AddedMFD_INACCESSIBLEflag to forceF_SEAL_INACCESSIBLE.
- Commit message improvement.
- Many small fixes for comments from the last version.Links to previous discussions
-----------------------------
[1] Original design proposal:
https://lkml.kernel.org/kvm/[email protected]/
[2] Updated proposal and RFC patch v1:
https://lkml.kernel.org/linux-fsdevel/[email protected]/
[3] Patch v5: https://lkml.org/lkml/2022/5/19/861Chao Peng (12):
mm: AddF_SEAL_AUTO_ALLOCATEseal to memfd selftests/memfd: Add tests forF_SEAL_AUTO_ALLOCATE
mm: Introducememfile_notifier
mm/memfd: IntroduceMFD_INACCESSIBLEflag
KVM: RenameKVM_PRIVATE_MEM_SLOTStoKVM_INTERNAL_MEM_SLOTS
KVM: Use gfn instead of hva formmu_notifier_retry
KVM: Rename mmu_notifier_*
KVM: Extend the memslot to support fd-based private memory
KVM: AddKVM_EXIT_MEMORY_FAULTexit
KVM: Register/unregister the guest private memory regions
KVM: Handle page fault for private memory
KVM: Enable and exposeKVM_MEM_PRIVATEKirill A. Shutemov (1):
mm/shmem: Supportmemfile_notifierDocumentation/virt/kvm/api.rst | 77 +++++- arch/arm64/kvm/mmu.c | 8 +- arch/mips/include/asm/kvm_host.h | 2 +- arch/mips/kvm/mmu.c | 10 +- arch/powerpc/include/asm/kvm_book3s_64.h | 2 +- arch/powerpc/kvm/book3s_64_mmu_host.c | 4 +- arch/powerpc/kvm/book3s_64_mmu_hv.c | 4 +- arch/powerpc/kvm/book3s_64_mmu_radix.c | 6 +- arch/powerpc/kvm/book3s_hv_nested.c | 2 +- arch/powerpc/kvm/book3s_hv_rm_mmu.c | 8 +- arch/powerpc/kvm/e500_mmu_host.c | 4 +- arch/riscv/kvm/mmu.c | 4 +- arch/x86/include/asm/kvm_host.h | 3 +- arch/x86/kvm/Kconfig | 3 + arch/x86/kvm/mmu.h | 2 - arch/x86/kvm/mmu/mmu.c | 74 +++++- arch/x86/kvm/mmu/mmu_internal.h | 18 ++ arch/x86/kvm/mmu/mmutrace.h | 1 + arch/x86/kvm/mmu/paging_tmpl.h | 4 +- arch/x86/kvm/x86.c | 2 +- include/linux/kvm_host.h | 105 +++++--- include/linux/memfile_notifier.h | 91 +++++++ include/linux/shmem_fs.h | 2 + include/uapi/linux/fcntl.h | 1 + include/uapi/linux/kvm.h | 37 +++ include/uapi/linux/memfd.h | 1 + mm/Kconfig | 4 + mm/Makefile | 1 + mm/memfd.c | 18 +- mm/memfile_notifier.c | 123 ++++++++++ mm/shmem.c | 125 +++++++++- tools/testing/selftests/memfd/memfd_test.c | 166 +++++++++++++ virt/kvm/Kconfig | 3 + virt/kvm/kvm_main.c | 272 ++++++++++++++++++--- virt/kvm/pfncache.c | 14 +- 35 files changed, 1074 insertions(+), 127 deletions(-) create mode 100644 include/linux/memfile_notifier.h create mode 100644 mm/memfile_notifier.c--
2.25.1
Quoted 71 lines · Fuad Tabba
Hi,
Quoted 52 lines · Chao Peng
This is the v7 of this series which tries to implement the fd-based KVM guest private memory. The patches are based on latest kvm/queue branch commit:
b9b71f43683a(kvm/queue) KVM: x86/mmu: Buffer nested MMUsplit_desc_cacheonly by default capacityIntroduction
------------
In general this patch series introduce fd-based memslot which provides guest memory through memory file descriptor fd[offset,size] instead of hva/size. The fd can be created from a supported memory filesystem like tmpfs/hugetlbfs etc. which we refer as memory backing store. KVM and the the memory backing store exchange callbacks when such memslot gets created. At runtime KVM will call into callbacks provided by the backing store to get the pfn with the fd+offset. Memory backing store will also call into KVM callbacks when userspace punch hole on the fd to notify KVM to unmap secondary MMU page table entries.Comparing to existing hva-based memslot, this new type of memslot allows guest memory unmapped from host userspace like QEMU and even the kernel itself, therefore reduce attack surface and prevent bugs.
Based on this fd-based memslot, we can build guest private memory that is going to be used in confidential computing environments such as Intel TDX and AMD SEV. When supported, the memory backing store can provide more enforcement on the fd and KVM can use a single memslot to hold both the private and shared part of the guest memory.
mm extension
---------------------
Introduces newMFD_INACCESSIBLEflag formemfd_create(), the file created with these flags cannotread(),write()ormmap()etc via normal MMU operations. The file content can only be used with the newly introducedmemfile_notifierextension.The
memfile_notifierextension provides two sets of callbacks for KVM to interact with the memory backing store:
-memfile_notifier_ops: callbacks for memory backing store to notify KVM when memory gets invalidated.
- backing store callbacks: callbacks for KVM to call into memory backing store to request memory pages for guest private memory.The
memfile_notifierextension also provides APIs for memory backing store to register/unregister itself and to trigger the notifier when the bookmarked memory gets invalidated.The patchset also introduces a new memfd seal
F_SEAL_AUTO_ALLOCATEto prevent double allocation caused by unintentional guest when we only have a single side of the shared/private memfds effective.Quoted 8 lines
memslot extension
-----------------
Add the private fd and the fd offset to existing 'shared' memslot so that both private/shared guest memory can live in one single memslot. A page in the memslot is either private or shared. Whether a guest page is private or shared is maintained through reusing existing SEV ioctls KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.I'm on the Android pKVM team at Google, and we've been looking into how this approach fits with what we've been doing with pkvm/arm64. I've had a go at porting your patches, along with some fixes and additions so it would go on top of our latest pkvm patch series [1] to see how well this proposal fits with what we’re doing. You can find the ported code at this link [2].
Quoted 4 lines
In general, an fd-based approach fits very well with pKVM for the reasons you mention. It means that we don't necessarily need to map the guest memory, and with the new extensions it allows the host kernel to control whether to restrict migration and swapping.
Good to hear that.
Quoted 7 lines
For pKVM, we would also need the guest private memory not to be GUP’able by the kernel so that userspace can’t trick the kernel into accessing guest private memory in a context where it isn’t prepared to handle the fault injected by the hypervisor. We’re looking at whether we could use
memfd_secretto achieve this, or maybe whether extending your work might solve the problem.
This is interesting and can be a valuable addition to this series.
Quoted 6 lines
However, during the porting effort, the main issue we've encountered is that many of the details of this approach seem to be targeted at TDX/SEV and don’t readily align with the design of pKVM. My knowledge on TDX is very rudimentary, so please bear with me if I get things wrong.
No doubt this series is initially designed for confidential computing usages, but pKVM can definitely extend it if it finds useful.
Quoted 10 lines
The idea of the memslot having two references to the backing memory, the (new)
private_fd(a file descriptor) as well as theuserspace_addr(a memory address), with the meaning changing depending on whether the memory is private or shared. Both can potentially be live at the same time, but only one is used by the guest depending on whether the memory is shared or private. For pKVM, the memory region is the same, and whether the underlying physical page is shared or private is determined by the hypervisor based on the initial configuration of the VM and also in response to hypercalls from the guest.
For confidential computing usages, this is actually the same. The shared or private is determined by initial configuration or guest hypercalls.
Quoted 3 lines
So at least from
our side, having aprivate_fdisn't the best fit, but rather just having an fd instead of auserspace_addr.
Let me understand this a bit: pKVM basically wants to maintain the shared and private memory in only one fd, and not use userspace_addr at all, right? Any blocking for pKVM to use private_fd + userspace_addr instead?
Quoted 11 lines
Moreover, something which was discussed here before [3], is the ability to share in-place. For pKVM/arm64, the conversion between shared and private involves only changes to the stage-2 page tables, which are controlled by the hypervisor. Android supports this in-place conversion already, and I think that the cost of copying for many use-cases that would involve large amounts of data would be big. We will measure the relative costs in due course, but in the meantime we’re nervous about adopting a new user ABI which doesn’t appear to cater for in-place conversion; having just the fd would simplify that somewhat
I understand there is difficulty to achieve that with the current private_fd + userspace_addr (they basically in two separate fds), but is it possible for pKVM to extend this? Brainstorming for example, pKVM can ignore userspace_addr and only use private_fd to cover both shared and private memory, or pKVM introduce new KVM memslot flag?
Quoted 9 lines
In the memfd approach, what is the plan for being able to initialize guest private memory from the host? In my port of this patch series, I've added an
fcntl()command that allows setting INACCESSIBLE after the memfd has been created. So the memory can be mapped, initialized, then unmapped. Of course there is no way to enforce that the memory is unmapped from userspace before being used as private memory, but the hypervisor will take care of the stage-2 mapping and so a user access to the private memory would result in a SEGV regardless of the flag
There is discussion on removing MFD_INACCESSIBLE and delaying the alignment of the flag to the KVM/backing store binding time
(https://lkml.kernel.org/lkml/[email protected]/).
Creating new API like what you are playing with fcntl() also works if it turns out the MFD_INACCESSIBLE has to be set at the memfd_create time.
Quoted 7 lines
Now, moving on to implementation-specific issues in this patch series that I have encountered:
- There are a couple of small issues in porting the patches, some of which have been mentioned already by others. I will point out the rest in direct replies to these patches.
Thanks.
Quoted 4 lines
-
MEMFILE_F_UNRECLAIMABLEandMEMFILE_F_UNMOVABLEare never set in this patch series.MFD_INACCESSIBLEonly setsMEMFILE_F_USER_INACCESSIBLE. Is this intentional?
It gets set in kvm_private_mem_register() of patch 13, basically those flags are expected to be set by architecture code.
Quoted 4 lines
- Nothing in this patch series enforces that
MFD_INACCESSIBLEor that any of the MEMFILE_F_* flags are set for the file descriptor to be used as aprivate_fd. Is this also intentional?
With KVM_MEM_PRIVATE memslot flag, the MEMFILE_F_* are enforced by the architecture code.
Quoted 5 lines
Most of us working on pKVM will be at KVM forum Dublin in September, so it would be great if we could have a chat (and/or beer!) face to face sometime during the conference to help us figure out an upstreamable solution for Android
I would like to, but currently I have no travel plan due to COVID-19 :( We can have more online discussions anyway.
Thanks,
Chao
Quoted 142 lines
Cheers,
/fuad[1] https://lore.kernel.org/all/[email protected]/
[2] https://android-kvm.googlesource.com/linux/+/refs/heads/tabba/fdmem
[3] https://lore.kernel.org/all/[email protected]/Quoted 133 lines
Test
----
To test the new functionalities of this patch TDX patchset is needed. Since TDX patchset has not been merged so I did two kinds of test:(quoted diff) +0
-2- Regresion test on kvm/queue (this patchset) Most new code are not covered. Code also in below repo: https://github.com/chao-p/linux/tree/privmem-v7 - New Funational test on latest TDX code The patch is rebased to latest TDX code and tested the new funcationalities. See below repos: Linux: https://github.com/chao-p/linux/tree/privmem-v7-tdx QEMU: https://github.com/chao-p/qemu/tree/privmem-v7An example QEMU command line for TDX test:
(quoted diff) +0
-4-object tdx-guest,id=tdx,debug=off,sept-ve-disable=off \ -machine confidential-guest-support=tdx \ -object memory-backend-memfd-private,id=ram1,size=${mem} \ -machine memory-backend=ram1Changelog
----------
v7:
- Move the private/shared info from backing store to KVM.
- IntroduceF_SEAL_AUTO_ALLOCATEto avoid double allocation.
- Rework on the sync mechanism between zap/page fault paths.
- Addressed other comments in v6.
v6:
- Re-organzied patch for both mm/KVM parts.
- Added flags formemfile_notifierso its consumers can state their features and memory backing store can check against these flags.
- Put a backing store reference in thememfile_notifierand movepfn_opsinto backing store.
- Only support boot time backing store register.
- Overall KVM part improvement suggested by Sean and some others.
v5:
- Removed userspace visibleF_SEAL_INACCESSIBLE, instead using an in-kernel flag (SHM_F_INACCESSIBLEfor shmem). Private fd can only be created byMFD_INACCESSIBLE.
- Introduced new APIs for backing store to register itself tomemfile_notifierinstead of direct function call.
- Added the accounting and restriction forMFD_INACCESSIBLEmemory.
- Added KVM API doc for new memslot extensions and man page for the newMFD_INACCESSIBLEflag.
- Removed the overlap check for mapping the same file+offset into multiple gfns due to perf consideration, warned in document.
- Addressed other comments in v4.
v4:
- Decoupled the callbacks between KVM/mm from memfd and use new name 'memfile_notifier'.
- Supported register multiple memslots to the same backing store.
- Added per-memslotpfn_opsinstead of per-system.
- Reworked the invalidation part.
- Improved new KVM uAPIs (private memslot extension and memory error) per Sean's suggestions.
- Addressed many other minor fixes for comments from v3.
v3:
- Added locking protection when calling invalidate_page_range/fallocate callbacks.
- Changed memslot structure to keep use useraddr for shared memory.
- Re-organizedF_SEAL_INACCESSIBLEandMEMFD_OPS.
- AddedMFD_INACCESSIBLEflag to forceF_SEAL_INACCESSIBLE.
- Commit message improvement.
- Many small fixes for comments from the last version.Links to previous discussions
-----------------------------
[1] Original design proposal:
https://lkml.kernel.org/kvm/[email protected]/
[2] Updated proposal and RFC patch v1:
https://lkml.kernel.org/linux-fsdevel/[email protected]/
[3] Patch v5: https://lkml.org/lkml/2022/5/19/861Chao Peng (12):
mm: AddF_SEAL_AUTO_ALLOCATEseal to memfd selftests/memfd: Add tests forF_SEAL_AUTO_ALLOCATE
mm: Introducememfile_notifier
mm/memfd: IntroduceMFD_INACCESSIBLEflag
KVM: RenameKVM_PRIVATE_MEM_SLOTStoKVM_INTERNAL_MEM_SLOTS
KVM: Use gfn instead of hva formmu_notifier_retry
KVM: Rename mmu_notifier_*
KVM: Extend the memslot to support fd-based private memory
KVM: AddKVM_EXIT_MEMORY_FAULTexit
KVM: Register/unregister the guest private memory regions
KVM: Handle page fault for private memory
KVM: Enable and exposeKVM_MEM_PRIVATEKirill A. Shutemov (1):
mm/shmem: Supportmemfile_notifierDocumentation/virt/kvm/api.rst | 77 +++++- arch/arm64/kvm/mmu.c | 8 +- arch/mips/include/asm/kvm_host.h | 2 +- arch/mips/kvm/mmu.c | 10 +- arch/powerpc/include/asm/kvm_book3s_64.h | 2 +- arch/powerpc/kvm/book3s_64_mmu_host.c | 4 +- arch/powerpc/kvm/book3s_64_mmu_hv.c | 4 +- arch/powerpc/kvm/book3s_64_mmu_radix.c | 6 +- arch/powerpc/kvm/book3s_hv_nested.c | 2 +- arch/powerpc/kvm/book3s_hv_rm_mmu.c | 8 +- arch/powerpc/kvm/e500_mmu_host.c | 4 +- arch/riscv/kvm/mmu.c | 4 +- arch/x86/include/asm/kvm_host.h | 3 +- arch/x86/kvm/Kconfig | 3 + arch/x86/kvm/mmu.h | 2 - arch/x86/kvm/mmu/mmu.c | 74 +++++- arch/x86/kvm/mmu/mmu_internal.h | 18 ++ arch/x86/kvm/mmu/mmutrace.h | 1 + arch/x86/kvm/mmu/paging_tmpl.h | 4 +- arch/x86/kvm/x86.c | 2 +- include/linux/kvm_host.h | 105 +++++--- include/linux/memfile_notifier.h | 91 +++++++ include/linux/shmem_fs.h | 2 + include/uapi/linux/fcntl.h | 1 + include/uapi/linux/kvm.h | 37 +++ include/uapi/linux/memfd.h | 1 + mm/Kconfig | 4 + mm/Makefile | 1 + mm/memfd.c | 18 +- mm/memfile_notifier.c | 123 ++++++++++ mm/shmem.c | 125 +++++++++- tools/testing/selftests/memfd/memfd_test.c | 166 +++++++++++++ virt/kvm/Kconfig | 3 + virt/kvm/kvm_main.c | 272 ++++++++++++++++++--- virt/kvm/pfncache.c | 14 +- 35 files changed, 1074 insertions(+), 127 deletions(-) create mode 100644 include/linux/memfile_notifier.h create mode 100644 mm/memfile_notifier.c--
2.25.1
Hi Chao,
Thank you for your reply.
Quoted 81 lines · Chao Peng
Quoted 71 lines · Fuad Tabba
Hi,
Quoted 52 lines · Chao Peng
This is the v7 of this series which tries to implement the fd-based KVM guest private memory. The patches are based on latest kvm/queue branch commit:
b9b71f43683a(kvm/queue) KVM: x86/mmu: Buffer nested MMUsplit_desc_cacheonly by default capacityIntroduction
------------
In general this patch series introduce fd-based memslot which provides guest memory through memory file descriptor fd[offset,size] instead of hva/size. The fd can be created from a supported memory filesystem like tmpfs/hugetlbfs etc. which we refer as memory backing store. KVM and the the memory backing store exchange callbacks when such memslot gets created. At runtime KVM will call into callbacks provided by the backing store to get the pfn with the fd+offset. Memory backing store will also call into KVM callbacks when userspace punch hole on the fd to notify KVM to unmap secondary MMU page table entries.Comparing to existing hva-based memslot, this new type of memslot allows guest memory unmapped from host userspace like QEMU and even the kernel itself, therefore reduce attack surface and prevent bugs.
Based on this fd-based memslot, we can build guest private memory that is going to be used in confidential computing environments such as Intel TDX and AMD SEV. When supported, the memory backing store can provide more enforcement on the fd and KVM can use a single memslot to hold both the private and shared part of the guest memory.
mm extension
---------------------
Introduces newMFD_INACCESSIBLEflag formemfd_create(), the file created with these flags cannotread(),write()ormmap()etc via normal MMU operations. The file content can only be used with the newly introducedmemfile_notifierextension.The
memfile_notifierextension provides two sets of callbacks for KVM to interact with the memory backing store:
-memfile_notifier_ops: callbacks for memory backing store to notify KVM when memory gets invalidated.
- backing store callbacks: callbacks for KVM to call into memory backing store to request memory pages for guest private memory.The
memfile_notifierextension also provides APIs for memory backing store to register/unregister itself and to trigger the notifier when the bookmarked memory gets invalidated.The patchset also introduces a new memfd seal
F_SEAL_AUTO_ALLOCATEto prevent double allocation caused by unintentional guest when we only have a single side of the shared/private memfds effective.Quoted 8 lines
memslot extension
-----------------
Add the private fd and the fd offset to existing 'shared' memslot so that both private/shared guest memory can live in one single memslot. A page in the memslot is either private or shared. Whether a guest page is private or shared is maintained through reusing existing SEV ioctls KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.I'm on the Android pKVM team at Google, and we've been looking into how this approach fits with what we've been doing with pkvm/arm64. I've had a go at porting your patches, along with some fixes and additions so it would go on top of our latest pkvm patch series [1] to see how well this proposal fits with what we’re doing. You can find the ported code at this link [2].
Quoted 4 lines
In general, an fd-based approach fits very well with pKVM for the reasons you mention. It means that we don't necessarily need to map the guest memory, and with the new extensions it allows the host kernel to control whether to restrict migration and swapping.
Good to hear that.
Quoted 1 line
Quoted 8 lines
Quoted 6 lines
For pKVM, we would also need the guest private memory not to be GUP’able by the kernel so that userspace can’t trick the kernel into accessing guest private memory in a context where it isn’t prepared to handle the fault injected by the hypervisor. We’re looking at whether we could use
memfd_secretto achieve this, or maybe whether extending your work might solve the problem.This is interesting and can be a valuable addition to this series.
I'll keep you posted as it goes. I think with the work that you've already put in, it wouldn't require that much more.
Quoted 44 lines
Quoted 6 lines
However, during the porting effort, the main issue we've encountered is that many of the details of this approach seem to be targeted at TDX/SEV and don’t readily align with the design of pKVM. My knowledge on TDX is very rudimentary, so please bear with me if I get things wrong.
No doubt this series is initially designed for confidential computing usages, but pKVM can definitely extend it if it finds useful.
Quoted 10 lines
The idea of the memslot having two references to the backing memory, the (new)
private_fd(a file descriptor) as well as theuserspace_addr(a memory address), with the meaning changing depending on whether the memory is private or shared. Both can potentially be live at the same time, but only one is used by the guest depending on whether the memory is shared or private. For pKVM, the memory region is the same, and whether the underlying physical page is shared or private is determined by the hypervisor based on the initial configuration of the VM and also in response to hypercalls from the guest.For confidential computing usages, this is actually the same. The shared or private is determined by initial configuration or guest hypercalls.
Quoted 3 lines
So at least from
our side, having aprivate_fdisn't the best fit, but rather just having an fd instead of auserspace_addr.Let me understand this a bit: pKVM basically wants to maintain the shared and private memory in only one fd, and not use
userspace_addrat all, right? Any blocking for pKVM to useprivate_fd+userspace_addrinstead?Quoted 11 lines
Moreover, something which was discussed here before [3], is the ability to share in-place. For pKVM/arm64, the conversion between shared and private involves only changes to the stage-2 page tables, which are controlled by the hypervisor. Android supports this in-place conversion already, and I think that the cost of copying for many use-cases that would involve large amounts of data would be big. We will measure the relative costs in due course, but in the meantime we’re nervous about adopting a new user ABI which doesn’t appear to cater for in-place conversion; having just the fd would simplify that somewhat
Quoted 5 lines
I understand there is difficulty to achieve that with the current
private_fd+userspace_addr(they basically in two separate fds), but is it possible for pKVM to extend this? Brainstorming for example, pKVM can ignoreuserspace_addrand only useprivate_fdto cover both shared and private memory, or pKVM introduce new KVM memslot flag?
It's not that there's anything blocking pKVM from doing that. It's that the disconnect of using a memory address for the shared memory, and a file descriptor for the private memory doesn't really make sense for pKVM. I see how it makes sense for TDX and the Intel-specific implementation. It just seems that this is baking in an implementation-specific aspect as a part of the KVM general api, and the worry is that this might have some unintended consequences in the future.
Quoted 10 lines
Quoted 9 lines
In the memfd approach, what is the plan for being able to initialize guest private memory from the host? In my port of this patch series, I've added an
fcntl()command that allows setting INACCESSIBLE after the memfd has been created. So the memory can be mapped, initialized, then unmapped. Of course there is no way to enforce that the memory is unmapped from userspace before being used as private memory, but the hypervisor will take care of the stage-2 mapping and so a user access to the private memory would result in a SEGV regardless of the flag
Quoted 6 lines
There is discussion on removing
MFD_INACCESSIBLEand delaying the alignment of the flag to the KVM/backing store binding time
(https://lkml.kernel.org/lkml/[email protected]/).Creating new API like what you are playing with
fcntl()also works if it turns out theMFD_INACCESSIBLEhas to be set at thememfd_createtime.
That makes sense.
Quoted 19 lines
Quoted 7 lines
Now, moving on to implementation-specific issues in this patch series that I have encountered:
- There are a couple of small issues in porting the patches, some of which have been mentioned already by others. I will point out the rest in direct replies to these patches.
Thanks.
Quoted 4 lines
-
MEMFILE_F_UNRECLAIMABLEandMEMFILE_F_UNMOVABLEare never set in this patch series.MFD_INACCESSIBLEonly setsMEMFILE_F_USER_INACCESSIBLE. Is this intentional?It gets set in
kvm_private_mem_register()of patch 13, basically those flags are expected to be set by architecture code.Quoted 1 line
Quoted 6 lines
Quoted 3 lines
- Nothing in this patch series enforces that
MFD_INACCESSIBLEor that any of the MEMFILE_F_* flags are set for the file descriptor to be used as aprivate_fd. Is this also intentional?With
KVM_MEM_PRIVATEmemslot flag, the MEMFILE_F_* are enforced by the architecture code.
Right. I was expecting them to be in the mem_fd, but I see now how they are being set and enforced in patch 13. This makes a lot of sense now. Thanks!
Quoted 8 lines
Quoted 5 lines
Most of us working on pKVM will be at KVM forum Dublin in September, so it would be great if we could have a chat (and/or beer!) face to face sometime during the conference to help us figure out an upstreamable solution for Android
I would like to, but currently I have no travel plan due to COVID-19 :( We can have more online discussions anyway.
Of course! We'll continue this online, and hopefully we will get a chance to meet in person soon.
Cheers,
/fuad
Quoted 144 lines
Thanks,
ChaoQuoted 142 lines
Cheers,
/fuad[1] https://lore.kernel.org/all/[email protected]/
[2] https://android-kvm.googlesource.com/linux/+/refs/heads/tabba/fdmem
[3] https://lore.kernel.org/all/[email protected]/Quoted 133 lines
Test
----
To test the new functionalities of this patch TDX patchset is needed. Since TDX patchset has not been merged so I did two kinds of test:(quoted diff) +0
-2- Regresion test on kvm/queue (this patchset) Most new code are not covered. Code also in below repo: https://github.com/chao-p/linux/tree/privmem-v7 - New Funational test on latest TDX code The patch is rebased to latest TDX code and tested the new funcationalities. See below repos: Linux: https://github.com/chao-p/linux/tree/privmem-v7-tdx QEMU: https://github.com/chao-p/qemu/tree/privmem-v7An example QEMU command line for TDX test:
(quoted diff) +0
-4-object tdx-guest,id=tdx,debug=off,sept-ve-disable=off \ -machine confidential-guest-support=tdx \ -object memory-backend-memfd-private,id=ram1,size=${mem} \ -machine memory-backend=ram1Changelog
----------
v7:
- Move the private/shared info from backing store to KVM.
- IntroduceF_SEAL_AUTO_ALLOCATEto avoid double allocation.
- Rework on the sync mechanism between zap/page fault paths.
- Addressed other comments in v6.
v6:
- Re-organzied patch for both mm/KVM parts.
- Added flags formemfile_notifierso its consumers can state their features and memory backing store can check against these flags.
- Put a backing store reference in thememfile_notifierand movepfn_opsinto backing store.
- Only support boot time backing store register.
- Overall KVM part improvement suggested by Sean and some others.
v5:
- Removed userspace visibleF_SEAL_INACCESSIBLE, instead using an in-kernel flag (SHM_F_INACCESSIBLEfor shmem). Private fd can only be created byMFD_INACCESSIBLE.
- Introduced new APIs for backing store to register itself tomemfile_notifierinstead of direct function call.
- Added the accounting and restriction forMFD_INACCESSIBLEmemory.
- Added KVM API doc for new memslot extensions and man page for the newMFD_INACCESSIBLEflag.
- Removed the overlap check for mapping the same file+offset into multiple gfns due to perf consideration, warned in document.
- Addressed other comments in v4.
v4:
- Decoupled the callbacks between KVM/mm from memfd and use new name 'memfile_notifier'.
- Supported register multiple memslots to the same backing store.
- Added per-memslotpfn_opsinstead of per-system.
- Reworked the invalidation part.
- Improved new KVM uAPIs (private memslot extension and memory error) per Sean's suggestions.
- Addressed many other minor fixes for comments from v3.
v3:
- Added locking protection when calling invalidate_page_range/fallocate callbacks.
- Changed memslot structure to keep use useraddr for shared memory.
- Re-organizedF_SEAL_INACCESSIBLEandMEMFD_OPS.
- AddedMFD_INACCESSIBLEflag to forceF_SEAL_INACCESSIBLE.
- Commit message improvement.
- Many small fixes for comments from the last version.Links to previous discussions
-----------------------------
[1] Original design proposal:
https://lkml.kernel.org/kvm/[email protected]/
[2] Updated proposal and RFC patch v1:
https://lkml.kernel.org/linux-fsdevel/[email protected]/
[3] Patch v5: https://lkml.org/lkml/2022/5/19/861Chao Peng (12):
mm: AddF_SEAL_AUTO_ALLOCATEseal to memfd selftests/memfd: Add tests forF_SEAL_AUTO_ALLOCATE
mm: Introducememfile_notifier
mm/memfd: IntroduceMFD_INACCESSIBLEflag
KVM: RenameKVM_PRIVATE_MEM_SLOTStoKVM_INTERNAL_MEM_SLOTS
KVM: Use gfn instead of hva formmu_notifier_retry
KVM: Rename mmu_notifier_*
KVM: Extend the memslot to support fd-based private memory
KVM: AddKVM_EXIT_MEMORY_FAULTexit
KVM: Register/unregister the guest private memory regions
KVM: Handle page fault for private memory
KVM: Enable and exposeKVM_MEM_PRIVATEKirill A. Shutemov (1):
mm/shmem: Supportmemfile_notifierDocumentation/virt/kvm/api.rst | 77 +++++- arch/arm64/kvm/mmu.c | 8 +- arch/mips/include/asm/kvm_host.h | 2 +- arch/mips/kvm/mmu.c | 10 +- arch/powerpc/include/asm/kvm_book3s_64.h | 2 +- arch/powerpc/kvm/book3s_64_mmu_host.c | 4 +- arch/powerpc/kvm/book3s_64_mmu_hv.c | 4 +- arch/powerpc/kvm/book3s_64_mmu_radix.c | 6 +- arch/powerpc/kvm/book3s_hv_nested.c | 2 +- arch/powerpc/kvm/book3s_hv_rm_mmu.c | 8 +- arch/powerpc/kvm/e500_mmu_host.c | 4 +- arch/riscv/kvm/mmu.c | 4 +- arch/x86/include/asm/kvm_host.h | 3 +- arch/x86/kvm/Kconfig | 3 + arch/x86/kvm/mmu.h | 2 - arch/x86/kvm/mmu/mmu.c | 74 +++++- arch/x86/kvm/mmu/mmu_internal.h | 18 ++ arch/x86/kvm/mmu/mmutrace.h | 1 + arch/x86/kvm/mmu/paging_tmpl.h | 4 +- arch/x86/kvm/x86.c | 2 +- include/linux/kvm_host.h | 105 +++++--- include/linux/memfile_notifier.h | 91 +++++++ include/linux/shmem_fs.h | 2 + include/uapi/linux/fcntl.h | 1 + include/uapi/linux/kvm.h | 37 +++ include/uapi/linux/memfd.h | 1 + mm/Kconfig | 4 + mm/Makefile | 1 + mm/memfd.c | 18 +- mm/memfile_notifier.c | 123 ++++++++++ mm/shmem.c | 125 +++++++++- tools/testing/selftests/memfd/memfd_test.c | 166 +++++++++++++ virt/kvm/Kconfig | 3 + virt/kvm/kvm_main.c | 272 ++++++++++++++++++--- virt/kvm/pfncache.c | 14 +- 35 files changed, 1074 insertions(+), 127 deletions(-) create mode 100644 include/linux/memfile_notifier.h create mode 100644 mm/memfile_notifier.c--
2.25.1
Quoted 17 lines · Fuad Tabba
Quoted 11 lines
Quoted 10 lines
Moreover, something which was discussed here before [3], is the ability to share in-place. For pKVM/arm64, the conversion between shared and private involves only changes to the stage-2 page tables, which are controlled by the hypervisor. Android supports this in-place conversion already, and I think that the cost of copying for many use-cases that would involve large amounts of data would be big. We will measure the relative costs in due course, but in the meantime we’re nervous about adopting a new user ABI which doesn’t appear to cater for in-place conversion; having just the fd would simplify that somewhat
Quoted 5 lines
I understand there is difficulty to achieve that with the current
private_fd+userspace_addr(they basically in two separate fds), but is it possible for pKVM to extend this? Brainstorming for example, pKVM can ignoreuserspace_addrand only useprivate_fdto cover both shared and private memory, or pKVM introduce new KVM memslot flag?
Quoted 8 lines
It's not that there's anything blocking pKVM from doing that. It's that the disconnect of using a memory address for the shared memory, and a file descriptor for the private memory doesn't really make sense for pKVM. I see how it makes sense for TDX and the Intel-specific implementation. It just seems that this is baking in an implementation-specific aspect as a part of the KVM general api, and the worry is that this might have some unintended consequences in the future.
It's true this API originates from supporting TDX and probably other similar confidential computing(CC) technologies. But if we ever get chance to make it more common to cover more usages like pKVM, I would also like to. The challenge on this point is pKVM diverges a lot from CC usages, putting both shared and private memory in the same fd complicates CC usages. If two things are different enough, I'm also thinking implementation-specific may not be that bad.
Chao
Quoted 23 lines · Chao Peng
This is the v7 of this series which tries to implement the fd-based KVM guest private memory. The patches are based on latest kvm/queue branch commit:
b9b71f43683a(kvm/queue) KVM: x86/mmu: Buffer nested MMUsplit_desc_cacheonly by default capacityIntroduction
------------
In general this patch series introduce fd-based memslot which provides guest memory through memory file descriptor fd[offset,size] instead of hva/size. The fd can be created from a supported memory filesystem like tmpfs/hugetlbfs etc. which we refer as memory backing store. KVM and the the memory backing store exchange callbacks when such memslot gets created. At runtime KVM will call into callbacks provided by the backing store to get the pfn with the fd+offset. Memory backing store will also call into KVM callbacks when userspace punch hole on the fd to notify KVM to unmap secondary MMU page table entries.Comparing to existing hva-based memslot, this new type of memslot allows guest memory unmapped from host userspace like QEMU and even the kernel itself, therefore reduce attack surface and prevent bugs.
Quoted 5 lines
Based on this fd-based memslot, we can build guest private memory that is going to be used in confidential computing environments such as Intel TDX and AMD SEV. When supported, the memory backing store can provide more enforcement on the fd and KVM can use a single memslot to hold both the private and shared part of the guest memory.
Hi everyone,
Just wanted to let you all know that I reserved a slot at the LPC Confidential Computing Microconference to discuss some topics related to unmapped/inaccessible private memory support:
"Unmapped Private Memory for Confidential Guests" Tuesday, Sep 13th, 10:00am (Dublin time)
https://lpc.events/event/16/sessions/133/#20220913
The discussion agenda is still a bit in flux, but one topic I really wanted to cover is how we intend to deal with the kernel directmap for TDX/SNP, where there is a need to either remove or split mappings so that KVM or other kernel threads writing to non-private pages don't run into issues due mappings overlapping with private pages.[1]
Other possible discussion topics:
- guarding against shared->private conversions while KVM is attempting to access a shared page (separate PFN pools for shared/private seems to resolve this nicely, but may not be compatible with things like pKVM where the underlying PFN is the same for shared/private)[2]
- extending KVM_EXIT_MEMORY_FAULT to handle batched requests to better handle things like explicit batched conversions initiated by the guest
It's a short session so not sure how much time we'll actually have to discuss things in detail, but maybe this can at least be a good jumping off point for other discussions.
Thanks, and hope to see you there!
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/lkml/CA+EHjTy6NF=BkCqK0vhXLdtKZMahp55JUMSfxN96-NT3YiMXYQ@mail.gmail.com/
v10 cover KVM: mm: fd-based approach for supporting KVM
This patch series implements KVM guest private memory for confidential computing scenarios like Intel TDX[1]. If a TDX host accesses TDX-protected guest memory, machine check can happen which can further crash the running host system, this is terrible for multi-tenant configurations. The host accesses include those from KVM userspace like QEMU. This series addresses KVM userspace induced crash by introducing new mm and KVM interfaces so KVM userspace can still manage guest memory via a fd-based approach, but it can never access the guest memory content.
The patch series touches both core mm and KVM code. I appreciate Andrew/Hugh and Paolo/Sean can review and pick these patches. Any other reviews are always welcome.
- 01: mm change, target for mm tree
- 02-09: KVM change, target for KVM tree
Given KVM is the only current user for the mm part, I have chatted with Paolo and he is OK to merge the mm change through KVM tree, but reviewed-by/acked-by is still expected from the mm people.
The patches have been verified with Intel TDX environment, but Vishal has done an excellent work on the selftests[4] which are dedicated for this series, making it possible to test this series without innovative hardware and fancy steps of building a VM environment. See Test section below for more info.
Introduction
============
KVM userspace being able to crash the host is horrible. Under current KVM architecture, all guest memory is inherently accessible from KVM userspace and is exposed to the mentioned crash issue. The goal of this series is to provide a solution to align mm and KVM, on a userspace inaccessible approach of exposing guest memory.
Normally, KVM populates secondary page table (e.g. EPT) by using a host virtual address (hva) from core mm page table (e.g. x86 userspace page table). This requires guest memory being mmaped into KVM userspace, but this is also the source where the mentioned crash issue can happen. In theory, apart from those 'shared' memory for device emulation etc, guest memory doesn't have to be mmaped into KVM userspace.
This series introduces fd-based guest memory which will not be mmaped into KVM userspace. KVM populates secondary page table by using a fd/offset pair backed by a memory file system. The fd can be created from a supported memory filesystem like tmpfs/hugetlbfs and KVM can directly interact with them with newly introduced in-kernel interface, therefore remove the KVM userspace from the path of accessing/mmaping the guest memory.
Kirill had a patch [2] to address the same issue in a different way. It tracks guest encrypted memory at the 'struct page' level and relies on HWPOISON to reject the userspace access. The patch has been discussed in several online and offline threads and resulted in a design document [3] which is also the original proposal for this series. Later this patch series evolved as more comments received in community but the major concepts in [3] still hold true so recommend reading.
The patch series may also be useful for other usages, for example, pure software approach may use it to harden itself against unintentional access to guest memory. This series is designed with these usages in mind but doesn't have code directly support them and extension might be needed.
mm change
=========
Introduces a new memfd_restricted system call which can create memory file that is restricted from userspace access via normal MMU operations like read(), write() or mmap() etc and the only way to use it is passing it to a third kernel module like KVM and relying on it to access the fd through the newly added restrictedmem kernel interface. The restrictedmem interface bridges the memory file subsystems (tmpfs/hugetlbfs etc) and their users (KVM in this case) and provides bi-directional communication between them.
KVM change
==========
Extends the KVM memslot to provide guest private (encrypted) memory from a fd. With this extension, a single memslot can maintain both private memory through private fd (restricted_fd/restricted_offset) and shared (unencrypted) memory through userspace mmaped host virtual address (userspace_addr). For a particular guest page, the corresponding page in KVM memslot can be only either private or shared and only one of the shared/private parts of the memslot is visible to guest. For how this new extension is used in QEMU, please refer to kvm_set_phys_mem() in below TDX-enabled QEMU repo.
Introduces new KVM_EXIT_MEMORY_FAULT exit to allow userspace to get the chance on decision-making for shared <-> private memory conversion. The exit can be an implicit conversion in KVM page fault handler or an explicit conversion from guest OS.
Introduces new KVM ioctl KVM_SET_MEMORY_ATTRIBUTES to maintain whether a page is private or shared. This ioctl allows userspace to convert a page between private <-> shared. The data maintained tells the truth whether a guest page is private or shared and this information will be used in KVM page fault handler to decide whether the private or the shared part of the memslot is visible to guest.
Test
====
Ran two kinds of tests:
- Selftests [4] from Vishal and VM boot tests in non-TDX environment Code also in below repo: https://github.com/chao-p/linux/tree/privmem-v10
- Functional tests in TDX capable environment
Tested the new functionalities in TDX environment. Code repos:
Linux: https://github.com/chao-p/linux/tree/privmem-v10-tdx
QEMU: https://github.com/chao-p/qemu/tree/privmem-v10
An example QEMU command line for TDX test:
-object tdx-guest,id=tdx,debug=off,sept-ve-disable=off \
-machine confidential-guest-support=tdx \
-object memory-backend-memfd-private,id=ram1,size=${mem} \
-machine memory-backend=ram1TODO
====
- Page accounting and limiting for encrypted memory
- hugetlbfs support
Changelog
=========
v10:
- mm: hook up restricted_memfd to memory failure and route it to kernel users through .error() callback.
- mm: call invalidate() notifier only for FALLOC_FL_PUNCH_HOLE, i.e. not for allocation.
- KVM: introduce new ioctl KVM_SET_MEMORY_ATTRIBUTES for memory conversion instead of reusing KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.
- KVM: refine gfn-based mmu_notifier_retry() mechanism.
- KVM: improve lpage_info updating code.
- KVM: fix the bug in private memory handling that a private fault may fall into a non-private memslot.
- KVM: handle memory machine check error for fd-based memory.
v9:
- mm: move inaccessible memfd into separated syscall.
- mm: return page instead of pfn_t for inaccessible_get_pfn and remove inaccessible_put_pfn.
- KVM: rename inaccessible/private to restricted and CONFIG change to make the code friendly to pKVM.
- KVM: add invalidate_begin/end pair to fix race contention and revise the lock protection for invalidation path.
- KVM: optimize setting lpage_info for > 2M level by direct accessing lower level's result.
- KVM: avoid load xarray in kvm_mmu_max_mapping_level() and instead let the caller to pass in is_private.
- KVM: API doc improvement.
v8:
- mm: redesign mm part by introducing a shim layer(inaccessible_memfd) in memfd to avoid touch the memory file systems directly.
- mm: exclude F_SEAL_AUTO_ALLOCATE as it is for shared memory and cause confusion in this series, will send out separately.
- doc: exclude the man page change, it's not kernel patch and will send out separately.
- KVM: adapt to use the new mm inaccessible_memfd interface.
- KVM: update lpage_info when setting mem_attr_array to support large page.
- KVM: change from xa_store_range to xa_store for mem_attr_array due to xa_store_range overrides all entries which is not intended behavior for us.
- KVM: refine the mmu_invalidate_retry_gfn mechanism for private page.
- KVM: reorganize KVM_MEMORY_ENCRYPT_{UN,}REG_REGION and private page handling code suggested by Sean.
v7:
- mm: introduce F_SEAL_AUTO_ALLOCATE to avoid double allocation.
- KVM: use KVM_MEMORY_ENCRYPT_{UN,}REG_REGION to record private/shared info.
- KVM: use similar sync mechanism between zap/page fault paths as mmu_notifier for memfile_notifier based invalidation.
v6:
- mm: introduce MEMFILE_F_* flags into memfile_node to allow checking feature consistence among all memfile_notifier users and get rid of internal flags like SHM_F_INACCESSIBLE.
- mm: make pfn_ops callbacks being members of memfile_backing_store and then refer to it directly in memfile_notifier.
- mm: remove backing store unregister.
- mm: remove RLIMIT_MEMLOCK based memory accounting and limiting.
- KVM: reorganize patch sequence for page fault handling and private memory enabling.
v5:
- Add man page for MFD_INACCESSIBLE flag and improve KVM API do for the new memslot extensions.
- mm: introduce memfile_{un}register_backing_store to allow memory backing store to register/unregister it from memfile_notifier.
- mm: remove F_SEAL_INACCESSIBLE, use in-kernel flag (SHM_F_INACCESSIBLE for shmem) instead.
- mm: add memory accounting and limiting (RLIMIT_MEMLOCK based) for MFD_INACCESSIBLE memory.
- KVM: remove the overlap check for mapping the same file+offset into multiple gfns due to perf consideration, warned in document.
v4:
- mm: rename memfd_ops to memfile_notifier and separate it from memfd.c to standalone memfile-notifier.c.
- KVM: move pfn_ops to per-memslot scope from per-vm scope and allow registering multiple memslots to the same memory backing store.
- KVM: add a 'kvm' reference in memslot so that we can recover kvm in memfile_notifier handlers.
- KVM: add 'private_' prefix for the new fields in memslot.
- KVM: reshape the 'type' to 'flag' for kvm_memory_exit
v3:
- Remove 'RFC' prefix.
- Fix race condition between memfile_notifier handlers and kvm destroy.
- mm: introduce MFD_INACCESSIBLE flag for memfd_create() to force setting F_SEAL_INACCESSIBLE when the fd is created.
- KVM: add the shared part of the memslot back to make private/shared pages live in one memslot.
Reference
=========
[1] Intel TDX:
https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html
[2] Kirill's implementation:
https://lore.kernel.org/all/[email protected]/T/
[3] Original design proposal:
https://lore.kernel.org/all/[email protected]/
[4] Selftest:
https://lore.kernel.org/all/[email protected]/
Chao Peng (8):
KVM: Introduce per-page memory attributes
KVM: Extend the memslot to support fd-based private memory
KVM: Add KVM_EXIT_MEMORY_FAULT exit
KVM: Use gfn instead of hva for mmu_notifier_retry
KVM: Unmap existing mappings when change the memory attributes
KVM: Update lpage info when private/shared memory are mixed
KVM: Handle page fault for private memory
KVM: Enable and expose KVM_MEM_PRIVATE
Kirill A. Shutemov (1):
mm: Introduce memfd_restricted system call to create restricted user
memory
Documentation/virt/kvm/api.rst | 125 ++++++- arch/x86/entry/syscalls/syscall_32.tbl | 1 + arch/x86/entry/syscalls/syscall_64.tbl | 1 + arch/x86/include/asm/kvm_host.h | 9 + arch/x86/kvm/Kconfig | 3 + arch/x86/kvm/mmu/mmu.c | 205 ++++++++++- arch/x86/kvm/mmu/mmu_internal.h | 14 +- arch/x86/kvm/mmu/mmutrace.h | 1 + arch/x86/kvm/mmu/tdp_mmu.c | 2 +- arch/x86/kvm/x86.c | 17 +- include/linux/kvm_host.h | 103 +++++- include/linux/restrictedmem.h | 71 ++++ include/linux/syscalls.h | 1 + include/uapi/asm-generic/unistd.h | 5 +- include/uapi/linux/kvm.h | 53 +++ include/uapi/linux/magic.h | 1 + kernel/sys_ni.c | 3 + mm/Kconfig | 4 + mm/Makefile | 1 + mm/memory-failure.c | 3 + mm/restrictedmem.c | 318 +++++++++++++++++ virt/kvm/Kconfig | 6 + virt/kvm/kvm_main.c | 469 +++++++++++++++++++++---- 23 files changed, 1323 insertions(+), 93 deletions(-) create mode 100644 include/linux/restrictedmem.h create mode 100644 mm/restrictedmem.c
base-commit: df0bb47baa95aad133820b149851d5b94cbc6790
Signature · 1 line
2.25.1
PATCH v10 1/9 mm: Introduce memfd_restricted system call to create restricted user memory
From: "Kirill A. Shutemov" <[email protected]>
Introduce 'memfd_restricted' system call with the ability to create memory areas that are restricted from userspace access through ordinary MMU operations (e.g. read/write/mmap). The memory content is expected to be used through the new in-kernel interface by a third kernel module.
memfd_restricted() is useful for scenarios where a file descriptor(fd) can be used as an interface into mm but want to restrict userspace's ability on the fd. Initially it is designed to provide protections for KVM encrypted guest memory.
Normally KVM uses memfd memory via mmapping the memfd into KVM userspace (e.g. QEMU) and then using the mmaped virtual address to setup the mapping in the KVM secondary page table (e.g. EPT). With confidential computing technologies like Intel TDX, the memfd memory may be encrypted with special key for special software domain (e.g. KVM guest) and is not expected to be directly accessed by userspace. Precisely, userspace access to such encrypted memory may lead to host crash so should be prevented.
memfd_restricted() provides semantics required for KVM guest encrypted memory support that a fd created with memfd_restricted() is going to be used as the source of guest memory in confidential computing environment and KVM can directly interact with core-mm without the need to expose the memoy content into KVM userspace.
KVM userspace is still in charge of the lifecycle of the fd. It should pass the created fd to KVM. KVM uses the new restrictedmem_get_page() to obtain the physical memory page and then uses it to populate the KVM secondary page table entries.
The userspace restricted memfd can be fallocate-ed or hole-punched from userspace. When hole-punched, KVM can get notified through invalidate_start/invalidate_end() callbacks, KVM then gets chance to remove any mapped entries of the range in the secondary page tables.
Machine check can happen for memory pages in the restricted memfd, instead of routing this directly to userspace, we call the error() callback that KVM registered. KVM then gets chance to handle it correctly.
memfd_restricted() itself is implemented as a shim layer on top of real memory file systems (currently tmpfs). Pages in restrictedmem are marked as unmovable and unevictable, this is required for current confidential usage. But in future this might be changed.
By default memfd_restricted() prevents userspace read, write and mmap. By defining new bit in the 'flags', it can be extended to support other restricted semantics in the future.
The system call is currently wired up for x86 arch.
--- arch/x86/entry/syscalls/syscall_32.tbl | 1 + arch/x86/entry/syscalls/syscall_64.tbl | 1 + include/linux/restrictedmem.h | 71 ++++++ include/linux/syscalls.h | 1 + include/uapi/asm-generic/unistd.h | 5 +- include/uapi/linux/magic.h | 1 + kernel/sys_ni.c | 3 + mm/Kconfig | 4 + mm/Makefile | 1 + mm/memory-failure.c | 3 + mm/restrictedmem.c | 318 +++++++++++++++++++++++++ 11 files changed, 408 insertions(+), 1 deletion(-) create mode 100644 include/linux/restrictedmem.h create mode 100644 mm/restrictedmem.c
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
@@ -455,3 +455,4 @@ 448 i386 process_mrelease sys_process_mrelease 449 i386 futex_waitv sys_futex_waitv 450 i386 set_mempolicy_home_node sys_set_mempolicy_home_node +451 i386 memfd_restricted sys_memfd_restricted
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
@@ -372,6 +372,7 @@ 448 common process_mrelease sys_process_mrelease 449 common futex_waitv sys_futex_waitv 450 common set_mempolicy_home_node sys_set_mempolicy_home_node +451 common memfd_restricted sys_memfd_restricted # # Due to a historical design error, certain syscalls are numbered differently
include/linux/restrictedmem.h new file +71 -0
71 lines not on this page · raw message
include/linux/syscalls.h +1 -0
@@ -1056,6 +1056,7 @@ asmlinkage long sys_memfd_secret(unsigned int flags);asmlinkage long sys_set_mempolicy_home_node (unsigned long start,unsigned long len,unsigned long home_node,unsigned long flags); +asmlinkage long sys_memfd_restricted (unsigned int flags);/* * Architecture-specific system calls
include/uapi/asm-generic/unistd.h +4 -1
@@ -886,8 +886,11 @@ __SYSCALL(__NR_futex_waitv, sys_futex_waitv)#define __NR_set_mempolicy_home_node 450 __SYSCALL(__NR_set_mempolicy_home_node, sys_set_mempolicy_home_node) +#define __NR_memfd_restricted 451 +__SYSCALL(__NR_memfd_restricted, sys_memfd_restricted) +#undef __NR_syscalls -#define __NR_syscalls 451 +#define __NR_syscalls 452/* * 32 bit systems traditionally used different
include/uapi/linux/magic.h +1 -0
@@ -101,5 +101,6 @@#define DMA_BUF_MAGIC 0x444d4142/* "DMAB" */ #define DEVMEM_MAGIC 0x454d444d/* "DMEM" */ #define SECRETMEM_MAGIC 0x5345434d/* "SECM" */ +#define RESTRICTEDMEM_MAGIC 0x5245534d/* "RESM" */ #endif /* __LINUX_MAGIC_H__ */
kernel/sys_ni.c +3 -0
@@ -360,6 +360,9 @@ COND_SYSCALL(pkey_free);/* memfd_secret */ COND_SYSCALL (memfd_secret); +/* memfd_restricted */ +COND_SYSCALL (memfd_restricted); +/* * Architecture specific weak syscall entries. */
mm/Kconfig +4 -0
@@ -1076,6 +1076,10 @@ config IO_MAPPING config SECRETMEM def_bool ARCH_HAS_SET_DIRECT_MAP && !EMBEDDED +config RESTRICTEDMEM + bool + depends on TMPFS + config ANON_VMA_NAME bool "Anonymous VMA name support" depends on PROC_FS && ADVISE_SYSCALLS && MMU
mm/Makefile +1 -0
@@ -121,6 +121,7 @@ obj-$(CONFIG_PAGE_EXTENSION) += page_ext.o obj-$(CONFIG_PAGE_TABLE_CHECK) += page_table_check.o obj-$(CONFIG_CMA_DEBUGFS) += cma_debug.o obj-$(CONFIG_SECRETMEM) += secretmem.o +obj-$(CONFIG_RESTRICTEDMEM) += restrictedmem.o obj-$(CONFIG_CMA_SYSFS) += cma_sysfs.o obj-$(CONFIG_USERFAULTFD) += userfaultfd.o obj-$(CONFIG_IDLE_PAGE_TRACKING) += page_idle.o
mm/memory-failure.c +3 -0
@@ -62,6 +62,7 @@#include <linux/page-isolation.h> #include <linux/pagewalk.h> #include <linux/shmem_fs.h> +#include <linux/restrictedmem.h> #include "swap.h" #include "internal.h" #include "ras/ras_event.h"
@@ -940,6 +941,8 @@ static int me_pagecache_clean(struct page_state *ps, struct page *p) goto out; } +restrictedmem_error_page (p, mapping); +/* * The shmem page is kept in page cache instead of truncating * so is expected to have an extra refcount after error-handling.
mm/restrictedmem.c new file +318 -0
318 lines not on this page · raw message
Signature · 1 line
2.25.1
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Hi,
Quoted 22 lines · Chao Peng
From: "Kirill A. Shutemov" <[email protected]>
Introduce '
memfd_restricted' system call with the ability to create memory areas that are restricted from userspace access through ordinary MMU operations (e.g. read/write/mmap). The memory content is expected to be used through the new in-kernel interface by a third kernel module.
memfd_restricted()is useful for scenarios where a file descriptor(fd) can be used as an interface into mm but want to restrict userspace's ability on the fd. Initially it is designed to provide protections for KVM encrypted guest memory.Normally KVM uses memfd memory via mmapping the memfd into KVM userspace (e.g. QEMU) and then using the mmaped virtual address to setup the mapping in the KVM secondary page table (e.g. EPT). With confidential computing technologies like Intel TDX, the memfd memory may be encrypted with special key for special software domain (e.g. KVM guest) and is not expected to be directly accessed by userspace. Precisely, userspace access to such encrypted memory may lead to host crash so should be prevented.
Quoted 5 lines
memfd_restricted()provides semantics required for KVM guest encrypted memory support that a fd created withmemfd_restricted()is going to be used as the source of guest memory in confidential computing environment and KVM can directly interact with core-mm without the need to expose the memoy content into KVM userspace.
nit: memory
Quoted 21 lines
KVM userspace is still in charge of the lifecycle of the fd. It should pass the created fd to KVM. KVM uses the new
restrictedmem_get_page()to obtain the physical memory page and then uses it to populate the KVM secondary page table entries.The userspace restricted memfd can be fallocate-ed or hole-punched from userspace. When hole-punched, KVM can get notified through invalidate_start/invalidate_end() callbacks, KVM then gets chance to remove any mapped entries of the range in the secondary page tables.
Machine check can happen for memory pages in the restricted memfd, instead of routing this directly to userspace, we call the
error()callback that KVM registered. KVM then gets chance to handle it correctly.
memfd_restricted()itself is implemented as a shim layer on top of real memory file systems (currently tmpfs). Pages in restrictedmem are marked as unmovable and unevictable, this is required for current confidential usage. But in future this might be changed.
Quoted 5 lines
By default
memfd_restricted()prevents userspace read, write and mmap. By defining new bit in the 'flags', it can be extended to support other restricted semantics in the future.The system call is currently wired up for x86 arch.
After wiring the system call for arm64 (on qemu/arm64):
Cheers,
/fuad
Quoted 546 lines
Signed-off-by Kirill A. Shutemov <[email protected]>Signed-off-by Chao Peng <[email protected]>--- arch/x86/entry/syscalls/syscall_32.tbl | 1 + arch/x86/entry/syscalls/syscall_64.tbl | 1 + include/linux/restrictedmem.h | 71 ++++++ include/linux/syscalls.h | 1 + include/uapi/asm-generic/unistd.h | 5 +- include/uapi/linux/magic.h | 1 + kernel/sys_ni.c | 3 + mm/Kconfig | 4 + mm/Makefile | 1 + mm/memory-failure.c | 3 + mm/restrictedmem.c | 318 +++++++++++++++++++++++++ 11 files changed, 408 insertions(+), 1 deletion(-) create mode 100644 include/linux/restrictedmem.h create mode 100644 mm/restrictedmem.carch/x86/entry/syscalls/syscall_32.tbl +1
-0@@ -455,3 +455,4 @@ 448 i386 process_mrelease sys_process_mrelease 449 i386 futex_waitv sys_futex_waitv 450 i386 set_mempolicy_home_node sys_set_mempolicy_home_node +451 i386 memfd_restricted sys_memfd_restrictedarch/x86/entry/syscalls/syscall_64.tbl +1
-0@@ -372,6 +372,7 @@ 448 common process_mrelease sys_process_mrelease 449 common futex_waitv sys_futex_waitv 450 common set_mempolicy_home_node sys_set_mempolicy_home_node +451 common memfd_restricted sys_memfd_restricted # # Due to a historical design error, certain syscalls are numbered differentlyinclude/linux/restrictedmem.h new file +71
-0@@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _LINUX_RESTRICTEDMEM_H + +#include <linux/file.h> +#include <linux/magic.h> +#include <linux/pfn_t.h> + +struct restrictedmem_notifier ; + +struct restrictedmem_notifier_ops { +void (*invalidate_start)(struct restrictedmem_notifier *notifier, +pgoff_t start,pgoff_t end); +void (*invalidate_end)(struct restrictedmem_notifier *notifier, +pgoff_t start,pgoff_t end); +void (*error)(struct restrictedmem_notifier *notifier, +pgoff_t start,pgoff_t end); +}; + +struct restrictedmem_notifier { +struct list_head list; +const struct restrictedmem_notifier_ops *ops; +}; + +#ifdef CONFIG_RESTRICTEDMEM + +void restrictedmem_register_notifier (struct file *file, +struct restrictedmem_notifier *notifier); +void restrictedmem_unregister_notifier (struct file *file, +struct restrictedmem_notifier *notifier); + +int restrictedmem_get_page (struct file *file,pgoff_t offset, +struct page **pagep,int *order); + +static inline bool file_is_restrictedmem (struct file *file) +{ +return file->f_inode->i_sb->s_magic ==RESTRICTEDMEM_MAGIC ; +} + +void restrictedmem_error_page (struct page *page,struct address_space *mapping); + +#else + +static inline void restrictedmem_register_notifier (struct file *file, +struct restrictedmem_notifier *notifier) +{ +} + +static inline void restrictedmem_unregister_notifier (struct file *file, +struct restrictedmem_notifier *notifier) +{ +} + +static inline int restrictedmem_get_page (struct file *file,pgoff_t offset, +struct page **pagep,int *order) +{ +return -1 ; +} + +static inline bool file_is_restrictedmem (struct file *file) +{ +return false; +} + +static inline void restrictedmem_error_page (struct page *page, +struct address_space *mapping) +{ +} + +#endif /* CONFIG_RESTRICTEDMEM */ + +#endif /* _LINUX_RESTRICTEDMEM_H */ include/linux/syscalls.h +1
-0@@ -1056,6 +1056,7 @@ asmlinkage long sys_memfd_secret(unsigned int flags);asmlinkage long sys_set_mempolicy_home_node (unsigned long start,unsigned long len,unsigned long home_node,unsigned long flags); +asmlinkage long sys_memfd_restricted (unsigned int flags);/* * Architecture-specific system calls include/uapi/asm-generic/unistd.h +4
-1@@ -886,8 +886,11 @@ __SYSCALL(__NR_futex_waitv, sys_futex_waitv)#define __NR_set_mempolicy_home_node 450 __SYSCALL(__NR_set_mempolicy_home_node, sys_set_mempolicy_home_node) +#define __NR_memfd_restricted 451 +__SYSCALL(__NR_memfd_restricted, sys_memfd_restricted) +#undef __NR_syscalls -#define __NR_syscalls 451 +#define __NR_syscalls 452/* * 32 bit systems traditionally used different include/uapi/linux/magic.h +1
-0@@ -101,5 +101,6 @@#define DMA_BUF_MAGIC 0x444d4142/* "DMAB" */ #define DEVMEM_MAGIC 0x454d444d/* "DMEM" */ #define SECRETMEM_MAGIC 0x5345434d/* "SECM" */ +#define RESTRICTEDMEM_MAGIC 0x5245534d/* "RESM" */ #endif /* __LINUX_MAGIC_H__ */ kernel/sys_ni.c +3
-0@@ -360,6 +360,9 @@ COND_SYSCALL(pkey_free);/* memfd_secret */ COND_SYSCALL (memfd_secret); +/* memfd_restricted */ +COND_SYSCALL (memfd_restricted); +/* * Architecture specific weak syscall entries. */ mm/Kconfig +4
-0@@ -1076,6 +1076,10 @@ config IO_MAPPING config SECRETMEM def_bool ARCH_HAS_SET_DIRECT_MAP && !EMBEDDED +config RESTRICTEDMEM + bool + depends on TMPFS + config ANON_VMA_NAME bool "Anonymous VMA name support" depends on PROC_FS && ADVISE_SYSCALLS && MMUmm/Makefile +1
-0@@ -121,6 +121,7 @@ obj-$(CONFIG_PAGE_EXTENSION) += page_ext.o obj-$(CONFIG_PAGE_TABLE_CHECK) += page_table_check.o obj-$(CONFIG_CMA_DEBUGFS) += cma_debug.o obj-$(CONFIG_SECRETMEM) += secretmem.o +obj-$(CONFIG_RESTRICTEDMEM) += restrictedmem.o obj-$(CONFIG_CMA_SYSFS) += cma_sysfs.o obj-$(CONFIG_USERFAULTFD) += userfaultfd.o obj-$(CONFIG_IDLE_PAGE_TRACKING) += page_idle.omm/memory-failure.c +3
-0@@ -62,6 +62,7 @@#include <linux/page-isolation.h> #include <linux/pagewalk.h> #include <linux/shmem_fs.h> +#include <linux/restrictedmem.h> #include "swap.h" #include "internal.h" #include "ras/ras_event.h" @@ -940,6 +941,8 @@ static int me_pagecache_clean(struct page_state *ps, struct page *p) goto out; } +restrictedmem_error_page (p, mapping); +/* * The shmem page is kept in page cache instead of truncating * so is expected to have an extra refcount after error-handling. mm/restrictedmem.c new file +318
-1@@ -0,0 +1,318 @@ +// SPDX-License-Identifier: GPL-2.0 +#include "linux/sbitmap.h" +#include <linux/pagemap.h> +#include <linux/pseudo_fs.h> +#include <linux/shmem_fs.h> +#include <linux/syscalls.h> +#include <uapi/linux/falloc.h> +#include <uapi/linux/magic.h> +#include <linux/restrictedmem.h> + +struct restrictedmem_data { +struct mutex lock; +struct file *memfd; +struct list_head notifiers; +}; + +static void restrictedmem_invalidate_start (struct restrictedmem_data *data, +pgoff_t start,pgoff_t end) +{ +struct restrictedmem_notifier *notifier; + +mutex_lock (&data->lock); +list_for_each_entry (notifier, &data->notifiers, list) { + notifier->ops->invalidate_start (notifier, start, end); + } +mutex_unlock (&data->lock); +} + +static void restrictedmem_invalidate_end (struct restrictedmem_data *data, +pgoff_t start,pgoff_t end) +{ +struct restrictedmem_notifier *notifier; + +mutex_lock (&data->lock); +list_for_each_entry (notifier, &data->notifiers, list) { + notifier->ops->invalidate_end (notifier, start, end); + } +mutex_unlock (&data->lock); +} + +static void restrictedmem_notifier_error (struct restrictedmem_data *data, +pgoff_t start,pgoff_t end) +{ +struct restrictedmem_notifier *notifier; + +mutex_lock (&data->lock); +list_for_each_entry (notifier, &data->notifiers, list) { + notifier->ops->error (notifier, start, end); + } +mutex_unlock (&data->lock); +} + +static int restrictedmem_release (struct inode *inode,struct file *file) +{ +struct restrictedmem_data *data = inode->i_mapping->private_data; + +fput (data->memfd); +kfree (data); +return 0 ; +} + +static long restrictedmem_punch_hole (struct restrictedmem_data *data,int mode, +loff_t offset,loff_t len) +{ +int ret; +pgoff_t start, end; +struct file *memfd = data->memfd; + +if (!PAGE_ALIGNED (offset) || !PAGE_ALIGNED (len)) +return -EINVAL ; + + start = offset >>PAGE_SHIFT ; + end = (offset + len) >>PAGE_SHIFT ; + +restrictedmem_invalidate_start (data, start, end); + ret = memfd->f_op->fallocate (memfd, mode, offset, len); +restrictedmem_invalidate_end (data, start, end); + +return ret; +} + +static long restrictedmem_fallocate (struct file *file,int mode, +loff_t offset,loff_t len) +{ +struct restrictedmem_data *data = file->f_mapping->private_data; +struct file *memfd = data->memfd; + +if (mode &FALLOC_FL_PUNCH_HOLE ) +return restrictedmem_punch_hole (data, mode, offset, len); + +return memfd->f_op->fallocate (memfd, mode, offset, len); +} + +static const struct file_operations restrictedmem_fops = { + .release = restrictedmem_release, + .fallocate = restrictedmem_fallocate, +}; + +static int restrictedmem_getattr (struct user_namespace *mnt_userns, +const struct path *path,struct kstat *stat, +u32 request_mask,unsigned int query_flags) +{ +struct inode *inode =d_inode (path->dentry); +struct restrictedmem_data *data = inode->i_mapping->private_data; +struct file *memfd = data->memfd; + +return memfd->f_inode->i_op->getattr (mnt_userns, path, stat, + request_mask, query_flags); +} + +static int restrictedmem_setattr (struct user_namespace *mnt_userns, +struct dentry *dentry,struct iattr *attr) +{ +struct inode *inode =d_inode (dentry); +struct restrictedmem_data *data = inode->i_mapping->private_data; +struct file *memfd = data->memfd; +int ret; + +if (attr->ia_valid &ATTR_SIZE ) { +if (memfd->f_inode->i_size) +return -EPERM ; + +if (!PAGE_ALIGNED (attr->ia_size)) +return -EINVAL ; + } + + ret = memfd->f_inode->i_op->setattr (mnt_userns, +file_dentry (memfd), attr); +return ret; +} + +static const struct inode_operations restrictedmem_iops = { + .getattr = restrictedmem_getattr, + .setattr = restrictedmem_setattr, +}; + +static int restrictedmem_init_fs_context (struct fs_context *fc) +{ +if (!init_pseudo (fc,RESTRICTEDMEM_MAGIC )) +return -ENOMEM ; + + fc->s_iflags |=SB_I_NOEXEC ; +return 0 ; +} + +static struct file_system_type restrictedmem_fs = { + .owner =THIS_MODULE , + .name ="memfd:restrictedmem" , + .init_fs_context = restrictedmem_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static struct vfsmount *restrictedmem_mnt; + +static __init int restrictedmem_init (void ) +{ + restrictedmem_mnt =kern_mount (&restrictedmem_fs); +if (IS_ERR (restrictedmem_mnt)) +return PTR_ERR (restrictedmem_mnt); +return 0 ; +} +fs_initcall (restrictedmem_init); + +static struct file *restrictedmem_file_create (struct file *memfd) +{ +struct restrictedmem_data *data; +struct address_space *mapping; +struct inode *inode; +struct file *file; + + data =kzalloc (sizeof (*data),GFP_KERNEL ); +if (!data) +return ERR_PTR (-ENOMEM ); + + data->memfd = memfd; +mutex_init (&data->lock); +INIT_LIST_HEAD (&data->notifiers); + + inode =alloc_anon_inode (restrictedmem_mnt->mnt_sb); +if (IS_ERR (inode)) { +kfree (data); +return ERR_CAST (inode); + } + + inode->i_mode |=S_IFREG ; + inode->i_op = &restrictedmem_iops; + inode->i_mapping->private_data = data; + + file =alloc_file_pseudo (inode, restrictedmem_mnt, +"restrictedmem" ,O_RDWR , + &restrictedmem_fops); +if (IS_ERR (file)) { +iput (inode); +kfree (data); +return ERR_CAST (file); + } + + file->f_flags |=O_LARGEFILE ; + +/* +* These pages are currently unmovable so don't place them into movable +* pageblocks (e.g. CMA and ZONE_MOVABLE). +*/ + mapping = memfd->f_mapping; +mapping_set_unevictable (mapping); +mapping_set_gfp_mask (mapping, +mapping_gfp_mask (mapping) & ~__GFP_MOVABLE); + +return file; +} + +SYSCALL_DEFINE1(memfd_restricted, unsigned int, flags) +{ +struct file *file, *restricted_file; +int fd, err; + +if (flags) +return -EINVAL ; + + fd =get_unused_fd_flags (0 ); +if (fd <0 ) +return fd; + + file =shmem_file_setup ("memfd:restrictedmem" ,0 ,VM_NORESERVE ); +if (IS_ERR (file)) { + err =PTR_ERR (file); + goto err_fd; + } + file->f_mode |=FMODE_LSEEK |FMODE_PREAD |FMODE_PWRITE ; + file->f_flags |=O_LARGEFILE ; + + restricted_file =restrictedmem_file_create (file); +if (IS_ERR (restricted_file)) { + err =PTR_ERR (restricted_file); +fput (file); + goto err_fd; + } + +fd_install (fd, restricted_file); +return fd; +err_fd: +put_unused_fd (fd); +return err; +} + +void restrictedmem_register_notifier (struct file *file, +struct restrictedmem_notifier *notifier) +{ +struct restrictedmem_data *data = file->f_mapping->private_data; + +mutex_lock (&data->lock); +list_add (¬ifier->list, &data->notifiers); +mutex_unlock (&data->lock); +} +EXPORT_SYMBOL_GPL (restrictedmem_register_notifier); + +void restrictedmem_unregister_notifier (struct file *file, +struct restrictedmem_notifier *notifier) +{ +struct restrictedmem_data *data = file->f_mapping->private_data; + +mutex_lock (&data->lock); +list_del (¬ifier->list); +mutex_unlock (&data->lock); +} +EXPORT_SYMBOL_GPL (restrictedmem_unregister_notifier); + +int restrictedmem_get_page (struct file *file,pgoff_t offset, +struct page **pagep,int *order) +{ +struct restrictedmem_data *data = file->f_mapping->private_data; +struct file *memfd = data->memfd; +struct folio *folio; +struct page *page; +int ret; + + ret =shmem_get_folio (file_inode (memfd), offset, &folio,SGP_WRITE ); +if (ret) +return ret; + + page =folio_file_page (folio, offset); + *pagep = page; +if (order) + *order =thp_order (compound_head (page)); + +SetPageUptodate (page); +unlock_page (page); + +return 0 ; +} +EXPORT_SYMBOL_GPL (restrictedmem_get_page); + +void restrictedmem_error_page (struct page *page,struct address_space *mapping) +{ +struct super_block *sb = restrictedmem_mnt->mnt_sb; +struct inode *inode, *next; + +if (!shmem_mapping (mapping)) +return ; + +spin_lock (&sb->s_inode_list_lock); +list_for_each_entry_safe (inode, next, &sb->s_inodes, i_sb_list) { +struct restrictedmem_data *data = inode->i_mapping->private_data; +struct file *memfd = data->memfd; + +if (memfd->f_mapping == mapping) { +pgoff_t start, end; + +spin_unlock (&sb->s_inode_list_lock); + + start = page->index; + end = start +thp_nr_pages (page); +restrictedmem_notifier_error (data, start, end); +return ; + } + } +spin_unlock (&sb->s_inode_list_lock); +} --2.25.1
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 25 lines · Fuad Tabba
Hi,
Quoted 22 lines · Chao Peng
From: "Kirill A. Shutemov" <[email protected]>
Introduce '
memfd_restricted' system call with the ability to create memory areas that are restricted from userspace access through ordinary MMU operations (e.g. read/write/mmap). The memory content is expected to be used through the new in-kernel interface by a third kernel module.
memfd_restricted()is useful for scenarios where a file descriptor(fd) can be used as an interface into mm but want to restrict userspace's ability on the fd. Initially it is designed to provide protections for KVM encrypted guest memory.Normally KVM uses memfd memory via mmapping the memfd into KVM userspace (e.g. QEMU) and then using the mmaped virtual address to setup the mapping in the KVM secondary page table (e.g. EPT). With confidential computing technologies like Intel TDX, the memfd memory may be encrypted with special key for special software domain (e.g. KVM guest) and is not expected to be directly accessed by userspace. Precisely, userspace access to such encrypted memory may lead to host crash so should be prevented.
Quoted 7 lines
Quoted 5 lines
memfd_restricted()provides semantics required for KVM guest encrypted memory support that a fd created withmemfd_restricted()is going to be used as the source of guest memory in confidential computing environment and KVM can directly interact with core-mm without the need to expose the memoy content into KVM userspace.nit: memory
Ya!
Quoted 26 lines
Quoted 26 lines
KVM userspace is still in charge of the lifecycle of the fd. It should pass the created fd to KVM. KVM uses the new
restrictedmem_get_page()to obtain the physical memory page and then uses it to populate the KVM secondary page table entries.The userspace restricted memfd can be fallocate-ed or hole-punched from userspace. When hole-punched, KVM can get notified through invalidate_start/invalidate_end() callbacks, KVM then gets chance to remove any mapped entries of the range in the secondary page tables.
Machine check can happen for memory pages in the restricted memfd, instead of routing this directly to userspace, we call the
error()callback that KVM registered. KVM then gets chance to handle it correctly.
memfd_restricted()itself is implemented as a shim layer on top of real memory file systems (currently tmpfs). Pages in restrictedmem are marked as unmovable and unevictable, this is required for current confidential usage. But in future this might be changed.By default
memfd_restricted()prevents userspace read, write and mmap. By defining new bit in the 'flags', it can be extended to support other restricted semantics in the future.
Quoted 5 lines
Quoted 1 line
The system call is currently wired up for x86 arch.
Reviewed-by Fuad Tabba <[email protected]>After wiring the system call for arm64 (on qemu/arm64):
Tested-by Fuad Tabba <[email protected]>
Thanks.
Chao
Quoted 552 lines
Cheers,
/fuadQuoted 546 lines
Signed-off-by Kirill A. Shutemov <[email protected]>Signed-off-by Chao Peng <[email protected]>--- arch/x86/entry/syscalls/syscall_32.tbl | 1 + arch/x86/entry/syscalls/syscall_64.tbl | 1 + include/linux/restrictedmem.h | 71 ++++++ include/linux/syscalls.h | 1 + include/uapi/asm-generic/unistd.h | 5 +- include/uapi/linux/magic.h | 1 + kernel/sys_ni.c | 3 + mm/Kconfig | 4 + mm/Makefile | 1 + mm/memory-failure.c | 3 + mm/restrictedmem.c | 318 +++++++++++++++++++++++++ 11 files changed, 408 insertions(+), 1 deletion(-) create mode 100644 include/linux/restrictedmem.h create mode 100644 mm/restrictedmem.carch/x86/entry/syscalls/syscall_32.tbl +1
-0@@ -455,3 +455,4 @@ 448 i386 process_mrelease sys_process_mrelease 449 i386 futex_waitv sys_futex_waitv 450 i386 set_mempolicy_home_node sys_set_mempolicy_home_node +451 i386 memfd_restricted sys_memfd_restrictedarch/x86/entry/syscalls/syscall_64.tbl +1
-0@@ -372,6 +372,7 @@ 448 common process_mrelease sys_process_mrelease 449 common futex_waitv sys_futex_waitv 450 common set_mempolicy_home_node sys_set_mempolicy_home_node +451 common memfd_restricted sys_memfd_restricted # # Due to a historical design error, certain syscalls are numbered differentlyinclude/linux/restrictedmem.h new file +71
-0@@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _LINUX_RESTRICTEDMEM_H + +#include <linux/file.h> +#include <linux/magic.h> +#include <linux/pfn_t.h> + +struct restrictedmem_notifier ; + +struct restrictedmem_notifier_ops { +void (*invalidate_start)(struct restrictedmem_notifier *notifier, +pgoff_t start,pgoff_t end); +void (*invalidate_end)(struct restrictedmem_notifier *notifier, +pgoff_t start,pgoff_t end); +void (*error)(struct restrictedmem_notifier *notifier, +pgoff_t start,pgoff_t end); +}; + +struct restrictedmem_notifier { +struct list_head list; +const struct restrictedmem_notifier_ops *ops; +}; + +#ifdef CONFIG_RESTRICTEDMEM + +void restrictedmem_register_notifier (struct file *file, +struct restrictedmem_notifier *notifier); +void restrictedmem_unregister_notifier (struct file *file, +struct restrictedmem_notifier *notifier); + +int restrictedmem_get_page (struct file *file,pgoff_t offset, +struct page **pagep,int *order); + +static inline bool file_is_restrictedmem (struct file *file) +{ +return file->f_inode->i_sb->s_magic ==RESTRICTEDMEM_MAGIC ; +} + +void restrictedmem_error_page (struct page *page,struct address_space *mapping); + +#else + +static inline void restrictedmem_register_notifier (struct file *file, +struct restrictedmem_notifier *notifier) +{ +} + +static inline void restrictedmem_unregister_notifier (struct file *file, +struct restrictedmem_notifier *notifier) +{ +} + +static inline int restrictedmem_get_page (struct file *file,pgoff_t offset, +struct page **pagep,int *order) +{ +return -1 ; +} + +static inline bool file_is_restrictedmem (struct file *file) +{ +return false; +} + +static inline void restrictedmem_error_page (struct page *page, +struct address_space *mapping) +{ +} + +#endif /* CONFIG_RESTRICTEDMEM */ + +#endif /* _LINUX_RESTRICTEDMEM_H */ include/linux/syscalls.h +1
-0@@ -1056,6 +1056,7 @@ asmlinkage long sys_memfd_secret(unsigned int flags);asmlinkage long sys_set_mempolicy_home_node (unsigned long start,unsigned long len,unsigned long home_node,unsigned long flags); +asmlinkage long sys_memfd_restricted (unsigned int flags);/* * Architecture-specific system calls include/uapi/asm-generic/unistd.h +4
-1@@ -886,8 +886,11 @@ __SYSCALL(__NR_futex_waitv, sys_futex_waitv)#define __NR_set_mempolicy_home_node 450 __SYSCALL(__NR_set_mempolicy_home_node, sys_set_mempolicy_home_node) +#define __NR_memfd_restricted 451 +__SYSCALL(__NR_memfd_restricted, sys_memfd_restricted) +#undef __NR_syscalls -#define __NR_syscalls 451 +#define __NR_syscalls 452/* * 32 bit systems traditionally used different include/uapi/linux/magic.h +1
-0@@ -101,5 +101,6 @@#define DMA_BUF_MAGIC 0x444d4142/* "DMAB" */ #define DEVMEM_MAGIC 0x454d444d/* "DMEM" */ #define SECRETMEM_MAGIC 0x5345434d/* "SECM" */ +#define RESTRICTEDMEM_MAGIC 0x5245534d/* "RESM" */ #endif /* __LINUX_MAGIC_H__ */ kernel/sys_ni.c +3
-0@@ -360,6 +360,9 @@ COND_SYSCALL(pkey_free);/* memfd_secret */ COND_SYSCALL (memfd_secret); +/* memfd_restricted */ +COND_SYSCALL (memfd_restricted); +/* * Architecture specific weak syscall entries. */ mm/Kconfig +4
-0@@ -1076,6 +1076,10 @@ config IO_MAPPING config SECRETMEM def_bool ARCH_HAS_SET_DIRECT_MAP && !EMBEDDED +config RESTRICTEDMEM + bool + depends on TMPFS + config ANON_VMA_NAME bool "Anonymous VMA name support" depends on PROC_FS && ADVISE_SYSCALLS && MMUmm/Makefile +1
-0@@ -121,6 +121,7 @@ obj-$(CONFIG_PAGE_EXTENSION) += page_ext.o obj-$(CONFIG_PAGE_TABLE_CHECK) += page_table_check.o obj-$(CONFIG_CMA_DEBUGFS) += cma_debug.o obj-$(CONFIG_SECRETMEM) += secretmem.o +obj-$(CONFIG_RESTRICTEDMEM) += restrictedmem.o obj-$(CONFIG_CMA_SYSFS) += cma_sysfs.o obj-$(CONFIG_USERFAULTFD) += userfaultfd.o obj-$(CONFIG_IDLE_PAGE_TRACKING) += page_idle.omm/memory-failure.c +3
-0@@ -62,6 +62,7 @@#include <linux/page-isolation.h> #include <linux/pagewalk.h> #include <linux/shmem_fs.h> +#include <linux/restrictedmem.h> #include "swap.h" #include "internal.h" #include "ras/ras_event.h" @@ -940,6 +941,8 @@ static int me_pagecache_clean(struct page_state *ps, struct page *p) goto out; } +restrictedmem_error_page (p, mapping); +/* * The shmem page is kept in page cache instead of truncating * so is expected to have an extra refcount after error-handling. mm/restrictedmem.c new file +318
-1@@ -0,0 +1,318 @@ +// SPDX-License-Identifier: GPL-2.0 +#include "linux/sbitmap.h" +#include <linux/pagemap.h> +#include <linux/pseudo_fs.h> +#include <linux/shmem_fs.h> +#include <linux/syscalls.h> +#include <uapi/linux/falloc.h> +#include <uapi/linux/magic.h> +#include <linux/restrictedmem.h> + +struct restrictedmem_data { +struct mutex lock; +struct file *memfd; +struct list_head notifiers; +}; + +static void restrictedmem_invalidate_start (struct restrictedmem_data *data, +pgoff_t start,pgoff_t end) +{ +struct restrictedmem_notifier *notifier; + +mutex_lock (&data->lock); +list_for_each_entry (notifier, &data->notifiers, list) { + notifier->ops->invalidate_start (notifier, start, end); + } +mutex_unlock (&data->lock); +} + +static void restrictedmem_invalidate_end (struct restrictedmem_data *data, +pgoff_t start,pgoff_t end) +{ +struct restrictedmem_notifier *notifier; + +mutex_lock (&data->lock); +list_for_each_entry (notifier, &data->notifiers, list) { + notifier->ops->invalidate_end (notifier, start, end); + } +mutex_unlock (&data->lock); +} + +static void restrictedmem_notifier_error (struct restrictedmem_data *data, +pgoff_t start,pgoff_t end) +{ +struct restrictedmem_notifier *notifier; + +mutex_lock (&data->lock); +list_for_each_entry (notifier, &data->notifiers, list) { + notifier->ops->error (notifier, start, end); + } +mutex_unlock (&data->lock); +} + +static int restrictedmem_release (struct inode *inode,struct file *file) +{ +struct restrictedmem_data *data = inode->i_mapping->private_data; + +fput (data->memfd); +kfree (data); +return 0 ; +} + +static long restrictedmem_punch_hole (struct restrictedmem_data *data,int mode, +loff_t offset,loff_t len) +{ +int ret; +pgoff_t start, end; +struct file *memfd = data->memfd; + +if (!PAGE_ALIGNED (offset) || !PAGE_ALIGNED (len)) +return -EINVAL ; + + start = offset >>PAGE_SHIFT ; + end = (offset + len) >>PAGE_SHIFT ; + +restrictedmem_invalidate_start (data, start, end); + ret = memfd->f_op->fallocate (memfd, mode, offset, len); +restrictedmem_invalidate_end (data, start, end); + +return ret; +} + +static long restrictedmem_fallocate (struct file *file,int mode, +loff_t offset,loff_t len) +{ +struct restrictedmem_data *data = file->f_mapping->private_data; +struct file *memfd = data->memfd; + +if (mode &FALLOC_FL_PUNCH_HOLE ) +return restrictedmem_punch_hole (data, mode, offset, len); + +return memfd->f_op->fallocate (memfd, mode, offset, len); +} + +static const struct file_operations restrictedmem_fops = { + .release = restrictedmem_release, + .fallocate = restrictedmem_fallocate, +}; + +static int restrictedmem_getattr (struct user_namespace *mnt_userns, +const struct path *path,struct kstat *stat, +u32 request_mask,unsigned int query_flags) +{ +struct inode *inode =d_inode (path->dentry); +struct restrictedmem_data *data = inode->i_mapping->private_data; +struct file *memfd = data->memfd; + +return memfd->f_inode->i_op->getattr (mnt_userns, path, stat, + request_mask, query_flags); +} + +static int restrictedmem_setattr (struct user_namespace *mnt_userns, +struct dentry *dentry,struct iattr *attr) +{ +struct inode *inode =d_inode (dentry); +struct restrictedmem_data *data = inode->i_mapping->private_data; +struct file *memfd = data->memfd; +int ret; + +if (attr->ia_valid &ATTR_SIZE ) { +if (memfd->f_inode->i_size) +return -EPERM ; + +if (!PAGE_ALIGNED (attr->ia_size)) +return -EINVAL ; + } + + ret = memfd->f_inode->i_op->setattr (mnt_userns, +file_dentry (memfd), attr); +return ret; +} + +static const struct inode_operations restrictedmem_iops = { + .getattr = restrictedmem_getattr, + .setattr = restrictedmem_setattr, +}; + +static int restrictedmem_init_fs_context (struct fs_context *fc) +{ +if (!init_pseudo (fc,RESTRICTEDMEM_MAGIC )) +return -ENOMEM ; + + fc->s_iflags |=SB_I_NOEXEC ; +return 0 ; +} + +static struct file_system_type restrictedmem_fs = { + .owner =THIS_MODULE , + .name ="memfd:restrictedmem" , + .init_fs_context = restrictedmem_init_fs_context, + .kill_sb = kill_anon_super, +}; + +static struct vfsmount *restrictedmem_mnt; + +static __init int restrictedmem_init (void ) +{ + restrictedmem_mnt =kern_mount (&restrictedmem_fs); +if (IS_ERR (restrictedmem_mnt)) +return PTR_ERR (restrictedmem_mnt); +return 0 ; +} +fs_initcall (restrictedmem_init); + +static struct file *restrictedmem_file_create (struct file *memfd) +{ +struct restrictedmem_data *data; +struct address_space *mapping; +struct inode *inode; +struct file *file; + + data =kzalloc (sizeof (*data),GFP_KERNEL ); +if (!data) +return ERR_PTR (-ENOMEM ); + + data->memfd = memfd; +mutex_init (&data->lock); +INIT_LIST_HEAD (&data->notifiers); + + inode =alloc_anon_inode (restrictedmem_mnt->mnt_sb); +if (IS_ERR (inode)) { +kfree (data); +return ERR_CAST (inode); + } + + inode->i_mode |=S_IFREG ; + inode->i_op = &restrictedmem_iops; + inode->i_mapping->private_data = data; + + file =alloc_file_pseudo (inode, restrictedmem_mnt, +"restrictedmem" ,O_RDWR , + &restrictedmem_fops); +if (IS_ERR (file)) { +iput (inode); +kfree (data); +return ERR_CAST (file); + } + + file->f_flags |=O_LARGEFILE ; + +/* +* These pages are currently unmovable so don't place them into movable +* pageblocks (e.g. CMA and ZONE_MOVABLE). +*/ + mapping = memfd->f_mapping; +mapping_set_unevictable (mapping); +mapping_set_gfp_mask (mapping, +mapping_gfp_mask (mapping) & ~__GFP_MOVABLE); + +return file; +} + +SYSCALL_DEFINE1(memfd_restricted, unsigned int, flags) +{ +struct file *file, *restricted_file; +int fd, err; + +if (flags) +return -EINVAL ; + + fd =get_unused_fd_flags (0 ); +if (fd <0 ) +return fd; + + file =shmem_file_setup ("memfd:restrictedmem" ,0 ,VM_NORESERVE ); +if (IS_ERR (file)) { + err =PTR_ERR (file); + goto err_fd; + } + file->f_mode |=FMODE_LSEEK |FMODE_PREAD |FMODE_PWRITE ; + file->f_flags |=O_LARGEFILE ; + + restricted_file =restrictedmem_file_create (file); +if (IS_ERR (restricted_file)) { + err =PTR_ERR (restricted_file); +fput (file); + goto err_fd; + } + +fd_install (fd, restricted_file); +return fd; +err_fd: +put_unused_fd (fd); +return err; +} + +void restrictedmem_register_notifier (struct file *file, +struct restrictedmem_notifier *notifier) +{ +struct restrictedmem_data *data = file->f_mapping->private_data; + +mutex_lock (&data->lock); +list_add (¬ifier->list, &data->notifiers); +mutex_unlock (&data->lock); +} +EXPORT_SYMBOL_GPL (restrictedmem_register_notifier); + +void restrictedmem_unregister_notifier (struct file *file, +struct restrictedmem_notifier *notifier) +{ +struct restrictedmem_data *data = file->f_mapping->private_data; + +mutex_lock (&data->lock); +list_del (¬ifier->list); +mutex_unlock (&data->lock); +} +EXPORT_SYMBOL_GPL (restrictedmem_unregister_notifier); + +int restrictedmem_get_page (struct file *file,pgoff_t offset, +struct page **pagep,int *order) +{ +struct restrictedmem_data *data = file->f_mapping->private_data; +struct file *memfd = data->memfd; +struct folio *folio; +struct page *page; +int ret; + + ret =shmem_get_folio (file_inode (memfd), offset, &folio,SGP_WRITE ); +if (ret) +return ret; + + page =folio_file_page (folio, offset); + *pagep = page; +if (order) + *order =thp_order (compound_head (page)); + +SetPageUptodate (page); +unlock_page (page); + +return 0 ; +} +EXPORT_SYMBOL_GPL (restrictedmem_get_page); + +void restrictedmem_error_page (struct page *page,struct address_space *mapping) +{ +struct super_block *sb = restrictedmem_mnt->mnt_sb; +struct inode *inode, *next; + +if (!shmem_mapping (mapping)) +return ; + +spin_lock (&sb->s_inode_list_lock); +list_for_each_entry_safe (inode, next, &sb->s_inodes, i_sb_list) { +struct restrictedmem_data *data = inode->i_mapping->private_data; +struct file *memfd = data->memfd; + +if (memfd->f_mapping == mapping) { +pgoff_t start, end; + +spin_unlock (&sb->s_inode_list_lock); + + start = page->index; + end = start +thp_nr_pages (page); +restrictedmem_notifier_error (data, start, end); +return ; + } + } +spin_unlock (&sb->s_inode_list_lock); +} --2.25.1
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
In reply to Chao PengQuoted 7 lines
memfd_restricted()itself is implemented as a shim layer on top of real memory file systems (currently tmpfs). Pages in restrictedmem are marked as unmovable and unevictable, this is required for current confidential usage. But in future this might be changed.
I didn't dig full histroy, but I interpret this as we don't support page migration and swapping for restricted memfd for now. IMHO "page marked as unmovable" can be confused with PageMovable(), which is a different thing from this series. It's better to just say something like "those pages cannot be migrated and swapped".
[...]
mm/restrictedmem.c line 207
Quoted 9 lines
mm/restrictedmem.c new file +9
-0+ +/* +* These pages are currently unmovable so don't place them into movable +* pageblocks (e.g. CMA and ZONE_MOVABLE). +*/ + mapping = memfd->f_mapping; +mapping_set_unevictable (mapping); +mapping_set_gfp_mask (mapping, +mapping_gfp_mask (mapping) & ~__GFP_MOVABLE);
But, IIUC removing __GFP_MOVABLE flag here only makes page allocation from non- movable zones, but doesn't necessarily prevent page from being migrated. My first glance is you need to implement either a_ops->migrate_folio() or just get_page() after faulting in the page to prevent.
So I think the comment also needs improvement -- IMHO we can just call out currently those pages cannot be migrated and swapped, which is clearer (and the latter justifies mapping_set_unevictable() clearly).
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 7 lines · Kai
Quoted 7 lines
memfd_restricted()itself is implemented as a shim layer on top of real memory file systems (currently tmpfs). Pages in restrictedmem are marked as unmovable and unevictable, this is required for current confidential usage. But in future this might be changed.
Quoted 5 lines
I didn't dig full histroy, but I interpret this as we don't support page migration and swapping for restricted memfd for now. IMHO "page marked as unmovable" can be confused with
PageMovable(), which is a different thing from this series. It's better to just say something like "those pages cannot be migrated and swapped".
Yes, if that helps some clarification.
Quoted 17 lines
[...]
mm/restrictedmem.c line 207
Quoted 9 lines
mm/restrictedmem.c new file +9
-0+ +/* +* These pages are currently unmovable so don't place them into movable +* pageblocks (e.g. CMA and ZONE_MOVABLE). +*/ + mapping = memfd->f_mapping; +mapping_set_unevictable (mapping); +mapping_set_gfp_mask (mapping, +mapping_gfp_mask (mapping) & ~__GFP_MOVABLE);But, IIUC removing
__GFP_MOVABLEflag here only makes page allocation from non- movable zones, but doesn't necessarily prevent page from being migrated. My first glance is you need to implement eithera_ops->migrate_folio()or justget_page()after faulting in the page to prevent.
The current api restrictedmem_get_page() already does this, after the caller calling it, it holds a reference to the page. The caller then decides when to call put_page() appropriately.
Quoted 4 lines
So I think the comment also needs improvement -- IMHO we can just call out currently those pages cannot be migrated and swapped, which is clearer (and the latter justifies
mapping_set_unevictable()clearly).
Good to me.
Thanks,
Chao
Quoted 2 lines
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 20 lines · Chao Peng
Quoted 19 lines
[...]
mm/restrictedmem.c line 207
Quoted 10 lines
mm/restrictedmem.c new file +3
-0+ +/* +* These pages are currently unmovable so don't place them into movable
mm/restrictedmem.c new file +6
-0+* pageblocks (e.g. CMA and ZONE_MOVABLE). +*/ + mapping = memfd->f_mapping; +mapping_set_unevictable (mapping); +mapping_set_gfp_mask (mapping, + mapping_gfp_mask(mapping) & ~__GFP_MOVABLE);But, IIUC removing
__GFP_MOVABLEflag here only makes page allocation from non-
movable zones, but doesn't necessarily prevent page from being migrated. My first glance is you need to implement eithera_ops->migrate_folio()or justget_page()after faulting in the page to prevent.
Quoted 3 lines
The current api
restrictedmem_get_page()already does this, after the caller calling it, it holds a reference to the page. The caller then decides when to callput_page()appropriately.
I tried to dig some history. Perhaps I am missing something, but it seems Kirill said in v9 that this code doesn't prevent page migration, and we need to increase page refcount in restrictedmem_get_page():
https://lore.kernel.org/linux-mm/[email protected]/
But looking at this series it seems restrictedmem_get_page() in this v10 is identical to the one in v9 (except v10 uses 'folio' instead of 'page')?
Anyway if this is not fixed, then it should be fixed. Otherwise, a comment at the place where page refcount is increased will be helpful to help people understand page migration is actually prevented.
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 25 lines · Kai
Quoted 20 lines · Chao Peng
Quoted 19 lines
[...]
mm/restrictedmem.c line 207
Quoted 10 lines
mm/restrictedmem.c new file +3
-0+ +/* +* These pages are currently unmovable so don't place them into movable
mm/restrictedmem.c new file +6
-0+* pageblocks (e.g. CMA and ZONE_MOVABLE). +*/ + mapping = memfd->f_mapping; +mapping_set_unevictable (mapping); +mapping_set_gfp_mask (mapping, + mapping_gfp_mask(mapping) & ~__GFP_MOVABLE);But, IIUC removing
__GFP_MOVABLEflag here only makes page allocation from non-
movable zones, but doesn't necessarily prevent page from being migrated. My first glance is you need to implement eithera_ops->migrate_folio()or justget_page()after faulting in the page to prevent.Quoted 3 lines
The current api
restrictedmem_get_page()already does this, after the caller calling it, it holds a reference to the page. The caller then decides when to callput_page()appropriately.
Quoted 8 lines
I tried to dig some history. Perhaps I am missing something, but it seems Kirill said in v9 that this code doesn't prevent page migration, and we need to increase page refcount in
restrictedmem_get_page():https://lore.kernel.org/linux-mm/[email protected]/
But looking at this series it seems
restrictedmem_get_page()in this v10 is identical to the one in v9 (except v10 uses 'folio' instead of 'page')?
restrictedmem_get_page() increases page refcount several versions ago so no change in v10 is needed. You probably missed my reply:
https://lore.kernel.org/linux-mm/[email protected]/
The current solution is clear: unless we have better approach, we will let restrictedmem user (KVM in this case) to hold the refcount to prevent page migration.
Thanks,
Chao
Quoted 5 lines
Anyway if this is not fixed, then it should be fixed. Otherwise, a comment at the place where page refcount is increased will be helpful to help people understand page migration is actually prevented.
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 32 lines · Chao Peng
Quoted 31 lines · Kai
Quoted 20 lines · Chao Peng
Quoted 19 lines
[...]
mm/restrictedmem.c line 207
Quoted 10 lines
mm/restrictedmem.c new file +3
-0+ +/* +* These pages are currently unmovable so don't place them into movable
mm/restrictedmem.c new file +6
-0+* pageblocks (e.g. CMA and ZONE_MOVABLE). +*/ + mapping = memfd->f_mapping; +mapping_set_unevictable (mapping); +mapping_set_gfp_mask (mapping, + mapping_gfp_mask(mapping) & ~__GFP_MOVABLE);But, IIUC removing
__GFP_MOVABLEflag here only makes page allocation from non-
movable zones, but doesn't necessarily prevent page from being migrated. My first glance is you need to implement eithera_ops->migrate_folio()or justget_page()after faulting in the page to prevent.Quoted 3 lines
The current api
restrictedmem_get_page()already does this, after the caller calling it, it holds a reference to the page. The caller then decides when to callput_page()appropriately.I tried to dig some history. Perhaps I am missing something, but it seems Kirill said in v9 that this code doesn't prevent page migration, and we need to increase page refcount in
restrictedmem_get_page():
Quoted 7 lines
Quoted 2 lines
But looking at this series it seems
restrictedmem_get_page()in this v10 is identical to the one in v9 (except v10 uses 'folio' instead of 'page')?
restrictedmem_get_page()increases page refcount several versions ago so no change in v10 is needed. You probably missed my reply:
But for non-restricted-mem case, it is correct for KVM to decrease page's refcount after setting up mapping in the secondary mmu, otherwise the page will be pinned by KVM for normal VM (since KVM uses GUP to get the page).
So what we are expecting is: for KVM if the page comes from restricted mem, then KVM cannot decrease the refcount, otherwise for normal page via GUP KVM should.
Quoted 5 lines
The current solution is clear: unless we have better approach, we will let restrictedmem user (KVM in this case) to hold the refcount to prevent page migration.
OK. Will leave to others :)
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 36 lines · Kai
Quoted 35 lines · Chao Peng
Quoted 33 lines · Kai
Quoted 20 lines · Chao Peng
Quoted 19 lines
[...]
mm/restrictedmem.c line 207
Quoted 10 lines
mm/restrictedmem.c new file +3
-0+ +/* +* These pages are currently unmovable so don't place them into movable
mm/restrictedmem.c new file +6
-0+* pageblocks (e.g. CMA and ZONE_MOVABLE). +*/ + mapping = memfd->f_mapping; +mapping_set_unevictable (mapping); +mapping_set_gfp_mask (mapping, + mapping_gfp_mask(mapping) & ~__GFP_MOVABLE);But, IIUC removing
__GFP_MOVABLEflag here only makes page allocation from non-
movable zones, but doesn't necessarily prevent page from being migrated. My first glance is you need to implement eithera_ops->migrate_folio()or justget_page()after faulting in the page to prevent.Quoted 3 lines
The current api
restrictedmem_get_page()already does this, after the caller calling it, it holds a reference to the page. The caller then decides when to callput_page()appropriately.I tried to dig some history. Perhaps I am missing something, but it seems Kirill said in v9 that this code doesn't prevent page migration, and we need to increase page refcount in
restrictedmem_get_page():https://lore.kernel.org/linux-mm/[email protected]/
But looking at this series it seems
restrictedmem_get_page()in this v10 is identical to the one in v9 (except v10 uses 'folio' instead of 'page')?
Quoted 8 lines
Quoted 4 lines
restrictedmem_get_page()increases page refcount several versions ago so no change in v10 is needed. You probably missed my reply:But for non-restricted-mem case, it is correct for KVM to decrease page's refcount after setting up mapping in the secondary mmu, otherwise the page will be pinned by KVM for normal VM (since KVM uses GUP to get the page).
That's true. Actually even true for restrictedmem case, most likely we will still need the kvm_release_pfn_clean() for KVM generic code. On one side, other restrictedmem users like pKVM may not require page pinning at all. On the other side, see below.
Quoted 3 lines
So what we are expecting is: for KVM if the page comes from restricted mem, then KVM cannot decrease the refcount, otherwise for normal page via GUP KVM should.
I argue that this page pinning (or page migration prevention) is not tied to where the page comes from, instead related to how the page will be used. Whether the page is restrictedmem backed or GUP() backed, once it's used by current version of TDX then the page pinning is needed. So such page migration prevention is really TDX thing, even not KVM generic thing (that's why I think we don't need change the existing logic of kvm_release_pfn_clean()). Wouldn't better to let TDX code (or who requires that) to increase/decrease the refcount when it populates/drops the secure EPT entries? This is exactly what the current TDX code does:
get_page():
https://github.com/intel/tdx/blob/kvm-upstream/arch/x86/kvm/vmx/tdx.c#L1217
put_page():
https://github.com/intel/tdx/blob/kvm-upstream/arch/x86/kvm/vmx/tdx.c#L1334
Thanks,
Chao
Quoted 9 lines
Quoted 6 lines
The current solution is clear: unless we have better approach, we will let restrictedmem user (KVM in this case) to hold the refcount to prevent page migration.
OK. Will leave to others :)
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 42 lines · Chao Peng
Quoted 42 lines · Kai
Quoted 41 lines
Quoted 41 lines · Chao Peng
Quoted 39 lines
Quoted 39 lines · Kai
Quoted 25 lines
Quoted 25 lines · Chao Peng
Quoted 23 lines
Quoted 23 lines
Quoted 19 lines
Quoted 19 lines
[...]
Quoted 10 lines
+
+ /*
+ * These pages are currently unmovable so don't place them into
movable
+ * pageblocks (e.g. CMA and ZONE_MOVABLE).
+ */
+ mapping = memfd->f_mapping;
+ mapping_set_unevictable(mapping);
+ mapping_set_gfp_mask(mapping,
+ mapping_gfp_mask(mapping) & ~__GFP_MOVABLE);But, IIUC removing
__GFP_MOVABLEflag here only makes page allocation from non-
movable zones, but doesn't necessarily prevent page from being migrated. My first glance is you need to implement eithera_ops->migrate_folio()or justget_page()after faulting in the page to prevent.The current api
restrictedmem_get_page()already does this, after the caller calling it, it holds a reference to the page. The caller then decides when to callput_page()appropriately.Quoted 8 lines
Quoted 8 lines
I tried to dig some history. Perhaps I am missing something, but it seems Kirill said in v9 that this code doesn't prevent page migration, and we need to increase page refcount in
restrictedmem_get_page():https://lore.kernel.org/linux-mm/[email protected]/
But looking at this series it seems
restrictedmem_get_page()in this v10 is identical to the one in v9 (except v10 uses 'folio' instead of 'page')?
restrictedmem_get_page()increases page refcount several versions ago so no change in v10 is needed. You probably missed my reply:
Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Quoted 3 lines
But for non-restricted-mem case, it is correct for KVM to decrease page's refcount after setting up mapping in the secondary mmu, otherwise the page will be pinned by KVM for normal VM (since KVM uses GUP to get the page).
That's true. Actually even true for restrictedmem case, most likely we will still need the
kvm_release_pfn_clean()for KVM generic code. On one side, other restrictedmem users like pKVM may not require page pinning at all. On the other side, see below.
OK. Agreed.
Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
Quoted 4 lines
So what we are expecting is: for KVM if the page comes from restricted mem, then KVM cannot decrease the refcount, otherwise for normal page via GUP KVM should.
Quoted 8 lines
Quoted 8 lines
I argue that this page pinning (or page migration prevention) is not tied to where the page comes from, instead related to how the page will be used. Whether the page is restrictedmem backed or
GUP()backed, once it's used by current version of TDX then the page pinning is needed. So such page migration prevention is really TDX thing, even not KVM generic thing (that's why I think we don't need change the existing logic ofkvm_release_pfn_clean()).
This essentially boils down to who "owns" page migration handling, and sadly, page migration is kinda "owned" by the core-kernel, i.e. KVM cannot handle page migration by itself -- it's just a passive receiver.
For normal pages, page migration is totally done by the core-kernel (i.e. it unmaps page from VMA, allocates a new page, and uses migrate_pape() or a_ops-
Quoted 1 line
migrate_page()to actually migrate the page).
In the sense of TDX, conceptually it should be done in the same way. The more important thing is: yes KVM can use get_page() to prevent page migration, but when KVM wants to support it, KVM cannot just remove get_page(), as the core- kernel will still just do migrate_page() which won't work for TDX (given restricted_memfd doesn't have a_ops->migrate_page() implemented).
So I think the restricted_memfd filesystem should own page migration handling, (i.e. by implementing a_ops->migrate_page() to either just reject page migration or somehow support it).
To support page migration, it may require KVM's help in case of TDX (the TDH.MEM.PAGE.RELOCATE SEAMCALL requires "GPA" and "level" of EPT mapping, which are only available in KVM), but that doesn't make KVM to own the handling of page migration.
Quoted 10 lines
Quoted 10 lines
Wouldn't better to let TDX code (or who
requires that) to increase/decrease the refcount when it populates/drops the secure EPT entries? This is exactly what the current TDX code does:
get_page():
https://github.com/intel/tdx/blob/kvm-upstream/arch/x86/kvm/vmx/tdx.c#L1217
put_page():
https://github.com/intel/tdx/blob/kvm-upstream/arch/x86/kvm/vmx/tdx.c#L1334
As explained above, I think doing so in KVM is wrong: it can prevent by using get_page(), but you cannot simply remove it to support page migration.
Sean also said similar thing when reviewing v8 KVM TDX series and I also agree:
https://lore.kernel.org/lkml/[email protected]/
https://lore.kernel.org/lkml/[email protected]/
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 68 lines · Kai
Quoted 42 lines · Chao Peng
Quoted 42 lines · Kai
Quoted 41 lines
Quoted 41 lines · Chao Peng
Quoted 39 lines
Quoted 39 lines · Kai
Quoted 25 lines
Quoted 25 lines · Chao Peng
Quoted 23 lines
Quoted 23 lines
Quoted 19 lines
Quoted 19 lines
[...]
+
+ /*
+ * These pages are currently unmovable so don't place them into
movable
+ * pageblocks (e.g. CMA and ZONE_MOVABLE).
+ */
+ mapping = memfd->f_mapping;
+ mapping_set_unevictable(mapping);
+ mapping_set_gfp_mask(mapping,
+ mapping_gfp_mask(mapping) & ~__GFP_MOVABLE);But, IIUC removing __GFP_MOVABLE flag here only makes page allocation from
non-
movable zones, but doesn't necessarily prevent page from being migrated. My
first glance is you need to implement either a_ops->migrate_folio() or just
get_page() after faulting in the page to prevent.The current api
restrictedmem_get_page()already does this, after the caller calling it, it holds a reference to the page. The caller then decides when to callput_page()appropriately.Quoted 8 lines
Quoted 8 lines
I tried to dig some history. Perhaps I am missing something, but it seems Kirill said in v9 that this code doesn't prevent page migration, and we need to increase page refcount in
restrictedmem_get_page():https://lore.kernel.org/linux-mm/[email protected]/
But looking at this series it seems
restrictedmem_get_page()in this v10 is identical to the one in v9 (except v10 uses 'folio' instead of 'page')?
restrictedmem_get_page()increases page refcount several versions ago so no change in v10 is needed. You probably missed my reply:Quoted 8 lines
Quoted 8 lines
Quoted 3 lines
Quoted 3 lines
But for non-restricted-mem case, it is correct for KVM to decrease page's refcount after setting up mapping in the secondary mmu, otherwise the page will be pinned by KVM for normal VM (since KVM uses GUP to get the page).
That's true. Actually even true for restrictedmem case, most likely we will still need the
kvm_release_pfn_clean()for KVM generic code. On one side, other restrictedmem users like pKVM may not require page pinning at all. On the other side, see below.OK. Agreed.
Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
Quoted 4 lines
So what we are expecting is: for KVM if the page comes from restricted mem, then KVM cannot decrease the refcount, otherwise for normal page via GUP KVM should.
Quoted 8 lines
Quoted 8 lines
I argue that this page pinning (or page migration prevention) is not tied to where the page comes from, instead related to how the page will be used. Whether the page is restrictedmem backed or
GUP()backed, once it's used by current version of TDX then the page pinning is needed. So such page migration prevention is really TDX thing, even not KVM generic thing (that's why I think we don't need change the existing logic ofkvm_release_pfn_clean()).
Quoted 3 lines
This essentially boils down to who "owns" page migration handling, and sadly, page migration is kinda "owned" by the core-kernel, i.e. KVM cannot handle page migration by itself -- it's just a passive receiver.
No, I'm not talking on the page migration handling itself, I know page migration requires coordination from both core-mm and KVM. I'm more concerning on the page migration prevention here. This is something we need to address for TDX before the page migration is supported.
Quoted 28 lines
For normal pages, page migration is totally done by the core-kernel (i.e. it unmaps page from VMA, allocates a new page, and uses
migrate_pape()or a_ops-Quoted 1 line
migrate_page()to actually migrate the page).In the sense of TDX, conceptually it should be done in the same way. The more important thing is: yes KVM can use
get_page()to prevent page migration, but when KVM wants to support it, KVM cannot just removeget_page(), as the core- kernel will still just domigrate_page()which won't work for TDX (givenrestricted_memfddoesn't havea_ops->migrate_page()implemented).So I think the
restricted_memfdfilesystem should own page migration handling, (i.e. by implementinga_ops->migrate_page()to either just reject page migration or somehow support it).To support page migration, it may require KVM's help in case of TDX (the TDH.MEM.PAGE.RELOCATE SEAMCALL requires "GPA" and "level" of EPT mapping, which are only available in KVM), but that doesn't make KVM to own the handling of page migration.
Quoted 7 lines
Quoted 7 lines
Wouldn't better to let TDX code (or who
requires that) to increase/decrease the refcount when it populates/drops the secure EPT entries? This is exactly what the current TDX code does:
get_page():
https://github.com/intel/tdx/blob/kvm-upstream/arch/x86/kvm/vmx/tdx.c#L1217
Quoted 6 lines
Quoted 3 lines
Quoted 3 lines
put_page():
https://github.com/intel/tdx/blob/kvm-upstream/arch/x86/kvm/vmx/tdx.c#L1334As explained above, I think doing so in KVM is wrong: it can prevent by using
get_page(), but you cannot simply remove it to support page migration.
Removing get_page() is definitely not enough for page migration support. But the key thing is for page migration prevention, other than get_page(), do we really have alternative.
Thanks,
Chao
Quoted 6 lines
Sean also said similar thing when reviewing v8 KVM TDX series and I also agree:
https://lore.kernel.org/lkml/[email protected]/
https://lore.kernel.org/lkml/[email protected]/
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
In reply to Huang, KaiQuoted 21 lines · Kai
Quoted 8 lines
Quoted 8 lines
I argue that this page pinning (or page migration prevention) is not tied to where the page comes from, instead related to how the page will be used. Whether the page is restrictedmem backed or
GUP()backed, once it's used by current version of TDX then the page pinning is needed. So such page migration prevention is really TDX thing, even not KVM generic thing (that's why I think we don't need change the existing logic ofkvm_release_pfn_clean()).This essentially boils down to who "owns" page migration handling, and sadly, page migration is kinda "owned" by the core-kernel, i.e. KVM cannot handle page migration by itself -- it's just a passive receiver.
For normal pages, page migration is totally done by the core-kernel (i.e. it unmaps page from VMA, allocates a new page, and uses
migrate_pape()or a_ops-Quoted 1 line
migrate_page()to actually migrate the page).In the sense of TDX, conceptually it should be done in the same way. The more important thing is: yes KVM can use
get_page()to prevent page migration, but when KVM wants to support it, KVM cannot just removeget_page(), as the core- kernel will still just domigrate_page()which won't work for TDX (givenrestricted_memfddoesn't havea_ops->migrate_page()implemented).
Quoted 3 lines
So I think the
restricted_memfdfilesystem should own page migration handling, (i.e. by implementinga_ops->migrate_page()to either just reject page migration or somehow support it).
While this thread seems to be settled on refcounts already, just wanted to point out that it wouldn't be ideal to prevent migrations by a_ops->migrate_page() rejecting them. It would mean cputime wasted (i.e. by memory compaction) by isolating the pages for migration and then releasing them after the callback rejects it (at least we wouldn't waste time creating and undoing migration entries in the userspace page tables as there's no mmap). Elevated refcount on the other hand is detected very early in compaction so no isolation is attempted, so from that aspect it's optimal.
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 26 lines · Vlastimil Babka
Quoted 21 lines · Kai
Quoted 8 lines
Quoted 8 lines
I argue that this page pinning (or page migration prevention) is not tied to where the page comes from, instead related to how the page will be used. Whether the page is restrictedmem backed or
GUP()backed, once it's used by current version of TDX then the page pinning is needed. So such page migration prevention is really TDX thing, even not KVM generic thing (that's why I think we don't need change the existing logic ofkvm_release_pfn_clean()).This essentially boils down to who "owns" page migration handling, and sadly, page migration is kinda "owned" by the core-kernel, i.e. KVM cannot handle page migration by itself -- it's just a passive receiver.
For normal pages, page migration is totally done by the core-kernel (i.e. it unmaps page from VMA, allocates a new page, and uses
migrate_pape()or a_ops-Quoted 1 line
migrate_page()to actually migrate the page).In the sense of TDX, conceptually it should be done in the same way. The more important thing is: yes KVM can use
get_page()to prevent page migration, but when KVM wants to support it, KVM cannot just removeget_page(), as the core- kernel will still just domigrate_page()which won't work for TDX (givenrestricted_memfddoesn't havea_ops->migrate_page()implemented).Quoted 3 lines
So I think the
restricted_memfdfilesystem should own page migration handling, (i.e. by implementinga_ops->migrate_page()to either just reject page migration or somehow support it).
Quoted 9 lines
While this thread seems to be settled on refcounts already, just wanted to point out that it wouldn't be ideal to prevent migrations by
a_ops->migrate_page()rejecting them. It would mean cputime wasted (i.e. by memory compaction) by isolating the pages for migration and then releasing them after the callback rejects it (at least we wouldn't waste time creating and undoing migration entries in the userspace page tables as there's no mmap). Elevated refcount on the other hand is detected very early in compaction so no isolation is attempted, so from that aspect it's optimal.
Hm. Do we need a new hook in a_ops to check if the page is migratable before going with longer path to migrate_page().
Or maybe add AS_UNMOVABLE?
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 37 lines · Kirill A. Shutemov
Quoted 26 lines · Vlastimil Babka
Quoted 21 lines · Kai
Quoted 8 lines
Quoted 8 lines
I argue that this page pinning (or page migration prevention) is not tied to where the page comes from, instead related to how the page will be used. Whether the page is restrictedmem backed or
GUP()backed, once it's used by current version of TDX then the page pinning is needed. So such page migration prevention is really TDX thing, even not KVM generic thing (that's why I think we don't need change the existing logic ofkvm_release_pfn_clean()).This essentially boils down to who "owns" page migration handling, and sadly, page migration is kinda "owned" by the core-kernel, i.e. KVM cannot handle page migration by itself -- it's just a passive receiver.
For normal pages, page migration is totally done by the core-kernel (i.e. it unmaps page from VMA, allocates a new page, and uses
migrate_pape()or a_ops-Quoted 1 line
migrate_page()to actually migrate the page).In the sense of TDX, conceptually it should be done in the same way. The more important thing is: yes KVM can use
get_page()to prevent page migration, but when KVM wants to support it, KVM cannot just removeget_page(), as the core- kernel will still just domigrate_page()which won't work for TDX (givenrestricted_memfddoesn't havea_ops->migrate_page()implemented).Quoted 3 lines
So I think the
restricted_memfdfilesystem should own page migration handling, (i.e. by implementinga_ops->migrate_page()to either just reject page migration or somehow support it).Quoted 9 lines
While this thread seems to be settled on refcounts already, just wanted to point out that it wouldn't be ideal to prevent migrations by
a_ops->migrate_page()rejecting them. It would mean cputime wasted (i.e. by memory compaction) by isolating the pages for migration and then releasing them after the callback rejects it (at least we wouldn't waste time creating and undoing migration entries in the userspace page tables as there's no mmap). Elevated refcount on the other hand is detected very early in compaction so no isolation is attempted, so from that aspect it's optimal.
Quoted 4 lines
Hm. Do we need a new hook in
a_opsto check if the page is migratable before going with longer path tomigrate_page().Or maybe add
AS_UNMOVABLE?
AS_UNMOVABLE should indeed allow a test in e.g. compaction to descide that the page is not worth isolating in the first place.
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
In reply to Vlastimil BabkaQuoted 22 lines · Vlastimil Babka
Quoted 21 lines · Kai
Quoted 8 lines
Quoted 8 lines
I argue that this page pinning (or page migration prevention) is not tied to where the page comes from, instead related to how the page will be used. Whether the page is restrictedmem backed or
GUP()backed, once it's used by current version of TDX then the page pinning is needed. So such page migration prevention is really TDX thing, even not KVM generic thing (that's why I think we don't need change the existing logic ofkvm_release_pfn_clean()).This essentially boils down to who "owns" page migration handling, and sadly, page migration is kinda "owned" by the core-kernel, i.e. KVM cannot handle page migration by itself -- it's just a passive receiver.
For normal pages, page migration is totally done by the core-kernel (i.e. it unmaps page from VMA, allocates a new page, and uses
migrate_pape()or a_ops-Quoted 1 line
migrate_page()to actually migrate the page).In the sense of TDX, conceptually it should be done in the same way. The more important thing is: yes KVM can use
get_page()to prevent page migration, but when KVM wants to support it, KVM cannot just removeget_page(), as the core- kernel will still just domigrate_page()which won't work for TDX (givenrestricted_memfddoesn't havea_ops->migrate_page()implemented).
Quoted 6 lines
Quoted 3 lines
So I think the
restricted_memfdfilesystem should own page migration handling, (i.e. by implementinga_ops->migrate_page()to either just reject page migration or somehow support it).While this thread seems to be settled on refcounts already,
I am not sure but will let Sean/Paolo to decide.
Quoted 9 lines
just wanted
to point out that it wouldn't be ideal to prevent migrations bya_ops->migrate_page()rejecting them. It would mean cputime wasted (i.e. by memory compaction) by isolating the pages for migration and then releasing them after the callback rejects it (at least we wouldn't waste time creating and undoing migration entries in the userspace page tables as there's no mmap). Elevated refcount on the other hand is detected very early in compaction so no isolation is attempted, so from that aspect it's optimal.
I am probably missing something, but IIUC the checking of refcount happens at very last stage of page migration too, for instance:
migrate_folio(...) -> migrate_folio_extra(..., 0 /* extra_count */) -> folio_migrate_mapping(...).
And it is folio_migrate_mapping() who does the actual compare with the refcount, which is at very late stage too:
int folio_migrate_mapping(struct address_space *mapping,
struct folio *newfolio, struct folio *folio, int extra_count)
{
...
int expected_count = folio_expected_refs(mapping, folio) + extra_count;
if (!mapping) {
/* Anonymous page without mapping */
if (folio_ref_count(folio) != expected_count)
return -EAGAIN;
....
return MIGRATEPAGE_SUCCESS;
}
....
if (!folio_ref_freeze(folio, expected_count)) {
xas_unlock_irq(&xas);
return -EAGAIN;
}
...
}Sean Christopherson
maintainerRe: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 23 lines · Kai
Quoted 22 lines · Vlastimil Babka
Quoted 21 lines · Kai
Quoted 8 lines
Quoted 8 lines
I argue that this page pinning (or page migration prevention) is not tied to where the page comes from, instead related to how the page will be used. Whether the page is restrictedmem backed or
GUP()backed, once it's used by current version of TDX then the page pinning is needed. So such page migration prevention is really TDX thing, even not KVM generic thing (that's why I think we don't need change the existing logic ofkvm_release_pfn_clean()).This essentially boils down to who "owns" page migration handling, and sadly, page migration is kinda "owned" by the core-kernel, i.e. KVM cannot handle page migration by itself -- it's just a passive receiver.
For normal pages, page migration is totally done by the core-kernel (i.e. it unmaps page from VMA, allocates a new page, and uses
migrate_pape()or a_ops-Quoted 1 line
migrate_page()to actually migrate the page).In the sense of TDX, conceptually it should be done in the same way. The more important thing is: yes KVM can use
get_page()to prevent page migration, but when KVM wants to support it, KVM cannot just removeget_page(), as the core- kernel will still just domigrate_page()which won't work for TDX (givenrestricted_memfddoesn't havea_ops->migrate_page()implemented).
Quoted 8 lines
Quoted 6 lines
Quoted 3 lines
So I think the
restricted_memfdfilesystem should own page migration handling, (i.e. by implementinga_ops->migrate_page()to either just reject page migration or somehow support it).While this thread seems to be settled on refcounts already,
I am not sure but will let Sean/Paolo to decide.
My preference is whatever is most performant without being hideous :-)
Quoted 11 lines
Quoted 9 lines
just wanted
to point out that it wouldn't be ideal to prevent migrations bya_ops->migrate_page()rejecting them. It would mean cputime wasted (i.e. by memory compaction) by isolating the pages for migration and then releasing them after the callback rejects it (at least we wouldn't waste time creating and undoing migration entries in the userspace page tables as there's no mmap). Elevated refcount on the other hand is detected very early in compaction so no isolation is attempted, so from that aspect it's optimal.I am probably missing something,
Heh, me too, I could have sworn that using refcounts was the least efficient way to block migration.
Quoted 1 line
but IIUC the checking of refcount happens at very last stage of page migration too
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 45 lines · Sean Christopherson
Quoted 23 lines · Kai
Quoted 22 lines · Vlastimil Babka
Quoted 21 lines · Kai
Quoted 8 lines
Quoted 8 lines
I argue that this page pinning (or page migration prevention) is not tied to where the page comes from, instead related to how the page will be used. Whether the page is restrictedmem backed or
GUP()backed, once it's used by current version of TDX then the page pinning is needed. So such page migration prevention is really TDX thing, even not KVM generic thing (that's why I think we don't need change the existing logic ofkvm_release_pfn_clean()).This essentially boils down to who "owns" page migration handling, and sadly, page migration is kinda "owned" by the core-kernel, i.e. KVM cannot handle page migration by itself -- it's just a passive receiver.
For normal pages, page migration is totally done by the core-kernel (i.e. it unmaps page from VMA, allocates a new page, and uses
migrate_pape()or a_ops-Quoted 1 line
migrate_page()to actually migrate the page).In the sense of TDX, conceptually it should be done in the same way. The more important thing is: yes KVM can use
get_page()to prevent page migration, but when KVM wants to support it, KVM cannot just removeget_page(), as the core- kernel will still just domigrate_page()which won't work for TDX (givenrestricted_memfddoesn't havea_ops->migrate_page()implemented).Quoted 8 lines
Quoted 6 lines
Quoted 3 lines
So I think the
restricted_memfdfilesystem should own page migration handling, (i.e. by implementinga_ops->migrate_page()to either just reject page migration or somehow support it).While this thread seems to be settled on refcounts already,
I am not sure but will let Sean/Paolo to decide.
My preference is whatever is most performant without being hideous :-)
Quoted 10 lines
Quoted 9 lines
just wanted
to point out that it wouldn't be ideal to prevent migrations bya_ops->migrate_page()rejecting them. It would mean cputime wasted (i.e. by memory compaction) by isolating the pages for migration and then releasing them after the callback rejects it (at least we wouldn't waste time creating and undoing migration entries in the userspace page tables as there's no mmap). Elevated refcount on the other hand is detected very early in compaction so no isolation is attempted, so from that aspect it's optimal.
Quoted 4 lines
Quoted 1 line
I am probably missing something,
Heh, me too, I could have sworn that using refcounts was the least efficient way to block migration.
Well I admit that due to my experience with it, I do mostly consider migration through memory compaction POV, which is a significant user of migration on random pages that's not requested by userspace actions on specific ranges.
And compaction has in isolate_migratepages_block():
/*
* Migration will fail if an anonymous page is pinned in memory,
* so avoid taking lru_lock and isolating it unnecessarily in an
* admittedly racy check.
*/
mapping = page_mapping(page);
if (!mapping && page_count(page) > page_mapcount(page))
goto isolate_fail;
so that prevents migration of pages with elevated refcount very early, before they are even isolated, so before migrate_pages() is called.
But it's true there are other sources of "random pages migration" - numa balancing, demotion in lieu of reclaim... and I'm not sure if all have such early check too.
Anyway, whatever is decided to be a better way than elevated refcounts, would ideally be checked before isolation as well, as that's the most efficient way.
Quoted 1 line
Quoted 1 line
but IIUC the checking of refcount happens at very last stage of page migration too
Sean Christopherson
maintainerRe: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
In reply to Chao PengQuoted 4 lines · Chao Peng
Quoted 3 lines · Kai
Quoted 2 lines · Chao Peng
Quoted 1 line · Kai
On Mon, 2022-12-19 at 15:53 +0800, Chao Peng wrote:
Quoted 12 lines
Quoted 3 lines
But for non-restricted-mem case, it is correct for KVM to decrease page's refcount after setting up mapping in the secondary mmu, otherwise the page will be pinned by KVM for normal VM (since KVM uses GUP to get the page).
That's true. Actually even true for restrictedmem case, most likely we will still need the
kvm_release_pfn_clean()for KVM generic code. On one side, other restrictedmem users like pKVM may not require page pinning at all. On the other side, see below.Quoted 3 lines
So what we are expecting is: for KVM if the page comes from restricted mem, then KVM cannot decrease the refcount, otherwise for normal page via GUP KVM should.
No, requiring the user (KVM) to guard against lack of support for page migration in restricted mem is a terrible API. It's totally fine for restricted mem to not support page migration until there's a use case, but punting the problem to KVM is not acceptable. Restricted mem itself doesn't yet support page migration, e.g. explosions would occur even if KVM wanted to allow migration since there is no notification to invalidate existing mappings.
Quoted 9 lines
I argue that this page pinning (or page migration prevention) is not tied to where the page comes from, instead related to how the page will be used. Whether the page is restrictedmem backed or
GUP()backed, once it's used by current version of TDX then the page pinning is needed. So such page migration prevention is really TDX thing, even not KVM generic thing (that's why I think we don't need change the existing logic ofkvm_release_pfn_clean()). Wouldn't better to let TDX code (or who requires that) to increase/decrease the refcount when it populates/drops the secure EPT entries? This is exactly what the current TDX code does:
I agree that whether or not migration is supported should be controllable by the user, but I strongly disagree on punting refcount management to KVM (or TDX). The whole point of restricted mem is to support technologies like TDX and SNP, accomodating their special needs for things like page migration should be part of the API, not some footnote in the documenation.
It's not difficult to let the user communicate support for page migration, e.g. if/when restricted mem gains support, add a hook to restrictedmem_notifier_ops to signal support (or lack thereof) for page migration. NULL == no migration, non-NULL == migration allowed.
We know that supporting page migration in TDX and SNP is possible, and we know that page migration will require a dedicated API since the backing store can't memcpy() the page. I don't see any reason to ignore that eventuality.
But again, unless I'm missing something, that's a future problem because restricted mem doesn't yet support page migration regardless of the downstream user.
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 18 lines · Sean Christopherson
Quoted 4 lines · Chao Peng
Quoted 3 lines · Kai
Quoted 2 lines · Chao Peng
Quoted 1 line · Kai
On Mon, 2022-12-19 at 15:53 +0800, Chao Peng wrote:
Quoted 12 lines
Quoted 3 lines
But for non-restricted-mem case, it is correct for KVM to decrease page's refcount after setting up mapping in the secondary mmu, otherwise the page will be pinned by KVM for normal VM (since KVM uses GUP to get the page).
That's true. Actually even true for restrictedmem case, most likely we will still need the
kvm_release_pfn_clean()for KVM generic code. On one side, other restrictedmem users like pKVM may not require page pinning at all. On the other side, see below.Quoted 3 lines
So what we are expecting is: for KVM if the page comes from restricted mem, then KVM cannot decrease the refcount, otherwise for normal page via GUP KVM should.
Quoted 8 lines
No, requiring the user (KVM) to guard against lack of support for page migration in restricted mem is a terrible API. It's totally fine for restricted mem to not support page migration until there's a use case, but punting the problem to KVM is not acceptable. Restricted mem itself doesn't yet support page migration, e.g. explosions would occur even if KVM wanted to allow migration since there is no notification to invalidate existing mappings.
Yes totally agree (I also replied separately).
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
In reply to Sean ChristophersonQuoted 35 lines · Sean Christopherson
Quoted 4 lines · Chao Peng
Quoted 3 lines · Kai
Quoted 2 lines · Chao Peng
Quoted 1 line · Kai
On Mon, 2022-12-19 at 15:53 +0800, Chao Peng wrote:
Quoted 12 lines
Quoted 3 lines
But for non-restricted-mem case, it is correct for KVM to decrease page's refcount after setting up mapping in the secondary mmu, otherwise the page will be pinned by KVM for normal VM (since KVM uses GUP to get the page).
That's true. Actually even true for restrictedmem case, most likely we will still need the
kvm_release_pfn_clean()for KVM generic code. On one side, other restrictedmem users like pKVM may not require page pinning at all. On the other side, see below.Quoted 3 lines
So what we are expecting is: for KVM if the page comes from restricted mem, then KVM cannot decrease the refcount, otherwise for normal page via GUP KVM should.
No, requiring the user (KVM) to guard against lack of support for page migration in restricted mem is a terrible API. It's totally fine for restricted mem to not support page migration until there's a use case, but punting the problem to KVM is not acceptable. Restricted mem itself doesn't yet support page migration, e.g. explosions would occur even if KVM wanted to allow migration since there is no notification to invalidate existing mappings.
Quoted 9 lines
I argue that this page pinning (or page migration prevention) is not tied to where the page comes from, instead related to how the page will be used. Whether the page is restrictedmem backed or
GUP()backed, once it's used by current version of TDX then the page pinning is needed. So such page migration prevention is really TDX thing, even not KVM generic thing (that's why I think we don't need change the existing logic ofkvm_release_pfn_clean()). Wouldn't better to let TDX code (or who requires that) to increase/decrease the refcount when it populates/drops the secure EPT entries? This is exactly what the current TDX code does:
Quoted 5 lines
I agree that whether or not migration is supported should be controllable by the user, but I strongly disagree on punting refcount management to KVM (or TDX). The whole point of restricted mem is to support technologies like TDX and SNP, accomodating their special needs for things like page migration should be part of the API, not some footnote in the documenation.
I never doubt page migration should be part of restrictedmem API, but that's not an initial implementing as we all agreed? Then before that API being introduced, we need find a solution to prevent page migration for TDX. Other than refcount management, do we have any other workable solution?
Quoted 5 lines
It's not difficult to let the user communicate support for page migration, e.g. if/when restricted mem gains support, add a hook to
restrictedmem_notifier_opsto signal support (or lack thereof) for page migration. NULL == no migration, non-NULL == migration allowed.
I know.
Quoted 4 lines
We know that supporting page migration in TDX and SNP is possible, and we know that page migration will require a dedicated API since the backing store can't
memcpy()the page. I don't see any reason to ignore that eventuality.
No, I'm not ignoring it. It's just about the short-term page migration prevention before that dedicated API being introduced.
Quoted 3 lines
But again, unless I'm missing something, that's a future problem because restricted mem doesn't yet support page migration regardless of the downstream user.
It's true a future problem for page migration support itself, but page migration prevention is not a future problem since TDX pages need to be pinned before page migration gets supported.
Thanks,
Chao
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
In reply to Sean ChristophersonQuoted 18 lines · Sean Christopherson
Quoted 4 lines · Chao Peng
Quoted 3 lines · Kai
Quoted 2 lines · Chao Peng
Quoted 1 line · Kai
On Mon, 2022-12-19 at 15:53 +0800, Chao Peng wrote:
Quoted 12 lines
Quoted 3 lines
But for non-restricted-mem case, it is correct for KVM to decrease page's refcount after setting up mapping in the secondary mmu, otherwise the page will be pinned by KVM for normal VM (since KVM uses GUP to get the page).
That's true. Actually even true for restrictedmem case, most likely we will still need the
kvm_release_pfn_clean()for KVM generic code. On one side, other restrictedmem users like pKVM may not require page pinning at all. On the other side, see below.Quoted 3 lines
So what we are expecting is: for KVM if the page comes from restricted mem, then KVM cannot decrease the refcount, otherwise for normal page via GUP KVM should.
Quoted 6 lines
No, requiring the user (KVM) to guard against lack of support for page migration in restricted mem is a terrible API. It's totally fine for restricted mem to not support page migration until there's a use case, but punting the problem to KVM is not acceptable. Restricted mem itself doesn't yet support page migration, e.g. explosions would occur even if KVM wanted to allow migration since there is no notification to invalidate existing mappings.
I tried to find a way to hook into migration path from restrictedmem. It is not easy because from code-mm PoV the restrictedmem page just yet another shmem page.
It is somewhat dubious, but I think it should be safe to override mapping->a_ops for the shmem mapping.
It also eliminates need in special treatment for the restrictedmem pages from memory-failure code.
shmem_mapping() uses ->a_ops to detect shmem mapping. Modify the implementation to still be true for restrictedmem pages.
Build tested only.
Any comments?
include/linux/restrictedmem.h +0 -7
@@ -36,8 +36,6 @@ static inline bool file_is_restrictedmem(struct file *file) return file->f_inode->i_sb->s_magic == RESTRICTEDMEM_MAGIC; } -void restrictedmem_error_page (struct page *page,struct address_space *mapping); -#else static inline bool file_is_restrictedmem (struct file *file)
@@ -45,11 +43,6 @@ static inline bool file_is_restrictedmem(struct file *file)return false; } -static inline void restrictedmem_error_page (struct page *page, -struct address_space *mapping) -{ -} -#endif /* CONFIG_RESTRICTEDMEM */ #endif /* _LINUX_RESTRICTEDMEM_H */
include/linux/shmem_fs.h +2 -2
@@ -9,6 +9,7 @@#include <linux/percpu_counter.h> #include <linux/xattr.h> #include <linux/fs_parser.h> +#include <linux/magic.h> /* inode in-kernel data */
@@ -75,10 +76,9 @@ extern unsigned long shmem_get_unmapped_area(struct file *, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags);extern int shmem_lock (struct file *file,int lock,struct ucounts *ucounts);#ifdef CONFIG_SHMEM -extern const struct address_space_operations shmem_aops;static inline bool shmem_mapping (struct address_space *mapping) { -return mapping->a_ops == &shmem_aops; +return mapping->host->i_sb->s_magic ==TMPFS_MAGIC ; }#else static inline bool shmem_mapping (struct address_space *mapping)
mm/memory-failure.c +0 -3
@@ -62,7 +62,6 @@#include <linux/page-isolation.h> #include <linux/pagewalk.h> #include <linux/shmem_fs.h> -#include <linux/restrictedmem.h> #include "swap.h" #include "internal.h" #include "ras/ras_event.h"
@@ -941,8 +940,6 @@ static int me_pagecache_clean(struct page_state *ps, struct page *p) goto out; } -restrictedmem_error_page (p, mapping); -/* * The shmem page is kept in page cache instead of truncating * so is expected to have an extra refcount after error-handling.
mm/restrictedmem.c +47 -28
90 lines not on this page · raw message
mm/shmem.c +2 -3
@@ -231,7 +231,7 @@ static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages) }static const struct super_operations shmem_ops; -const struct address_space_operations shmem_aops; +static const struct address_space_operations shmem_aops;static const struct file_operations shmem_file_operations;static const struct inode_operations shmem_inode_operations;static const struct inode_operations shmem_dir_inode_operations;
@@ -3894,7 +3894,7 @@ static int shmem_error_remove_page(struct address_space *mapping,return 0 ; } -const struct address_space_operations shmem_aops = { +static const struct address_space_operations shmem_aops = { .writepage = shmem_writepage, .dirty_folio = noop_dirty_folio, #ifdef CONFIG_TMPFS
@@ -3906,7 +3906,6 @@ const struct address_space_operations shmem_aops = {#endif .error_remove_page = shmem_error_remove_page, }; -EXPORT_SYMBOL (shmem_aops);static const struct file_operations shmem_file_operations = { .mmap = shmem_mmap,
Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 81 lines · Kirill A. Shutemov
Quoted 18 lines · Sean Christopherson
Quoted 4 lines · Chao Peng
Quoted 3 lines · Kai
Quoted 2 lines · Chao Peng
Quoted 1 line · Kai
On Mon, 2022-12-19 at 15:53 +0800, Chao Peng wrote:
Quoted 12 lines
Quoted 3 lines
But for non-restricted-mem case, it is correct for KVM to decrease page's refcount after setting up mapping in the secondary mmu, otherwise the page will be pinned by KVM for normal VM (since KVM uses GUP to get the page).
That's true. Actually even true for restrictedmem case, most likely we will still need the
kvm_release_pfn_clean()for KVM generic code. On one side, other restrictedmem users like pKVM may not require page pinning at all. On the other side, see below.Quoted 3 lines
So what we are expecting is: for KVM if the page comes from restricted mem, then KVM cannot decrease the refcount, otherwise for normal page via GUP KVM should.
Quoted 6 lines
No, requiring the user (KVM) to guard against lack of support for page migration in restricted mem is a terrible API. It's totally fine for restricted mem to not support page migration until there's a use case, but punting the problem to KVM is not acceptable. Restricted mem itself doesn't yet support page migration, e.g. explosions would occur even if KVM wanted to allow migration since there is no notification to invalidate existing mappings.
I tried to find a way to hook into migration path from restrictedmem. It is not easy because from code-mm PoV the restrictedmem page just yet another shmem page.
It is somewhat dubious, but I think it should be safe to override
mapping->a_opsfor the shmem mapping.It also eliminates need in special treatment for the restrictedmem pages from memory-failure code.
shmem_mapping()uses ->a_ops to detect shmem mapping. Modify the implementation to still be true for restrictedmem pages.Build tested only.
Any comments?
include/linux/restrictedmem.h +0
-7@@ -36,8 +36,6 @@ static inline bool file_is_restrictedmem(struct file *file) return file->f_inode->i_sb->s_magic == RESTRICTEDMEM_MAGIC; } -void restrictedmem_error_page (struct page *page,struct address_space *mapping); -#else static inline bool file_is_restrictedmem (struct file *file)@@ -45,11 +43,6 @@ static inline bool file_is_restrictedmem(struct file *file)return false; } -static inline void restrictedmem_error_page (struct page *page, -struct address_space *mapping) -{ -} -#endif /* CONFIG_RESTRICTEDMEM */ #endif /* _LINUX_RESTRICTEDMEM_H */ include/linux/shmem_fs.h +1
-0@@ -9,6 +9,7 @@#include <linux/percpu_counter.h> #include <linux/xattr.h> #include <linux/fs_parser.h> +#include <linux/magic.h> /* inode in-kernel data */
include/linux/shmem_fs.h extern unsigned long shmem_get_unmapped_area(struct file *, unsigned long addr, · line 81
Quoted 8 lines
include/linux/shmem_fs.h +1
-2@@ -75,10 +76,9 @@ extern unsigned long shmem_get_unmapped_area(struct file *, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags);extern int shmem_lock (struct file *file,int lock,struct ucounts *ucounts);#ifdef CONFIG_SHMEM -extern const struct address_space_operations shmem_aops;static inline bool shmem_mapping (struct address_space *mapping) { -return mapping->a_ops == &shmem_aops; +return mapping->host->i_sb->s_magic ==TMPFS_MAGIC ;
Alternatively just check a_ops against two possible values? Fewer chained dereferences, no-op with !CONFIG_RESTRICTEDMEM, maybe Hugh would be less unhappy with that.
Besides that, IIRC Michael Roth mentioned that this approach for preventing migration would be simpler for SNP than the refcount elevation? Do I recall right and should this be pursued then?
Quoted 151 lines
include/linux/shmem_fs.h +0
-0}#else static inline bool shmem_mapping (struct address_space *mapping)mm/memory-failure.c +0
-3@@ -62,7 +62,6 @@#include <linux/page-isolation.h> #include <linux/pagewalk.h> #include <linux/shmem_fs.h> -#include <linux/restrictedmem.h> #include "swap.h" #include "internal.h" #include "ras/ras_event.h" @@ -941,8 +940,6 @@ static int me_pagecache_clean(struct page_state *ps, struct page *p) goto out; } -restrictedmem_error_page (p, mapping); -/* * The shmem page is kept in page cache instead of truncating * so is expected to have an extra refcount after error-handling. mm/restrictedmem.c +47
-28@@ -189,6 +189,51 @@ static struct file *restrictedmem_file_create(struct file *memfd)return file; } +static int restricted_error_remove_page (struct address_space *mapping, +struct page *page) +{ +struct super_block *sb = restrictedmem_mnt->mnt_sb; +struct inode *inode, *next; +pgoff_t start, end; + + start = page->index; + end = start +thp_nr_pages (page); + +spin_lock (&sb->s_inode_list_lock); +list_for_each_entry_safe (inode, next, &sb->s_inodes, i_sb_list) { +struct restrictedmem *rm = inode->i_mapping->private_data; +struct restrictedmem_notifier *notifier; +struct file *memfd = rm->memfd; +unsigned long index; + +if (memfd->f_mapping != mapping) +continue ; + +xa_for_each_range (&rm->bindings, index, notifier, start, end) + notifier->ops->error (notifier, start, end); +break ; + } +spin_unlock (&sb->s_inode_list_lock); + +return 0 ; +} + +#ifdef CONFIG_MIGRATION +static int restricted_folio (struct address_space *mapping,struct folio *dst, +struct folio *src,enum migrate_mode mode) +{ +return -EBUSY ; +} +#endif + +static struct address_space_operations restricted_aops = { + .dirty_folio = noop_dirty_folio, + .error_remove_page = restricted_error_remove_page, +#ifdef CONFIG_MIGRATION + .migrate_folio = restricted_folio, +#endif +}; + SYSCALL_DEFINE1(memfd_restricted, unsigned int, flags) {struct file *file, *restricted_file;@@ -209,6 +254,8 @@ SYSCALL_DEFINE1(memfd_restricted, unsigned int, flags) file->f_mode |=FMODE_LSEEK |FMODE_PREAD |FMODE_PWRITE ; file->f_flags |=O_LARGEFILE ; + file->f_mapping->a_ops = &restricted_aops; + restricted_file =restrictedmem_file_create (file);if (IS_ERR (restricted_file)) { err =PTR_ERR (restricted_file);@@ -293,31 +340,3 @@ int restrictedmem_get_page(struct file *file, pgoff_t offset, }EXPORT_SYMBOL_GPL (restrictedmem_get_page); -void restrictedmem_error_page (struct page *page,struct address_space *mapping) -{ -struct super_block *sb = restrictedmem_mnt->mnt_sb; -struct inode *inode, *next; -pgoff_t start, end; - -if (!shmem_mapping (mapping)) -return ; - - start = page->index; - end = start +thp_nr_pages (page); - -spin_lock (&sb->s_inode_list_lock); -list_for_each_entry_safe (inode, next, &sb->s_inodes, i_sb_list) { -struct restrictedmem *rm = inode->i_mapping->private_data; -struct restrictedmem_notifier *notifier; -struct file *memfd = rm->memfd; -unsigned long index; - -if (memfd->f_mapping != mapping) -continue ; - -xa_for_each_range (&rm->bindings, index, notifier, start, end) - notifier->ops->error (notifier, start, end); -break ; - } -spin_unlock (&sb->s_inode_list_lock); -}mm/shmem.c +2
-3@@ -231,7 +231,7 @@ static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages) }static const struct super_operations shmem_ops; -const struct address_space_operations shmem_aops; +static const struct address_space_operations shmem_aops;static const struct file_operations shmem_file_operations;static const struct inode_operations shmem_inode_operations;static const struct inode_operations shmem_dir_inode_operations;@@ -3894,7 +3894,7 @@ static int shmem_error_remove_page(struct address_space *mapping,return 0 ; } -const struct address_space_operations shmem_aops = { +static const struct address_space_operations shmem_aops = { .writepage = shmem_writepage, .dirty_folio = noop_dirty_folio, #ifdef CONFIG_TMPFS@@ -3906,7 +3906,6 @@ const struct address_space_operations shmem_aops = {#endif .error_remove_page = shmem_error_remove_page, }; -EXPORT_SYMBOL (shmem_aops);static const struct file_operations shmem_file_operations = { .mmap = shmem_mmap,
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
In reply to Kirill A. ShutemovQuoted 36 lines · Kirill A. Shutemov
Quoted 18 lines · Sean Christopherson
Quoted 4 lines · Chao Peng
Quoted 3 lines · Kai
Quoted 2 lines · Chao Peng
Quoted 1 line · Kai
On Mon, 2022-12-19 at 15:53 +0800, Chao Peng wrote:
Quoted 12 lines
Quoted 3 lines
But for non-restricted-mem case, it is correct for KVM to decrease page's refcount after setting up mapping in the secondary mmu, otherwise the page will be pinned by KVM for normal VM (since KVM uses GUP to get the page).
That's true. Actually even true for restrictedmem case, most likely we will still need the
kvm_release_pfn_clean()for KVM generic code. On one side, other restrictedmem users like pKVM may not require page pinning at all. On the other side, see below.Quoted 3 lines
So what we are expecting is: for KVM if the page comes from restricted mem, then KVM cannot decrease the refcount, otherwise for normal page via GUP KVM should.
Quoted 6 lines
No, requiring the user (KVM) to guard against lack of support for page migration in restricted mem is a terrible API. It's totally fine for restricted mem to not support page migration until there's a use case, but punting the problem to KVM is not acceptable. Restricted mem itself doesn't yet support page migration, e.g. explosions would occur even if KVM wanted to allow migration since there is no notification to invalidate existing mappings.
I tried to find a way to hook into migration path from restrictedmem. It is not easy because from code-mm PoV the restrictedmem page just yet another shmem page.
It is somewhat dubious, but I think it should be safe to override
mapping->a_opsfor the shmem mapping.It also eliminates need in special treatment for the restrictedmem pages from memory-failure code.
Quoted 6 lines
shmem_mapping()uses ->a_ops to detect shmem mapping. Modify the implementation to still be true for restrictedmem pages.Build tested only.
Any comments?
Hi Kirill,
We've been testing your approach to handle pinning for the SNP+UPM implementation and haven't noticed any problems so far:
(based on top of Sean's updated UPM v10 tree)
https://github.com/mdroth/linux/commit/f780033e6812a01f8732060605d941474fee2bd6
Prior to your patch we also tried elevating refcount via restrictedmem_get_page() for cases where shmem_get_folio(..., SGP_NOALLOC) indicates the page hasn't been allocated yet, and that approach also seems to work, but there are potential races and other ugliness that make your approach seem a lot cleaner.
-Mike
Quoted 200 lines
include/linux/restrictedmem.h +0
-7@@ -36,8 +36,6 @@ static inline bool file_is_restrictedmem(struct file *file) return file->f_inode->i_sb->s_magic == RESTRICTEDMEM_MAGIC; } -void restrictedmem_error_page (struct page *page,struct address_space *mapping); -#else static inline bool file_is_restrictedmem (struct file *file)@@ -45,11 +43,6 @@ static inline bool file_is_restrictedmem(struct file *file)return false; } -static inline void restrictedmem_error_page (struct page *page, -struct address_space *mapping) -{ -} -#endif /* CONFIG_RESTRICTEDMEM */ #endif /* _LINUX_RESTRICTEDMEM_H */ include/linux/shmem_fs.h +2
-2@@ -9,6 +9,7 @@#include <linux/percpu_counter.h> #include <linux/xattr.h> #include <linux/fs_parser.h> +#include <linux/magic.h> /* inode in-kernel data */ @@ -75,10 +76,9 @@ extern unsigned long shmem_get_unmapped_area(struct file *, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags);extern int shmem_lock (struct file *file,int lock,struct ucounts *ucounts);#ifdef CONFIG_SHMEM -extern const struct address_space_operations shmem_aops;static inline bool shmem_mapping (struct address_space *mapping) { -return mapping->a_ops == &shmem_aops; +return mapping->host->i_sb->s_magic ==TMPFS_MAGIC ; }#else static inline bool shmem_mapping (struct address_space *mapping)mm/memory-failure.c +0
-3@@ -62,7 +62,6 @@#include <linux/page-isolation.h> #include <linux/pagewalk.h> #include <linux/shmem_fs.h> -#include <linux/restrictedmem.h> #include "swap.h" #include "internal.h" #include "ras/ras_event.h" @@ -941,8 +940,6 @@ static int me_pagecache_clean(struct page_state *ps, struct page *p) goto out; } -restrictedmem_error_page (p, mapping); -/* * The shmem page is kept in page cache instead of truncating * so is expected to have an extra refcount after error-handling. mm/restrictedmem.c +47
-28@@ -189,6 +189,51 @@ static struct file *restrictedmem_file_create(struct file *memfd)return file; } +static int restricted_error_remove_page (struct address_space *mapping, +struct page *page) +{ +struct super_block *sb = restrictedmem_mnt->mnt_sb; +struct inode *inode, *next; +pgoff_t start, end; + + start = page->index; + end = start +thp_nr_pages (page); + +spin_lock (&sb->s_inode_list_lock); +list_for_each_entry_safe (inode, next, &sb->s_inodes, i_sb_list) { +struct restrictedmem *rm = inode->i_mapping->private_data; +struct restrictedmem_notifier *notifier; +struct file *memfd = rm->memfd; +unsigned long index; + +if (memfd->f_mapping != mapping) +continue ; + +xa_for_each_range (&rm->bindings, index, notifier, start, end) + notifier->ops->error (notifier, start, end); +break ; + } +spin_unlock (&sb->s_inode_list_lock); + +return 0 ; +} + +#ifdef CONFIG_MIGRATION +static int restricted_folio (struct address_space *mapping,struct folio *dst, +struct folio *src,enum migrate_mode mode) +{ +return -EBUSY ; +} +#endif + +static struct address_space_operations restricted_aops = { + .dirty_folio = noop_dirty_folio, + .error_remove_page = restricted_error_remove_page, +#ifdef CONFIG_MIGRATION + .migrate_folio = restricted_folio, +#endif +}; + SYSCALL_DEFINE1(memfd_restricted, unsigned int, flags) {struct file *file, *restricted_file;@@ -209,6 +254,8 @@ SYSCALL_DEFINE1(memfd_restricted, unsigned int, flags) file->f_mode |=FMODE_LSEEK |FMODE_PREAD |FMODE_PWRITE ; file->f_flags |=O_LARGEFILE ; + file->f_mapping->a_ops = &restricted_aops; + restricted_file =restrictedmem_file_create (file);if (IS_ERR (restricted_file)) { err =PTR_ERR (restricted_file);@@ -293,31 +340,3 @@ int restrictedmem_get_page(struct file *file, pgoff_t offset, }EXPORT_SYMBOL_GPL (restrictedmem_get_page); -void restrictedmem_error_page (struct page *page,struct address_space *mapping) -{ -struct super_block *sb = restrictedmem_mnt->mnt_sb; -struct inode *inode, *next; -pgoff_t start, end; - -if (!shmem_mapping (mapping)) -return ; - - start = page->index; - end = start +thp_nr_pages (page); - -spin_lock (&sb->s_inode_list_lock); -list_for_each_entry_safe (inode, next, &sb->s_inodes, i_sb_list) { -struct restrictedmem *rm = inode->i_mapping->private_data; -struct restrictedmem_notifier *notifier; -struct file *memfd = rm->memfd; -unsigned long index; - -if (memfd->f_mapping != mapping) -continue ; - -xa_for_each_range (&rm->bindings, index, notifier, start, end) - notifier->ops->error (notifier, start, end); -break ; - } -spin_unlock (&sb->s_inode_list_lock); -}mm/shmem.c +2
-3@@ -231,7 +231,7 @@ static inline void shmem_inode_unacct_blocks(struct inode *inode, long pages) }static const struct super_operations shmem_ops; -const struct address_space_operations shmem_aops; +static const struct address_space_operations shmem_aops;static const struct file_operations shmem_file_operations;static const struct inode_operations shmem_inode_operations;static const struct inode_operations shmem_dir_inode_operations;@@ -3894,7 +3894,7 @@ static int shmem_error_remove_page(struct address_space *mapping,return 0 ; } -const struct address_space_operations shmem_aops = { +static const struct address_space_operations shmem_aops = { .writepage = shmem_writepage, .dirty_folio = noop_dirty_folio, #ifdef CONFIG_TMPFS@@ -3906,7 +3906,6 @@ const struct address_space_operations shmem_aops = {#endif .error_remove_page = shmem_error_remove_page, }; -EXPORT_SYMBOL (shmem_aops);static const struct file_operations shmem_file_operations = { .mmap = shmem_mmap,Signature · 1 line
Kiryl Shutsemau / Kirill A. Shutemov
Sean Christopherson
maintainerRe: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
In reply to Chao PengQuoted 1 line · Chao Peng
The system call is currently wired up for x86 arch.
Building on other architectures (except for arm64 for some reason) yields:
CALL /.../scripts/checksyscalls.sh
<stdin>:1565:2: warning: #warning syscall memfd_restricted not implemented [-Wcpp]
Do we care? It's the only such warning, which makes me think we either need to wire this up for all architectures, or explicitly document that it's unsupported.
Quoted 3 lines
Signed-off-by Kirill A. Shutemov <[email protected]>Signed-off-by Chao Peng <[email protected]>---
...
include/linux/restrictedmem.h line 2
Quoted 8 lines
include/linux/restrictedmem.h new file +2
-0@@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _LINUX_RESTRICTEDMEM_H
Missing
#define _LINUX_RESTRICTEDMEM_H
which causes fireworks if restrictedmem.h is included more than once.
Quoted 3 lines
include/linux/restrictedmem.h new file +3
-0+#include <linux/file.h> +#include <linux/magic.h> +#include <linux/pfn_t.h>
...
include/linux/restrictedmem.h line 56
Quoted 4 lines
include/linux/restrictedmem.h new file +4
-0+static inline int restrictedmem_get_page (struct file *file,pgoff_t offset, +struct page **pagep,int *order) +{ +return -1 ;
This should be a proper -errno, though in the current incarnation of things it's a moot point because no stub is needed. KVM can (and should) easily provide its own stub for this one.
Quoted 15 lines
include/linux/restrictedmem.h new file +15
-0+} + +static inline bool file_is_restrictedmem (struct file *file) +{ +return false; +} + +static inline void restrictedmem_error_page (struct page *page, +struct address_space *mapping) +{ +} + +#endif /* CONFIG_RESTRICTEDMEM */ + +#endif /* _LINUX_RESTRICTEDMEM_H */
...
Quoted 7 lines
mm/restrictedmem.c new file +1
-0@@ -0,0 +1,318 @@ +// SPDX-License-Identifier: GPL-2.0
mm/restrictedmem.c line 11
Quoted 10 lines
mm/restrictedmem.c new file +10
-0+#include "linux/sbitmap.h" +#include <linux/pagemap.h> +#include <linux/pseudo_fs.h> +#include <linux/shmem_fs.h> +#include <linux/syscalls.h> +#include <uapi/linux/falloc.h> +#include <uapi/linux/magic.h> +#include <linux/restrictedmem.h> + +struct restrictedmem_data {
Any objection to simply calling this "restrictedmem"? And then using either "rm" or "rmem" for local variable names? I kept reading "data" as the underyling data being written to the page, as opposed to the metadata describing the restrictedmem instance.
mm/restrictedmem.c line 22
Quoted 11 lines
mm/restrictedmem.c new file +11
-0+struct mutex lock; +struct file *memfd; +struct list_head notifiers; +}; + +static void restrictedmem_invalidate_start (struct restrictedmem_data *data, +pgoff_t start,pgoff_t end) +{ +struct restrictedmem_notifier *notifier; + +mutex_lock (&data->lock);
This can be a r/w semaphore instead of a mutex, that way punching holes at multiple points in the file can at least run the notifiers in parallel. The actual allocation by shmem will still be serialized, but I think it's worth the simple optimization since zapping and flushing in KVM may be somewhat slow.
mm/restrictedmem.c line 24
Quoted 2 lines
mm/restrictedmem.c new file +2
-0+list_for_each_entry (notifier, &data->notifiers, list) { + notifier->ops->invalidate_start (notifier, start, end);
Two major design issues that we overlooked long ago:
1. Blindly invoking notifiers will not scale. E.g. if userspace configures a VM with a large number of convertible memslots that are all backed by a single large restrictedmem instance, then converting a single page will result in a linear walk through all memslots. I don't expect anyone to actually do something silly like that, but I also never expected there to be a legitimate usecase for thousands of memslots.
2. This approach fails to provide the ability for KVM to ensure a guest has exclusive access to a page. As discussed in the past, the kernel can rely on hardware (and maybe ARM's pKVM implementation?) for those guarantees, but only for SNP and TDX VMs. For VMs where userspace is trusted to some extent, e.g. SEV, there is value in ensuring a 1:1 association.
And probably more importantly, relying on hardware for SNP and TDX yields a poor ABI and complicates KVM's internals. If the kernel doesn't guarantee a page is exclusive to a guest, i.e. if userspace can hand out the same page from a restrictedmem instance to multiple VMs, then failure will occur only when KVM tries to assign the page to the second VM. That will happen deep in KVM, which means KVM needs to gracefully handle such errors, and it means that KVM's ABI effectively allows plumbing garbage into its memslots.
Rather than use a simple list of notifiers, this appears to be yet another opportunity to use an xarray. Supporting sharing of restrictedmem will be non-trivial, but IMO we should punt that to the future since it's still unclear exactly how sharing will work.
An xarray will solve #1 by notifying only the consumers (memslots) that are bound to the affected range.
And for #2, it's relatively straightforward (knock wood) to detect existing entries, i.e. if the user wants exclusive access to memory, then the bind operation can be reject if there's an existing entry.
VERY lightly tested code snippet at the bottom (will provide link to fully worked code in cover letter).
Quoted 6 lines
mm/restrictedmem.c new file +6
-0+static long restrictedmem_punch_hole (struct restrictedmem_data *data,int mode, +loff_t offset,loff_t len) +{ +int ret; +pgoff_t start, end; +struct file *memfd = data->memfd;
mm/restrictedmem.c line 77
Quoted 10 lines
mm/restrictedmem.c new file +10
-0+ +if (!PAGE_ALIGNED (offset) || !PAGE_ALIGNED (len)) +return -EINVAL ; + + start = offset >>PAGE_SHIFT ; + end = (offset + len) >>PAGE_SHIFT ; + +restrictedmem_invalidate_start (data, start, end); + ret = memfd->f_op->fallocate (memfd, mode, offset, len); +restrictedmem_invalidate_end (data, start, end);
The lock needs to be end for the entire duration of the hole punch, i.e. needs to be taken before invalidate_start() and released after invalidate_end(). If a user (un)binds/(un)registers after invalidate_state(), it will see an unpaired notification, e.g. could leave KVM with incorrect notifier counts.
mm/restrictedmem.c line 80
Quoted 3 lines
mm/restrictedmem.c new file +3
-0+ +return ret; +}
What I ended up with for an xarray-based implementation. I'm very flexible on names and whatnot, these are just what made sense to me.
static long restrictedmem_punch_hole(struct restrictedmem *rm, int mode,
loff_t offset, loff_t len)
{
struct restrictedmem_notifier *notifier;
struct file *memfd = rm->memfd;
unsigned long index;
pgoff_t start, end;
int ret;
if (!PAGE_ALIGNED(offset) || !PAGE_ALIGNED(len))
return -EINVAL;
start = offset >> PAGE_SHIFT;
end = (offset + len) >> PAGE_SHIFT;
/*
* Bindings must stable across invalidation to ensure the start+end
* are balanced.
*/
down_read(&rm->lock);
xa_for_each_range(&rm->bindings, index, notifier, start, end)
notifier->ops->invalidate_start(notifier, start, end);
ret = memfd->f_op->fallocate(memfd, mode, offset, len);
xa_for_each_range(&rm->bindings, index, notifier, start, end)
notifier->ops->invalidate_end(notifier, start, end);
up_read(&rm->lock);
return ret;
}int restrictedmem_bind(struct file *file, pgoff_t start, pgoff_t end,
struct restrictedmem_notifier *notifier, bool exclusive)
{
struct restrictedmem *rm = file->f_mapping->private_data;
int ret = -EINVAL;
down_write(&rm->lock);
/* Non-exclusive mappings are not yet implemented. */
if (!exclusive)
goto out_unlock;
if (!xa_empty(&rm->bindings)) {
if (exclusive != rm->exclusive)
goto out_unlock;
if (exclusive && xa_find(&rm->bindings, &start, end, XA_PRESENT))
goto out_unlock;
}
xa_store_range(&rm->bindings, start, end, notifier, GFP_KERNEL);
rm->exclusive = exclusive;
ret = 0;
out_unlock:
up_write(&rm->lock);
return ret;
}EXPORT_SYMBOL_GPL(restrictedmem_bind);
void restrictedmem_unbind(struct file *file, pgoff_t start, pgoff_t end,
struct restrictedmem_notifier *notifier)
{
struct restrictedmem *rm = file->f_mapping->private_data;
down_write(&rm->lock);
xa_store_range(&rm->bindings, start, end, NULL, GFP_KERNEL);
synchronize_rcu();
up_write(&rm->lock);
}EXPORT_SYMBOL_GPL(restrictedmem_unbind);
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 10 lines · Sean Christopherson
Quoted 1 line · Chao Peng
The system call is currently wired up for x86 arch.
Building on other architectures (except for arm64 for some reason) yields:
CALL /.../scripts/checksyscalls.sh
<stdin>:1565:2: warning: #warning syscallmemfd_restrictednot implemented [-Wcpp]Do we care? It's the only such warning, which makes me think we either need to wire this up for all architectures, or explicitly document that it's unsupported.
I'm a bit conservative and prefer enabling only on x86 where we know the exact usecase. For the warning we can get rid of by changing scripts/checksyscalls.sh, just like __IGNORE_memfd_secret:
https://lkml.kernel.org/r/[email protected]
Quoted 113 lines
Quoted 4 lines
Signed-off-by Kirill A. Shutemov <[email protected]>Signed-off-by Chao Peng <[email protected]>---
...
include/linux/restrictedmem.h line 2
Quoted 8 lines
include/linux/restrictedmem.h new file +2
-0@@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _LINUX_RESTRICTEDMEM_HMissing
#define
_LINUX_RESTRICTEDMEM_Hwhich causes fireworks if
restrictedmem.his included more than once.Quoted 3 lines
include/linux/restrictedmem.h new file +3
-0+#include <linux/file.h> +#include <linux/magic.h> +#include <linux/pfn_t.h> ...
include/linux/restrictedmem.h line 56
Quoted 4 lines
include/linux/restrictedmem.h new file +4
-0+static inline int restrictedmem_get_page (struct file *file,pgoff_t offset, +struct page **pagep,int *order) +{ +return -1 ;This should be a proper -errno, though in the current incarnation of things it's a moot point because no stub is needed. KVM can (and should) easily provide its own stub for this one.
Quoted 15 lines
include/linux/restrictedmem.h new file +15
-0+} + +static inline bool file_is_restrictedmem (struct file *file) +{ +return false; +} + +static inline void restrictedmem_error_page (struct page *page, +struct address_space *mapping) +{ +} + +#endif /* CONFIG_RESTRICTEDMEM */ + +#endif /* _LINUX_RESTRICTEDMEM_H */ ...
Quoted 7 lines
mm/restrictedmem.c new file +1
-0@@ -0,0 +1,318 @@ +// SPDX-License-Identifier: GPL-2.0 mm/restrictedmem.c line 11
Quoted 10 lines
mm/restrictedmem.c new file +10
-0+#include "linux/sbitmap.h" +#include <linux/pagemap.h> +#include <linux/pseudo_fs.h> +#include <linux/shmem_fs.h> +#include <linux/syscalls.h> +#include <uapi/linux/falloc.h> +#include <uapi/linux/magic.h> +#include <linux/restrictedmem.h> + +struct restrictedmem_data {Any objection to simply calling this "restrictedmem"? And then using either "rm" or "rmem" for local variable names? I kept reading "data" as the underyling data being written to the page, as opposed to the metadata describing the restrictedmem instance.
mm/restrictedmem.c line 22
Quoted 11 lines
mm/restrictedmem.c new file +11
-0+struct mutex lock; +struct file *memfd; +struct list_head notifiers; +}; + +static void restrictedmem_invalidate_start (struct restrictedmem_data *data, +pgoff_t start,pgoff_t end) +{ +struct restrictedmem_notifier *notifier; + +mutex_lock (&data->lock);This can be a r/w semaphore instead of a mutex, that way punching holes at multiple points in the file can at least run the notifiers in parallel. The actual allocation by shmem will still be serialized, but I think it's worth the simple optimization since zapping and flushing in KVM may be somewhat slow.
mm/restrictedmem.c line 24
Quoted 2 lines
mm/restrictedmem.c new file +2
-0+list_for_each_entry (notifier, &data->notifiers, list) { + notifier->ops->invalidate_start (notifier, start, end);Two major design issues that we overlooked long ago:
1. Blindly invoking notifiers will not scale. E.g. if userspace configures a VM with a large number of convertible memslots that are all backed by a single large restrictedmem instance, then converting a single page will result in a linear walk through all memslots. I don't expect anyone to actually do something silly like that, but I also never expected there to be a legitimate usecase for thousands of memslots.
2. This approach fails to provide the ability for KVM to ensure a guest has exclusive access to a page. As discussed in the past, the kernel can rely on hardware (and maybe ARM's pKVM implementation?) for those guarantees, but only for SNP and TDX VMs. For VMs where userspace is trusted to some extent, e.g. SEV, there is value in ensuring a 1:1 association.
Quoted 7 lines
And probably more importantly, relying on hardware for SNP and TDX yields a poor ABI and complicates KVM's internals. If the kernel doesn't guarantee a page is exclusive to a guest, i.e. if userspace can hand out the same page from a restrictedmem instance to multiple VMs, then failure will occur only when KVM tries to assign the page to the second VM. That will happen deep in KVM, which means KVM needs to gracefully handle such errors, and it means that KVM's ABI effectively allows plumbing garbage into its memslots.
It may not be a valid usage, but in my TDX environment I do meet below issue.
kvm_set_user_memory AddrSpace#0 Slot#0 flags=0x4 gpa=0x0 size=0x80000000 ua=0x7fe1ebfff000 ret=0 kvm_set_user_memory AddrSpace#0 Slot#1 flags=0x4 gpa=0xffc00000 size=0x400000 ua=0x7fe271579000 ret=0 kvm_set_user_memory AddrSpace#0 Slot#2 flags=0x4 gpa=0xfeda0000 size=0x20000 ua=0x7fe1ec09f000 ret=-22
Slot#2('SMRAM') is actually an alias into system memory(Slot#0) in QEMU and slot#2 fails due to below exclusive check.
Currently I changed QEMU code to mark these alias slots as shared instead of private but I'm not 100% confident this is correct fix.
Quoted 120 lines
Rather than use a simple list of notifiers, this appears to be yet another opportunity to use an xarray. Supporting sharing of restrictedmem will be non-trivial, but IMO we should punt that to the future since it's still unclear exactly how sharing will work.
An xarray will solve #1 by notifying only the consumers (memslots) that are bound to the affected range.
And for #2, it's relatively straightforward (knock wood) to detect existing entries, i.e. if the user wants exclusive access to memory, then the bind operation can be reject if there's an existing entry.
VERY lightly tested code snippet at the bottom (will provide link to fully worked code in cover letter).
Quoted 6 lines
mm/restrictedmem.c new file +6
-0+static long restrictedmem_punch_hole (struct restrictedmem_data *data,int mode, +loff_t offset,loff_t len) +{ +int ret; +pgoff_t start, end; +struct file *memfd = data->memfd;mm/restrictedmem.c line 77
Quoted 10 lines
mm/restrictedmem.c new file +10
-0+ +if (!PAGE_ALIGNED (offset) || !PAGE_ALIGNED (len)) +return -EINVAL ; + + start = offset >>PAGE_SHIFT ; + end = (offset + len) >>PAGE_SHIFT ; + +restrictedmem_invalidate_start (data, start, end); + ret = memfd->f_op->fallocate (memfd, mode, offset, len); +restrictedmem_invalidate_end (data, start, end);The lock needs to be end for the entire duration of the hole punch, i.e. needs to be taken before
invalidate_start()and released afterinvalidate_end(). If a user (un)binds/(un)registers afterinvalidate_state(), it will see an unpaired notification, e.g. could leave KVM with incorrect notifier counts.mm/restrictedmem.c line 80
Quoted 3 lines
mm/restrictedmem.c new file +3
-0+ +return ret; +}What I ended up with for an xarray-based implementation. I'm very flexible on names and whatnot, these are just what made sense to me.
static long restrictedmem_punch_hole(struct restrictedmem *rm, int mode,
loff_toffset,loff_tlen){ struct restrictedmem_notifier *notifier; struct file *memfd = rm->memfd; unsigned long index; pgoff_t start, end; int ret; if (!PAGE_ALIGNED(offset) || !PAGE_ALIGNED(len)) return -EINVAL; start = offset >> PAGE_SHIFT; end = (offset + len) >> PAGE_SHIFT; /* * Bindings must stable across invalidation to ensure the start+end * are balanced. */ down_read(&rm->lock); xa_for_each_range(&rm->bindings, index, notifier, start, end) notifier->ops->invalidate_start(notifier, start, end); ret = memfd->f_op->fallocate(memfd, mode, offset, len); xa_for_each_range(&rm->bindings, index, notifier, start, end) notifier->ops->invalidate_end(notifier, start, end); up_read(&rm->lock); return ret; }int restrictedmem_bind(struct file *file,
pgoff_tstart,pgoff_tend,
structrestrictedmem_notifier*notifier, bool exclusive){ struct restrictedmem *rm = file->f_mapping->private_data; int ret = -EINVAL; down_write(&rm->lock); /* Non-exclusive mappings are not yet implemented. */ if (!exclusive) goto out_unlock; if (!xa_empty(&rm->bindings)) { if (exclusive != rm->exclusive) goto out_unlock; if (exclusive && xa_find(&rm->bindings, &start, end, XA_PRESENT)) goto out_unlock; } xa_store_range(&rm->bindings, start, end, notifier, GFP_KERNEL); rm->exclusive = exclusive; ret = 0; out_unlock: up_write(&rm->lock); return ret; }
EXPORT_SYMBOL_GPL(restrictedmem_bind);void restrictedmem_unbind(struct file *file,
pgoff_tstart,pgoff_tend,
structrestrictedmem_notifier*notifier){ struct restrictedmem *rm = file->f_mapping->private_data; down_write(&rm->lock); xa_store_range(&rm->bindings, start, end, NULL, GFP_KERNEL); synchronize_rcu(); up_write(&rm->lock); }
EXPORT_SYMBOL_GPL(restrictedmem_unbind);
Sean Christopherson
maintainerRe: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 34 lines · Chao Peng
Quoted 18 lines · Sean Christopherson
Review
Quoted 2 lines
(quoted diff) +2
-0+ list_for_each_entry(notifier, &data->notifiers, list) { + notifier->ops->invalidate_start(notifier, start, end);Two major design issues that we overlooked long ago:
1. Blindly invoking notifiers will not scale. E.g. if userspace configures a VM with a large number of convertible memslots that are all backed by a single large restrictedmem instance, then converting a single page will result in a linear walk through all memslots. I don't expect anyone to actually do something silly like that, but I also never expected there to be a legitimate usecase for thousands of memslots.
2. This approach fails to provide the ability for KVM to ensure a guest has exclusive access to a page. As discussed in the past, the kernel can rely on hardware (and maybe ARM's pKVM implementation?) for those guarantees, but only for SNP and TDX VMs. For VMs where userspace is trusted to some extent, e.g. SEV, there is value in ensuring a 1:1 association.
Quoted 7 lines
And probably more importantly, relying on hardware for SNP and TDX yields a poor ABI and complicates KVM's internals. If the kernel doesn't guarantee a page is exclusive to a guest, i.e. if userspace can hand out the same page from a restrictedmem instance to multiple VMs, then failure will occur only when KVM tries to assign the page to the second VM. That will happen deep in KVM, which means KVM needs to gracefully handle such errors, and it means that KVM's ABI effectively allows plumbing garbage into its memslots.
It may not be a valid usage, but in my TDX environment I do meet below issue.
kvm_set_user_memoryAddrSpace#0 Slot#0 flags=0x4 gpa=0x0 size=0x80000000 ua=0x7fe1ebfff000 ret=0kvm_set_user_memoryAddrSpace#0 Slot#1 flags=0x4 gpa=0xffc00000 size=0x400000 ua=0x7fe271579000 ret=0kvm_set_user_memoryAddrSpace#0 Slot#2 flags=0x4 gpa=0xfeda0000 size=0x20000 ua=0x7fe1ec09f000 ret=-22
Quoted 5 lines
Slot#2('SMRAM') is actually an alias into system memory(Slot#0) in QEMU and slot#2 fails due to below exclusive check.
Currently I changed QEMU code to mark these alias slots as shared instead of private but I'm not 100% confident this is correct fix.
That's a QEMU bug of sorts. SMM is mutually exclusive with TDX, QEMU shouldn't be configuring SMRAM (or any SMM memslots for that matter) for TDX guests.
Actually, KVM should enforce that by disallowing SMM memslots for TDX guests. Ditto for SNP guests and UPM-backed SEV and SEV-ES guests. I think it probably even makes sense to introduce that restriction in the base UPM support, e.g. something like the below. That would unnecessarily prevent emulating SMM for KVM_X86_PROTECTED_VM types that aren't encrypted, but IMO that's an acceptable limitation until there's an actual use case for KVM_X86_PROTECTED_VM guests beyond SEV (my thought is that KVM_X86_PROTECTED_VM will mostly be a vehicle for selftests and UPM-based SEV and SEV-ES guests).
arch/x86/kvm/x86.c +8 -0
@@ -4357,6 +4357,14 @@ bool kvm_arch_has_private_mem(struct kvm *kvm)return kvm->arch.vm_type !=KVM_X86_DEFAULT_VM ; } +bool kvm_arch_nr_address_spaces (struct kvm *kvm) +{ +if (kvm->arch.vm_type !=KVM_X86_DEFAULT_VM ) +return 1 ; + +return KVM_ADDRESS_SPACE_NUM ; +} +static bool kvm_is_vm_type_supported (unsigned long type) { return type == KVM_X86_DEFAULT_VM ||
virt/kvm/kvm_main.c +1 -1
@@ -2126,7 +2126,7 @@ int __kvm_set_memory_region(struct kvm *kvm, mem->restricted_offset + mem->memory_size < mem->restricted_offset || 0 /* TODO: require gfn be aligned with restricted offset */)) return -EINVAL; -if (as_id >=KVM_ADDRESS_SPACE_NUM || id >=KVM_MEM_SLOTS_NUM ) +if (as_id >=kvm_arch_nr_address_spaces (vm) || id >=KVM_MEM_SLOTS_NUM )return -EINVAL ;if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)return -EINVAL ;
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 35 lines · Sean Christopherson
Quoted 34 lines · Chao Peng
Quoted 18 lines · Sean Christopherson
Review
Quoted 2 lines
(quoted diff) +2
-0+ list_for_each_entry(notifier, &data->notifiers, list) { + notifier->ops->invalidate_start(notifier, start, end);Two major design issues that we overlooked long ago:
1. Blindly invoking notifiers will not scale. E.g. if userspace configures a VM with a large number of convertible memslots that are all backed by a single large restrictedmem instance, then converting a single page will result in a linear walk through all memslots. I don't expect anyone to actually do something silly like that, but I also never expected there to be a legitimate usecase for thousands of memslots.
2. This approach fails to provide the ability for KVM to ensure a guest has exclusive access to a page. As discussed in the past, the kernel can rely on hardware (and maybe ARM's pKVM implementation?) for those guarantees, but only for SNP and TDX VMs. For VMs where userspace is trusted to some extent, e.g. SEV, there is value in ensuring a 1:1 association.
Quoted 7 lines
And probably more importantly, relying on hardware for SNP and TDX yields a poor ABI and complicates KVM's internals. If the kernel doesn't guarantee a page is exclusive to a guest, i.e. if userspace can hand out the same page from a restrictedmem instance to multiple VMs, then failure will occur only when KVM tries to assign the page to the second VM. That will happen deep in KVM, which means KVM needs to gracefully handle such errors, and it means that KVM's ABI effectively allows plumbing garbage into its memslots.
It may not be a valid usage, but in my TDX environment I do meet below issue.
kvm_set_user_memoryAddrSpace#0 Slot#0 flags=0x4 gpa=0x0 size=0x80000000 ua=0x7fe1ebfff000 ret=0kvm_set_user_memoryAddrSpace#0 Slot#1 flags=0x4 gpa=0xffc00000 size=0x400000 ua=0x7fe271579000 ret=0kvm_set_user_memoryAddrSpace#0 Slot#2 flags=0x4 gpa=0xfeda0000 size=0x20000 ua=0x7fe1ec09f000 ret=-22
Quoted 8 lines
Quoted 5 lines
Slot#2('SMRAM') is actually an alias into system memory(Slot#0) in QEMU and slot#2 fails due to below exclusive check.
Currently I changed QEMU code to mark these alias slots as shared instead of private but I'm not 100% confident this is correct fix.
That's a QEMU bug of sorts. SMM is mutually exclusive with TDX, QEMU shouldn't be configuring SMRAM (or any SMM memslots for that matter) for TDX guests.
Thanks for the confirmation. As long as we only bind one notifier for each address, using xarray does make things simple.
Chao
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 39 lines · Chao Peng
Quoted 38 lines · Sean Christopherson
Quoted 37 lines · Chao Peng
Quoted 18 lines · Sean Christopherson
Review
Quoted 2 lines
(quoted diff) +2
-0+ list_for_each_entry(notifier, &data->notifiers, list) { + notifier->ops->invalidate_start(notifier, start, end);Two major design issues that we overlooked long ago:
1. Blindly invoking notifiers will not scale. E.g. if userspace configures a VM with a large number of convertible memslots that are all backed by a single large restrictedmem instance, then converting a single page will result in a linear walk through all memslots. I don't expect anyone to actually do something silly like that, but I also never expected there to be a legitimate usecase for thousands of memslots.
2. This approach fails to provide the ability for KVM to ensure a guest has exclusive access to a page. As discussed in the past, the kernel can rely on hardware (and maybe ARM's pKVM implementation?) for those guarantees, but only for SNP and TDX VMs. For VMs where userspace is trusted to some extent, e.g. SEV, there is value in ensuring a 1:1 association.
Quoted 7 lines
And probably more importantly, relying on hardware for SNP and TDX yields a poor ABI and complicates KVM's internals. If the kernel doesn't guarantee a page is exclusive to a guest, i.e. if userspace can hand out the same page from a restrictedmem instance to multiple VMs, then failure will occur only when KVM tries to assign the page to the second VM. That will happen deep in KVM, which means KVM needs to gracefully handle such errors, and it means that KVM's ABI effectively allows plumbing garbage into its memslots.
It may not be a valid usage, but in my TDX environment I do meet below issue.
kvm_set_user_memoryAddrSpace#0 Slot#0 flags=0x4 gpa=0x0 size=0x80000000 ua=0x7fe1ebfff000 ret=0kvm_set_user_memoryAddrSpace#0 Slot#1 flags=0x4 gpa=0xffc00000 size=0x400000 ua=0x7fe271579000 ret=0kvm_set_user_memoryAddrSpace#0 Slot#2 flags=0x4 gpa=0xfeda0000 size=0x20000 ua=0x7fe1ec09f000 ret=-22Slot#2('SMRAM') is actually an alias into system memory(Slot#0) in QEMU and slot#2 fails due to below exclusive check.
Quoted 8 lines
Quoted 5 lines
Quoted 2 lines
Currently I changed QEMU code to mark these alias slots as shared instead of private but I'm not 100% confident this is correct fix.
That's a QEMU bug of sorts. SMM is mutually exclusive with TDX, QEMU shouldn't be configuring SMRAM (or any SMM memslots for that matter) for TDX guests.
Thanks for the confirmation. As long as we only bind one notifier for each address, using xarray does make things simple.
In the past, I had patches for qemu to disable PAM and SMRAM, but they were dropped for simplicity because SMRAM/PAM are disabled as reset state with unused memslot registered. TDX guest bios(TDVF or EDK2) doesn't enable them. Now we can revive them.
Signature · 1 line
Isaku Yamahata <[email protected]>
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
In reply to Sean ChristophersonQuoted 223 lines · Sean Christopherson
Quoted 1 line · Chao Peng
The system call is currently wired up for x86 arch.
Building on other architectures (except for arm64 for some reason) yields:
CALL /.../scripts/checksyscalls.sh
<stdin>:1565:2: warning: #warning syscallmemfd_restrictednot implemented [-Wcpp]Do we care? It's the only such warning, which makes me think we either need to wire this up for all architectures, or explicitly document that it's unsupported.
Quoted 3 lines
Signed-off-by Kirill A. Shutemov <[email protected]>Signed-off-by Chao Peng <[email protected]>---
...
include/linux/restrictedmem.h line 2
Quoted 8 lines
include/linux/restrictedmem.h new file +2
-0@@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _LINUX_RESTRICTEDMEM_HMissing
#define _LINUX_RESTRICTEDMEM_Hwhich causes fireworks if
restrictedmem.his included more than once.Quoted 3 lines
include/linux/restrictedmem.h new file +3
-0+#include <linux/file.h> +#include <linux/magic.h> +#include <linux/pfn_t.h> ...
include/linux/restrictedmem.h
Quoted 4 lines
include/linux/restrictedmem.h new file +4
-0+static inline int restrictedmem_get_page (struct file *file,pgoff_t offset, +struct page **pagep,int *order) +{ +return -1 ;This should be a proper -errno, though in the current incarnation of things it's a moot point because no stub is needed. KVM can (and should) easily provide its own stub for this one.
Quoted 15 lines
include/linux/restrictedmem.h new file +15
-0+} + +static inline bool file_is_restrictedmem (struct file *file) +{ +return false; +} + +static inline void restrictedmem_error_page (struct page *page, +struct address_space *mapping) +{ +} + +#endif /* CONFIG_RESTRICTEDMEM */ + +#endif /* _LINUX_RESTRICTEDMEM_H */ ...
Quoted 7 lines
mm/restrictedmem.c new file +1
-0@@ -0,0 +1,318 @@ +// SPDX-License-Identifier: GPL-2.0 mm/restrictedmem.c line 11
Quoted 10 lines
mm/restrictedmem.c new file +10
-0+#include "linux/sbitmap.h" +#include <linux/pagemap.h> +#include <linux/pseudo_fs.h> +#include <linux/shmem_fs.h> +#include <linux/syscalls.h> +#include <uapi/linux/falloc.h> +#include <uapi/linux/magic.h> +#include <linux/restrictedmem.h> + +struct restrictedmem_data {Any objection to simply calling this "restrictedmem"? And then using either "rm" or "rmem" for local variable names? I kept reading "data" as the underyling data being written to the page, as opposed to the metadata describing the restrictedmem instance.
mm/restrictedmem.c line 22
Quoted 11 lines
mm/restrictedmem.c new file +11
-0+struct mutex lock; +struct file *memfd; +struct list_head notifiers; +}; + +static void restrictedmem_invalidate_start (struct restrictedmem_data *data, +pgoff_t start,pgoff_t end) +{ +struct restrictedmem_notifier *notifier; + +mutex_lock (&data->lock);This can be a r/w semaphore instead of a mutex, that way punching holes at multiple points in the file can at least run the notifiers in parallel. The actual allocation by shmem will still be serialized, but I think it's worth the simple optimization since zapping and flushing in KVM may be somewhat slow.
mm/restrictedmem.c line 24
Quoted 2 lines
mm/restrictedmem.c new file +2
-0+list_for_each_entry (notifier, &data->notifiers, list) { + notifier->ops->invalidate_start (notifier, start, end);Two major design issues that we overlooked long ago:
1. Blindly invoking notifiers will not scale. E.g. if userspace configures a VM with a large number of convertible memslots that are all backed by a single large restrictedmem instance, then converting a single page will result in a linear walk through all memslots. I don't expect anyone to actually do something silly like that, but I also never expected there to be a legitimate usecase for thousands of memslots.
2. This approach fails to provide the ability for KVM to ensure a guest has exclusive access to a page. As discussed in the past, the kernel can rely on hardware (and maybe ARM's pKVM implementation?) for those guarantees, but only for SNP and TDX VMs. For VMs where userspace is trusted to some extent, e.g. SEV, there is value in ensuring a 1:1 association.
And probably more importantly, relying on hardware for SNP and TDX yields a poor ABI and complicates KVM's internals. If the kernel doesn't guarantee a page is exclusive to a guest, i.e. if userspace can hand out the same page from a restrictedmem instance to multiple VMs, then failure will occur only when KVM tries to assign the page to the second VM. That will happen deep in KVM, which means KVM needs to gracefully handle such errors, and it means that KVM's ABI effectively allows plumbing garbage into its memslots.
Rather than use a simple list of notifiers, this appears to be yet another opportunity to use an xarray. Supporting sharing of restrictedmem will be non-trivial, but IMO we should punt that to the future since it's still unclear exactly how sharing will work.
An xarray will solve #1 by notifying only the consumers (memslots) that are bound to the affected range.
And for #2, it's relatively straightforward (knock wood) to detect existing entries, i.e. if the user wants exclusive access to memory, then the bind operation can be reject if there's an existing entry.
VERY lightly tested code snippet at the bottom (will provide link to fully worked code in cover letter).
Quoted 6 lines
mm/restrictedmem.c new file +6
-0+static long restrictedmem_punch_hole (struct restrictedmem_data *data,int mode, +loff_t offset,loff_t len) +{ +int ret; +pgoff_t start, end; +struct file *memfd = data->memfd;mm/restrictedmem.c line 40
Quoted 10 lines
mm/restrictedmem.c new file +10
-0+ +if (!PAGE_ALIGNED (offset) || !PAGE_ALIGNED (len)) +return -EINVAL ; + + start = offset >>PAGE_SHIFT ; + end = (offset + len) >>PAGE_SHIFT ; + +restrictedmem_invalidate_start (data, start, end); + ret = memfd->f_op->fallocate (memfd, mode, offset, len); +restrictedmem_invalidate_end (data, start, end);The lock needs to be end for the entire duration of the hole punch, i.e. needs to be taken before
invalidate_start()and released afterinvalidate_end(). If a user (un)binds/(un)registers afterinvalidate_state(), it will see an unpaired notification, e.g. could leave KVM with incorrect notifier counts.mm/restrictedmem.c line 43
Quoted 3 lines
mm/restrictedmem.c new file +3
-0+ +return ret; +}What I ended up with for an xarray-based implementation. I'm very flexible on names and whatnot, these are just what made sense to me.
static long restrictedmem_punch_hole(struct restrictedmem *rm, int mode,
loff_toffset,loff_tlen){ struct restrictedmem_notifier *notifier; struct file *memfd = rm->memfd; unsigned long index; pgoff_t start, end; int ret; if (!PAGE_ALIGNED(offset) || !PAGE_ALIGNED(len)) return -EINVAL; start = offset >> PAGE_SHIFT; end = (offset + len) >> PAGE_SHIFT; /* * Bindings must stable across invalidation to ensure the start+end * are balanced. */ down_read(&rm->lock); xa_for_each_range(&rm->bindings, index, notifier, start, end) notifier->ops->invalidate_start(notifier, start, end); ret = memfd->f_op->fallocate(memfd, mode, offset, len); xa_for_each_range(&rm->bindings, index, notifier, start, end) notifier->ops->invalidate_end(notifier, start, end); up_read(&rm->lock); return ret; }int restrictedmem_bind(struct file *file,
pgoff_tstart,pgoff_tend,
structrestrictedmem_notifier*notifier, bool exclusive){ struct restrictedmem *rm = file->f_mapping->private_data; int ret = -EINVAL; down_write(&rm->lock); /* Non-exclusive mappings are not yet implemented. */ if (!exclusive) goto out_unlock; if (!xa_empty(&rm->bindings)) {
Quoted 8 lines
if (exclusive != rm->exclusive) goto out_unlock; if (exclusive && xa_find(&rm->bindings, &start, end, XA_PRESENT)) goto out_unlock; } xa_store_range(&rm->bindings, start, end, notifier, GFP_KERNEL);
|| ld: mm/restrictedmem.o: in function `restrictedmem_bind': mm/restrictedmem.c|295| undefined reference to `xa_store_range'
This is missing:
===
mm/Kconfig +1 -0
@@ -1087,6 +1087,7 @@ config SECRETMEM config RESTRICTEDMEM bool depends on TMPFS + select XARRAY_MULTI
===
Thanks,
Quoted 19 lines
rm->exclusive = exclusive; ret = 0; out_unlock: up_write(&rm->lock); return ret; }
EXPORT_SYMBOL_GPL(restrictedmem_bind);void restrictedmem_unbind(struct file *file,
pgoff_tstart,pgoff_tend,
structrestrictedmem_notifier*notifier){ struct restrictedmem *rm = file->f_mapping->private_data; down_write(&rm->lock); xa_store_range(&rm->bindings, start, end, NULL, GFP_KERNEL); synchronize_rcu(); up_write(&rm->lock); }
EXPORT_SYMBOL_GPL(restrictedmem_unbind);
Signature · 1 line
Alexey
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 20 lines
Quoted 20 lines
int restrictedmem_bind(struct file *file,
pgoff_tstart,pgoff_tend,
structrestrictedmem_notifier*notifier, bool exclusive){ struct restrictedmem *rm = file->f_mapping->private_data; int ret = -EINVAL; down_write(&rm->lock); /* Non-exclusive mappings are not yet implemented. */ if (!exclusive) goto out_unlock; if (!xa_empty(&rm->bindings)) { if (exclusive != rm->exclusive) goto out_unlock; if (exclusive && xa_find(&rm->bindings, &start, end, XA_PRESENT)) goto out_unlock; }
Quoted 5 lines
Quoted 1 line
xa_store_range(&rm->bindings, start, end, notifier, GFP_KERNEL);|| ld: mm/restrictedmem.o: in function `restrictedmem_bind': mm/restrictedmem.c|295| undefined reference to `xa_store_range'
Right, xa_store_range() is only available for XARRAY_MULTI.
Quoted 41 lines
This is missing:
===mm/Kconfig +1
-0@@ -1087,6 +1087,7 @@ config SECRETMEM config RESTRICTEDMEM bool depends on TMPFS + select XARRAY_MULTI===
Thanks,
Quoted 19 lines
rm->exclusive = exclusive; ret = 0; out_unlock: up_write(&rm->lock); return ret; }
EXPORT_SYMBOL_GPL(restrictedmem_bind);void restrictedmem_unbind(struct file *file,
pgoff_tstart,pgoff_tend,
structrestrictedmem_notifier*notifier){ struct restrictedmem *rm = file->f_mapping->private_data; down_write(&rm->lock); xa_store_range(&rm->bindings, start, end, NULL, GFP_KERNEL); synchronize_rcu(); up_write(&rm->lock); }
EXPORT_SYMBOL_GPL(restrictedmem_unbind);Signature · 1 line
Alexey
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
In reply to Chao PengReview
Quoted 11 lines
(quoted diff) +10
-0+static int restrictedmem_getattr(struct user_namespace *mnt_userns, + const struct path *path, struct kstat *stat, + u32 request_mask, unsigned int query_flags) +{ + struct inode *inode = d_inode(path->dentry); + struct restrictedmem_data *data = inode->i_mapping->private_data; + struct file *memfd = data->memfd; + + return memfd->f_inode->i_op->getattr(mnt_userns, path, stat, + request_mask, query_flags);
Instead of calling shmem's getattr() with path, we should be using the the memfd's path.
Otherwise, shmem's getattr() will use restrictedmem's inode instead of shmem's inode. The private fields will be of the wrong type, and the host will crash when shmem_is_huge() does SHMEM_SB(inode->i_sb)->huge), since inode->i_sb->s_fs_info is NULL for the restrictedmem's superblock.
Here's the patch:
mm/restrictedmem.c +1 -1
@@ -84,7 +84,7 @@ static int restrictedmem_getattr(struct user_namespace *mnt_userns,struct restrictedmem *rm = inode->i_mapping->private_data;struct file *memfd = rm->memfd; -return memfd->f_inode->i_op->getattr (mnt_userns, path, stat, +return memfd->f_inode->i_op->getattr (mnt_userns, &memfd->f_path, stat, request_mask, query_flags); }
Quoted 27 lines
(quoted diff) +27
-0+} + +static int restrictedmem_setattr(struct user_namespace *mnt_userns, + struct dentry *dentry, struct iattr *attr) +{ + struct inode *inode = d_inode(dentry); + struct restrictedmem_data *data = inode->i_mapping->private_data; + struct file *memfd = data->memfd; + int ret; + + if (attr->ia_valid & ATTR_SIZE) { + if (memfd->f_inode->i_size) + return -EPERM; + + if (!PAGE_ALIGNED(attr->ia_size)) + return -EINVAL; + } + + ret = memfd->f_inode->i_op->setattr(mnt_userns, + file_dentry(memfd), attr); + return ret; +} + +static const struct inode_operations restrictedmem_iops = { + .getattr = restrictedmem_getattr, + .setattr = restrictedmem_setattr, +};
RE: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 36 lines · Ackerley Tng
Review
Quoted 4 lines
(quoted diff) +3
-0+static int restrictedmem_getattr(struct user_namespace *mnt_userns, + const struct path *path, struct kstat *stat, + u32 request_mask, unsigned int query_flags){
Review
Quoted 7 lines
(quoted diff) +2
-0+ struct inode *inode = d_inode(path->dentry); + struct restrictedmem_data *data = inode->i_mapping-
private_data;(quoted diff) +4
-0+ struct file *memfd = data->memfd; + + return memfd->f_inode->i_op->getattr(mnt_userns, path, stat, + request_mask, query_flags);Instead of calling shmem's
getattr()with path, we should be using the the memfd's path.Otherwise, shmem's
getattr()will use restrictedmem's inode instead of shmem's inode. The private fields will be of the wrong type, and the host will crash whenshmem_is_huge()does SHMEM_SB(inode->i_sb)->huge), sinceinode->i_sb->s_fs_infois NULL for the restrictedmem's superblock.Here's the patch:
mm/restrictedmem.c index renamed from mm/restrictedmem.c +0
-0
37191cd9eed1..06b72d593bd8100644mm/restrictedmem.c +1
-1@@ -84,7 +84,7 @@ static int restrictedmem_getattr(struct user_namespace *mnt_userns, struct restrictedmem *rm = inode->i_mapping->private_data;struct file *memfd = rm->memfd; -return memfd->f_inode->i_op->getattr (mnt_userns, path, stat, +return memfd->f_inode->i_op->getattr (mnt_userns, &memfd- >f_path, stat, request_mask, query_flags);
Quoted 2 lines
}
Nice catch. I also encountered this issue during my work. The fix can further be enforced by shmem:
index c301487be5fb..d850c0190359 100644
mm/shmem.c +3 -2
@@ -472,8 +472,9 @@ bool shmem_is_huge(struct vm_area_struct *vma, struct inode *inode, pgoff_t index, bool shmem_huge_force) {loff_t i_size; +struct shmem_sb_info *sbinfo =SHMEM_SB (inode->i_sb); -if (!S_ISREG (inode->i_mode)) +if (!sbinfo || !S_ISREG (inode->i_mode))return false;if (vma && ((vma->vm_flags &VM_NOHUGEPAGE ) ||test_bit (MMF_DISABLE_THP , &vma->vm_mm->flags)))
@@ -485,7 +486,7 @@ bool shmem_is_huge(struct vm_area_struct *vma, struct inode *inode,if (shmem_huge ==SHMEM_HUGE_DENY )return false; -switch (SHMEM_SB (inode->i_sb)->huge) { +switch (sbinfo->huge) {case SHMEM_HUGE_ALWAYS :return true;case SHMEM_HUGE_WITHIN_SIZE :
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
In reply to Chao PengQuoted 11 lines
mm/restrictedmem.c new file +10
-0+static struct file *restrictedmem_file_create (struct file *memfd) +{ +struct restrictedmem_data *data; +struct address_space *mapping; +struct inode *inode; +struct file *file; + + data =kzalloc (sizeof (*data),GFP_KERNEL ); +if (!data) +return ERR_PTR (-ENOMEM );
mm/restrictedmem.c line 183
Quoted 10 lines
mm/restrictedmem.c new file +10
-0+ + data->memfd = memfd; +mutex_init (&data->lock); +INIT_LIST_HEAD (&data->notifiers); + + inode =alloc_anon_inode (restrictedmem_mnt->mnt_sb); +if (IS_ERR (inode)) { +kfree (data); +return ERR_CAST (inode); + }
alloc_anon_inode() uses new_pseudo_inode() to get the inode. As per the comment, new inode is not added to the superblock s_inodes list.
/**
* new_inode_pseudo - obtain an inode
* @sb: superblock
*
* Allocates a new inode for given superblock.
* Inode wont be chained in superblock s_inodes list
* This means :
* - fs can't be unmount
* - quotas, fsnotify, writeback can't work
*/
So the restrictedmem_error_page will not find the inode as it was never added to the s_inodes list.
We might need to add the inode after allocating.
inode_sb_list_add(inode);
Quoted 16 lines
mm/restrictedmem.c new file +16
-0+void restrictedmem_error_page (struct page *page,struct address_space *mapping) +{ +struct super_block *sb = restrictedmem_mnt->mnt_sb; +struct inode *inode, *next; + +if (!shmem_mapping (mapping)) +return ; + +spin_lock (&sb->s_inode_list_lock); +list_for_each_entry_safe (inode, next, &sb->s_inodes, i_sb_list) { +struct restrictedmem_data *data = inode->i_mapping->private_data; +struct file *memfd = data->memfd; + +if (memfd->f_mapping == mapping) { +pgoff_t start, end; +
mm/restrictedmem.c line 318
Quoted 10 lines
mm/restrictedmem.c new file +10
-0+spin_unlock (&sb->s_inode_list_lock); + + start = page->index; + end = start +thp_nr_pages (page); +restrictedmem_notifier_error (data, start, end); +return ; + } + } +spin_unlock (&sb->s_inode_list_lock); +}
Regards
Nikunj
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
Quoted 16 lines · Nikunj A. Dadhania
Quoted 16 lines
mm/restrictedmem.c new file +15
-0+static struct file *restrictedmem_file_create (struct file *memfd) +{ +struct restrictedmem_data *data; +struct address_space *mapping; +struct inode *inode; +struct file *file; + + data =kzalloc (sizeof (*data),GFP_KERNEL ); +if (!data) +return ERR_PTR (-ENOMEM ); + + data->memfd = memfd; +mutex_init (&data->lock); +INIT_LIST_HEAD (&data->notifiers); +
Quoted 8 lines
mm/restrictedmem.c line 183
Quoted 5 lines
mm/restrictedmem.c new file +5
-0+ inode =alloc_anon_inode (restrictedmem_mnt->mnt_sb); +if (IS_ERR (inode)) { +kfree (data); +return ERR_CAST (inode); + }
alloc_anon_inode()usesnew_pseudo_inode()to get the inode. As per the comment, new inode is not added to the superblocks_inodeslist.
Another issue somewhat related to alloc_anon_inode() is that the shmem code in some cases assumes the inode struct was allocated via shmem_alloc_inode(), which allocates a struct shmem_inode_info, which is a superset of struct inode with additional fields for things like spinlocks.
These additional fields don't get allocated/ininitialized in the case of restrictedmem, so when restrictedmem_getattr() tries to pass the inode on to shmem handler, it can cause a crash.
For instance, the following trace was seen when executing 'sudo lsof' while a process/guest was running with an open memfd FD:
[24393.121409] general protection fault, probably for non-canonical address 0xfe9fb182fea3f077: 0000 [#1] PREEMPT SMP NOPTI
[24393.133546] CPU: 2 PID: 590073 Comm: lsof Tainted: G E 6.1.0-rc4-upm10b-host-snp-v8b+ #4
[24393.144125] Hardware name: AMD Corporation ETHANOL_X/ETHANOL_X, BIOS RXM1009B 05/14/2022
[24393.153150] RIP: 0010:native_queued_spin_lock_slowpath+0x3a3/0x3e0
[24393.160049] Code: f3 90 41 8b 04 24 85 c0 74 ea eb f4 c1 ea 12 83 e0 03 83 ea 01 48 c1 e0 05 48 63 d2 48 05 00 41 04 00 48 03 04 d5 e0 ea 8b 82 <48> 89 18 8b 43 08 85 c0 75 09 f3 90 8b 43 08 85 c0 74 f7 48 8b 13
[24393.181004] RSP: 0018:ffffc9006b6a3cf8 EFLAGS: 00010086
[24393.186832] RAX: fe9fb182fea3f077 RBX: ffff889fcc144100 RCX: 0000000000000000
[24393.194793] RDX: 0000000000003ffe RSI: ffffffff827acde9 RDI: ffffc9006b6a3cdf
[24393.202751] RBP: ffffc9006b6a3d20 R08: 0000000000000001 R09: 0000000000000000
[24393.210710] R10: 0000000000000000 R11: 000000000000ffff R12: ffff888179fa50e0
[24393.218670] R13: ffff889fcc144100 R14: 00000000000c0000 R15: 00000000000c0000
[24393.226629] FS: 00007f9440f45400(0000) GS:ffff889fcc100000(0000) knlGS:0000000000000000
[24393.235692] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[24393.242101] CR2: 000055c55a9cf088 CR3: 0008000220e9c003 CR4: 0000000000770ee0
[24393.250059] PKRU: 55555554
[24393.253073] Call Trace:
[24393.255797] <TASK>
[24393.258133] do_raw_spin_lock+0xc4/0xd0
[24393.262410] _raw_spin_lock_irq+0x50/0x70
[24393.266880] ? shmem_getattr+0x4c/0xf0
[24393.271060] shmem_getattr+0x4c/0xf0
[24393.275044] restrictedmem_getattr+0x34/0x40
[24393.279805] vfs_getattr_nosec+0xbd/0xe0
[24393.284178] vfs_getattr+0x37/0x50
[24393.287971] vfs_statx+0xa0/0x150
[24393.291668] vfs_fstatat+0x59/0x80
[24393.295462] __do_sys_newstat+0x35/0x70
[24393.299739] __x64_sys_newstat+0x16/0x20
[24393.304111] do_syscall_64+0x3b/0x90
[24393.308098] entry_SYSCALL_64_after_hwframe+0x63/0xcdAs a workaround we've been doing the following, but it's probably not the proper fix:
https://github.com/AMDESE/linux/commit/0378116b5c4e373295c9101727f2cb5112d6b1f4
-Mike
Re: [PATCH v10 1/9] mm: Introduce memfd_restricted system call to create restricted user memory
In reply to Chao PengQuoted 18 lines · Chao Peng
From: "Kirill A. Shutemov" <[email protected]>
Introduce '
memfd_restricted' system call with the ability to create memory areas that are restricted from userspace access through ordinary MMU operations (e.g. read/write/mmap). The memory content is expected to be used through the new in-kernel interface by a third kernel module....
mm/restrictedmem.c new file +3
-0@@ -0,0 +1,318 @@ +// SPDX-License-Identifier: GPL-2.0 +#include "linux/sbitmap.h" +#include <linux/pagemap.h>
mm/restrictedmem.c line 13
Quoted 10 lines
mm/restrictedmem.c new file +10
-0+#include <linux/pseudo_fs.h> +#include <linux/shmem_fs.h> +#include <linux/syscalls.h> +#include <uapi/linux/falloc.h> +#include <uapi/linux/magic.h> +#include <linux/restrictedmem.h> + +struct restrictedmem_data { +struct mutex lock; +struct file *memfd;
Can this be renamed to file, or lower_file (as in stacking filesystems)?
It's a little confusing because this pointer doesn't actually refer to an fd.
'memfd' is already used by udmabuf to refer to an actual fd [1], which makes this a little misleading.
Quoted 4 lines
mm/restrictedmem.c new file +3
-0+struct list_head notifiers; +}; +
PATCH v10 2/9 KVM: Introduce per-page memory attributes
In reply to Chao PengIn confidential computing usages, whether a page is private or shared is necessary information for KVM to perform operations like page fault handling, page zapping etc. There are other potential use cases for per-page memory attributes, e.g. to make memory read-only (or no-exec, or exec-only, etc.) without having to modify memslots.
Introduce two ioctls (advertised by KVM_CAP_MEMORY_ATTRIBUTES) to allow userspace to operate on the per-page memory attributes.
- KVM_SET_MEMORY_ATTRIBUTES to set the per-page memory attributes to a guest memory range.
- KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES to return the KVM supported memory attributes.
KVM internally uses xarray to store the per-page memory attributes.
--- Documentation/virt/kvm/api.rst | 63 ++++++++++++++++++++++++++++ arch/x86/kvm/Kconfig | 1 + include/linux/kvm_host.h | 3 ++ include/uapi/linux/kvm.h | 17 ++++++++ virt/kvm/Kconfig | 3 ++ virt/kvm/kvm_main.c | 76 ++++++++++++++++++++++++++++++++++ 6 files changed, 163 insertions(+)
Documentation/virt/kvm/api.rst +63 -0
@@ -5952,6 +5952,59 @@ delivery must be provided via the "reg_aen" struct. The "pad" and "reserved" fields may be used for future extensions and should be set to 0s by userspace. +4.138 KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: u64 memory attributes bitmask(out) +:Returns: 0 on success, <0 on error + +Returns supported memory attributes bitmask. Supported memory attributes will +have the corresponding bits set in u64 memory attributes bitmask. + +The following memory attributes are defined:: + + #define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) + #define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) + #define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) + #define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) + +4.139 KVM_SET_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: struct kvm_memory_attributes(in/out) +:Returns: 0 on success, <0 on error + +Sets memory attributes for pages in a guest memory range. Parameters are +specified via the following structure:: + + struct kvm_memory_attributes { + __u64 address; + __u64 size; + __u64 attributes; + __u64 flags; + }; + +The user sets the per-page memory attributes to a guest memory range indicated +by address/size, and in return KVM adjusts address and size to reflect the +actual pages of the memory range have been successfully set to the attributes. +If the call returns 0, "address" is updated to the last successful address + 1 +and "size" is updated to the remaining address size that has not been set +successfully. The user should check the return value as well as the size to +decide if the operation succeeded for the whole range or not. The user may want +to retry the operation with the returned address/size if the previous range was +partially successful. + +Both address and size should be page aligned and the supported attributes can be +retrieved with KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES. + +The "flags" field may be used for future extensions and should be set to 0s. + 5. The kvm_run structure ========================
@@ -8270,6 +8323,16 @@ structure. When getting the Modified Change Topology Report value, the attr->addr must point to a byte where the value will be stored or retrieved from. +8.40 KVM_CAP_MEMORY_ATTRIBUTES +------------------------------ + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm + +This capability indicates KVM supports per-page memory attributes and ioctls +KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES/KVM_SET_MEMORY_ATTRIBUTES are available. + 9. Known KVM API problems =========================
arch/x86/kvm/Kconfig +1 -0
@@ -49,6 +49,7 @@ config KVM select SRCU select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM + select HAVE_KVM_MEMORY_ATTRIBUTES help Support hosting fully virtualized guest machines using hardware virtualization extensions. You will need a fairly recent
include/linux/kvm_host.h +3 -0
@@ -800,6 +800,9 @@ struct kvm {#ifdef CONFIG_HAVE_KVM_PM_NOTIFIER struct notifier_block pm_notifier; +#endif +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +struct xarray mem_attr_array;#endif char stats_id[KVM_STATS_NAME_SIZE ]; };
include/uapi/linux/kvm.h +17 -0
@@ -1182,6 +1182,7 @@ struct kvm_ppc_resize_hpt {#define KVM_CAP_S390_CPU_TOPOLOGY 222#define KVM_CAP_DIRTY_LOG_RING_ACQ_REL 223#define KVM_CAP_S390_PROTECTED_ASYNC_DISABLE 224 +#define KVM_CAP_MEMORY_ATTRIBUTES 225#ifdef KVM_CAP_IRQ_ROUTING
@@ -2238,4 +2239,20 @@ struct kvm_s390_zpci_op {/* flags for kvm_s390_zpci_op->u.reg_aen.flags */ #define KVM_S390_ZPCIOP_REGAEN_HOST (1 << 0) +/* Available with KVM_CAP_MEMORY_ATTRIBUTES */ +#define KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES _IOR(KVMIO, 0xd2, __u64) +#define KVM_SET_MEMORY_ATTRIBUTES _IOWR(KVMIO, 0xd3, struct kvm_memory_attributes) + +struct kvm_memory_attributes { +__u64 address; +__u64 size; +__u64 attributes; +__u64 flags; +}; + +#define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) +#define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) +#define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) +#define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) +#endif /* __LINUX_KVM_H */
virt/kvm/Kconfig +3 -0
@@ -19,6 +19,9 @@ config HAVE_KVM_IRQ_ROUTING config HAVE_KVM_DIRTY_RING bool +config HAVE_KVM_MEMORY_ATTRIBUTES + bool + # Only strongly ordered architectures can select this, as it doesn't # put any explicit constraint on userspace ordering. They can also # select the _ACQ_REL version.
virt/kvm/kvm_main.c +76 -0
106 lines not on this page · raw message
Signature · 1 line
2.25.1
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 66 lines · Chao Peng
In confidential computing usages, whether a page is private or shared is necessary information for KVM to perform operations like page fault handling, page zapping etc. There are other potential use cases for per-page memory attributes, e.g. to make memory read-only (or no-exec, or exec-only, etc.) without having to modify memslots.
Introduce two ioctls (advertised by
KVM_CAP_MEMORY_ATTRIBUTES) to allow userspace to operate on the per-page memory attributes.
-KVM_SET_MEMORY_ATTRIBUTESto set the per-page memory attributes to a guest memory range.
-KVM_GET_SUPPORTED_MEMORY_ATTRIBUTESto return the KVM supported memory attributes.KVM internally uses xarray to store the per-page memory attributes.
Suggested-by Sean Christopherson <[email protected]>Signed-off-by Chao Peng <[email protected]>--- Documentation/virt/kvm/api.rst | 63 ++++++++++++++++++++++++++++ arch/x86/kvm/Kconfig | 1 + include/linux/kvm_host.h | 3 ++ include/uapi/linux/kvm.h | 17 ++++++++ virt/kvm/Kconfig | 3 ++ virt/kvm/kvm_main.c | 76 ++++++++++++++++++++++++++++++++++ 6 files changed, 163 insertions(+)Documentation/virt/kvm/api.rst +31
-0@@ -5952,6 +5952,59 @@ delivery must be provided via the "reg_aen" struct. The "pad" and "reserved" fields may be used for future extensions and should be set to 0s by userspace. +4.138 KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: u64 memory attributes bitmask(out) +:Returns: 0 on success, <0 on error + +Returns supported memory attributes bitmask. Supported memory attributes will +have the corresponding bits set in u64 memory attributes bitmask. + +The following memory attributes are defined:: + + #define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) + #define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) + #define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) + #define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) + +4.139 KVM_SET_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: struct kvm_memory_attributes(in/out) +:Returns: 0 on success, <0 on error + +Sets memory attributes for pages in a guest memory range. Parameters are +specified via the following structure:: +
Documentation/virt/kvm/api.rst delivery must be provided via the "reg_aen" struct. · line 5995
Quoted 10 lines
Documentation/virt/kvm/api.rst +10
-0+ struct kvm_memory_attributes { + __u64 address; + __u64 size; + __u64 attributes; + __u64 flags; + }; + +The user sets the per-page memory attributes to a guest memory range indicated +by address/size, and in return KVM adjusts address and size to reflect the +actual pages of the memory range have been successfully set to the attributes.
This wording could cause some confusion, what about a simpler:
"reflect the range of pages that had its attributes successfully set"
Documentation/virt/kvm/api.rst delivery must be provided via the "reg_aen" struct.
Quoted 3 lines
Documentation/virt/kvm/api.rst +3
-0+If the call returns 0, "address" is updated to the last successful address + 1 +and "size" is updated to the remaining address size that has not been set +successfully.
"address + 1 page" or "subsequent page" perhaps.
In fact, wouldn't this all become simpler if size were number of pages instead?
Quoted 10 lines
The user should check the return value as well as the size to
Documentation/virt/kvm/api.rst +9
-0+decide if the operation succeeded for the whole range or not. The user may want +to retry the operation with the returned address/size if the previous range was +partially successful. + +Both address and size should be page aligned and the supported attributes can be +retrieved with KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES. + +The "flags" field may be used for future extensions and should be set to 0s. +
...
Quoted 10 lines
Documentation/virt/kvm/api.rst +10
-0+static int kvm_vm_ioctl_set_mem_attributes(struct kvm *kvm, + struct kvm_memory_attributes *attrs) +{ + gfn_t start, end; + unsigned long i; + void *entry; + u64 supported_attrs = kvm_supported_mem_attributes(kvm); + + /* flags is currently not used. */ + if (attrs->flags)
Documentation/virt/kvm/api.rst
Quoted 10 lines
Documentation/virt/kvm/api.rst +10
-0+ return -EINVAL; + if (attrs->attributes & ~supported_attrs) + return -EINVAL; + if (attrs->size == 0 || attrs->address + attrs->size < attrs->address) + return -EINVAL; + if (!PAGE_ALIGNED(attrs->address) || !PAGE_ALIGNED(attrs->size)) + return -EINVAL; + + start = attrs->address >> PAGE_SHIFT; + end = (attrs->address + attrs->size - 1 + PAGE_SIZE) >> PAGE_SHIFT;
Here PAGE_SIZE and -1 cancel out.
Consider using gpa_to_gfn as well.
Quoted 60 lines
Documentation/virt/kvm/api.rst +44
-0+ + entry = attrs->attributes ? xa_mk_value(attrs->attributes) : NULL; + + mutex_lock(&kvm->lock); + for (i = start; i < end; i++) + if (xa_err(xa_store(&kvm->mem_attr_array, i, entry, + GFP_KERNEL_ACCOUNT))) + break; + mutex_unlock(&kvm->lock); + + attrs->address = i << PAGE_SHIFT; + attrs->size = (end - i) << PAGE_SHIFT; + + return 0; +} +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ + struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn) { return __gfn_to_memslot(kvm_memslots(kvm), gfn);@@ -4459,6 +4508,9 @@ static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg) #ifdef CONFIG_HAVE_KVM_MSI case KVM_CAP_SIGNAL_MSI: #endif +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES + case KVM_CAP_MEMORY_ATTRIBUTES: +#endif #ifdef CONFIG_HAVE_KVM_IRQFD case KVM_CAP_IRQFD: case KVM_CAP_IRQFD_RESAMPLE:@@ -4804,6 +4856,30 @@ static long kvm_vm_ioctl(struct file *filp, break; } #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */ +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES + case KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES: { + u64 attrs = kvm_supported_mem_attributes(kvm); + + r = -EFAULT; + if (copy_to_user(argp, &attrs, sizeof(attrs))) + goto out; + r = 0; + break; + } + case KVM_SET_MEMORY_ATTRIBUTES: { + struct kvm_memory_attributes attrs; + + r = -EFAULT; + if (copy_from_user(&attrs, argp, sizeof(attrs))) + goto out; + + r = kvm_vm_ioctl_set_mem_attributes(kvm, &attrs); + + if (!r && copy_to_user(argp, &attrs, sizeof(attrs))) + r = -EFAULT; + break; + } +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ case KVM_CREATE_DEVICE: { struct kvm_create_device cd;
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 81 lines · Fabiano Rosas
Quoted 66 lines · Chao Peng
In confidential computing usages, whether a page is private or shared is necessary information for KVM to perform operations like page fault handling, page zapping etc. There are other potential use cases for per-page memory attributes, e.g. to make memory read-only (or no-exec, or exec-only, etc.) without having to modify memslots.
Introduce two ioctls (advertised by
KVM_CAP_MEMORY_ATTRIBUTES) to allow userspace to operate on the per-page memory attributes.
-KVM_SET_MEMORY_ATTRIBUTESto set the per-page memory attributes to a guest memory range.
-KVM_GET_SUPPORTED_MEMORY_ATTRIBUTESto return the KVM supported memory attributes.KVM internally uses xarray to store the per-page memory attributes.
Suggested-by Sean Christopherson <[email protected]>Signed-off-by Chao Peng <[email protected]>--- Documentation/virt/kvm/api.rst | 63 ++++++++++++++++++++++++++++ arch/x86/kvm/Kconfig | 1 + include/linux/kvm_host.h | 3 ++ include/uapi/linux/kvm.h | 17 ++++++++ virt/kvm/Kconfig | 3 ++ virt/kvm/kvm_main.c | 76 ++++++++++++++++++++++++++++++++++ 6 files changed, 163 insertions(+)Documentation/virt/kvm/api.rst +31
-0@@ -5952,6 +5952,59 @@ delivery must be provided via the "reg_aen" struct. The "pad" and "reserved" fields may be used for future extensions and should be set to 0s by userspace. +4.138 KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: u64 memory attributes bitmask(out) +:Returns: 0 on success, <0 on error + +Returns supported memory attributes bitmask. Supported memory attributes will +have the corresponding bits set in u64 memory attributes bitmask. + +The following memory attributes are defined:: + + #define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) + #define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) + #define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) + #define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) + +4.139 KVM_SET_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: struct kvm_memory_attributes(in/out) +:Returns: 0 on success, <0 on error + +Sets memory attributes for pages in a guest memory range. Parameters are +specified via the following structure:: +Documentation/virt/kvm/api.rst delivery must be provided via the "reg_aen" struct. · line 5995
Quoted 10 lines
Documentation/virt/kvm/api.rst +10
-0+ struct kvm_memory_attributes { + __u64 address; + __u64 size; + __u64 attributes; + __u64 flags; + }; + +The user sets the per-page memory attributes to a guest memory range indicated +by address/size, and in return KVM adjusts address and size to reflect the +actual pages of the memory range have been successfully set to the attributes.This wording could cause some confusion, what about a simpler:
Quoted 1 line
"reflect the range of pages that had its attributes successfully set"
Thanks, this is much better.
Quoted 8 lines
Documentation/virt/kvm/api.rst delivery must be provided via the "reg_aen" struct.
Quoted 4 lines
Documentation/virt/kvm/api.rst +3
-0+If the call returns 0, "address" is updated to the last successful address + 1 +and "size" is updated to the remaining address size that has not been set +successfully."address + 1 page" or "subsequent page" perhaps.
In fact, wouldn't this all become simpler if size were number of pages instead?
It indeed becomes better if the size is number of pages and the address is gfn, but I think we don't want to imply that the page size is 4K to userspace.
Quoted 28 lines
Quoted 11 lines
The user should check the return value as well as the size to
Documentation/virt/kvm/api.rst +9
-0+decide if the operation succeeded for the whole range or not. The user may want +to retry the operation with the returned address/size if the previous range was +partially successful. + +Both address and size should be page aligned and the supported attributes can be +retrieved with KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES. + +The "flags" field may be used for future extensions and should be set to 0s. +...
Quoted 14 lines
Documentation/virt/kvm/api.rst +14
-0+static int kvm_vm_ioctl_set_mem_attributes(struct kvm *kvm, + struct kvm_memory_attributes *attrs) +{ + gfn_t start, end; + unsigned long i; + void *entry; + u64 supported_attrs = kvm_supported_mem_attributes(kvm); + + /* flags is currently not used. */ + if (attrs->flags) + return -EINVAL; + if (attrs->attributes & ~supported_attrs) + return -EINVAL; + if (attrs->size == 0 || attrs->address + attrs->size < attrs->address)
Quoted 8 lines
Documentation/virt/kvm/api.rst
Quoted 6 lines
Documentation/virt/kvm/api.rst +6
-0+ return -EINVAL; + if (!PAGE_ALIGNED(attrs->address) || !PAGE_ALIGNED(attrs->size)) + return -EINVAL; + + start = attrs->address >> PAGE_SHIFT; + end = (attrs->address + attrs->size - 1 + PAGE_SIZE) >> PAGE_SHIFT;Here
PAGE_SIZEand -1 cancel out.
Correct!
Quoted 2 lines
Consider using
gpa_to_gfnas well.
Yes using gpa_to_gfn is appropriate.
Thanks,
Chao
Quoted 61 lines
Quoted 61 lines
Documentation/virt/kvm/api.rst +44
-0+ + entry = attrs->attributes ? xa_mk_value(attrs->attributes) : NULL; + + mutex_lock(&kvm->lock); + for (i = start; i < end; i++) + if (xa_err(xa_store(&kvm->mem_attr_array, i, entry, + GFP_KERNEL_ACCOUNT))) + break; + mutex_unlock(&kvm->lock); + + attrs->address = i << PAGE_SHIFT; + attrs->size = (end - i) << PAGE_SHIFT; + + return 0; +} +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ + struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn) { return __gfn_to_memslot(kvm_memslots(kvm), gfn);@@ -4459,6 +4508,9 @@ static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg) #ifdef CONFIG_HAVE_KVM_MSI case KVM_CAP_SIGNAL_MSI: #endif +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES + case KVM_CAP_MEMORY_ATTRIBUTES: +#endif #ifdef CONFIG_HAVE_KVM_IRQFD case KVM_CAP_IRQFD: case KVM_CAP_IRQFD_RESAMPLE:@@ -4804,6 +4856,30 @@ static long kvm_vm_ioctl(struct file *filp, break; } #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */ +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES + case KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES: { + u64 attrs = kvm_supported_mem_attributes(kvm); + + r = -EFAULT; + if (copy_to_user(argp, &attrs, sizeof(attrs))) + goto out; + r = 0; + break; + } + case KVM_SET_MEMORY_ATTRIBUTES: { + struct kvm_memory_attributes attrs; + + r = -EFAULT; + if (copy_from_user(&attrs, argp, sizeof(attrs))) + goto out; + + r = kvm_vm_ioctl_set_mem_attributes(kvm, &attrs); + + if (!r && copy_to_user(argp, &attrs, sizeof(attrs))) + r = -EFAULT; + break; + } +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ case KVM_CREATE_DEVICE: { struct kvm_create_device cd;
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
In reply to Chao PengHi,
Quoted 156 lines · Chao Peng
In confidential computing usages, whether a page is private or shared is necessary information for KVM to perform operations like page fault handling, page zapping etc. There are other potential use cases for per-page memory attributes, e.g. to make memory read-only (or no-exec, or exec-only, etc.) without having to modify memslots.
Introduce two ioctls (advertised by
KVM_CAP_MEMORY_ATTRIBUTES) to allow userspace to operate on the per-page memory attributes.
-KVM_SET_MEMORY_ATTRIBUTESto set the per-page memory attributes to a guest memory range.
-KVM_GET_SUPPORTED_MEMORY_ATTRIBUTESto return the KVM supported memory attributes.KVM internally uses xarray to store the per-page memory attributes.
Suggested-by Sean Christopherson <[email protected]>Signed-off-by Chao Peng <[email protected]>--- Documentation/virt/kvm/api.rst | 63 ++++++++++++++++++++++++++++ arch/x86/kvm/Kconfig | 1 + include/linux/kvm_host.h | 3 ++ include/uapi/linux/kvm.h | 17 ++++++++ virt/kvm/Kconfig | 3 ++ virt/kvm/kvm_main.c | 76 ++++++++++++++++++++++++++++++++++ 6 files changed, 163 insertions(+)Documentation/virt/kvm/api.rst +63
-0@@ -5952,6 +5952,59 @@ delivery must be provided via the "reg_aen" struct. The "pad" and "reserved" fields may be used for future extensions and should be set to 0s by userspace. +4.138 KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: u64 memory attributes bitmask(out) +:Returns: 0 on success, <0 on error + +Returns supported memory attributes bitmask. Supported memory attributes will +have the corresponding bits set in u64 memory attributes bitmask. + +The following memory attributes are defined:: + + #define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) + #define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) + #define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) + #define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) + +4.139 KVM_SET_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: struct kvm_memory_attributes(in/out) +:Returns: 0 on success, <0 on error + +Sets memory attributes for pages in a guest memory range. Parameters are +specified via the following structure:: + + struct kvm_memory_attributes { + __u64 address; + __u64 size; + __u64 attributes; + __u64 flags; + }; + +The user sets the per-page memory attributes to a guest memory range indicated +by address/size, and in return KVM adjusts address and size to reflect the +actual pages of the memory range have been successfully set to the attributes. +If the call returns 0, "address" is updated to the last successful address + 1 +and "size" is updated to the remaining address size that has not been set +successfully. The user should check the return value as well as the size to +decide if the operation succeeded for the whole range or not. The user may want +to retry the operation with the returned address/size if the previous range was +partially successful. + +Both address and size should be page aligned and the supported attributes can be +retrieved with KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES. + +The "flags" field may be used for future extensions and should be set to 0s. + 5. The kvm_run structure ========================@@ -8270,6 +8323,16 @@ structure. When getting the Modified Change Topology Report value, the attr->addr must point to a byte where the value will be stored or retrieved from. +8.40 KVM_CAP_MEMORY_ATTRIBUTES +------------------------------ + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm + +This capability indicates KVM supports per-page memory attributes and ioctls +KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES/KVM_SET_MEMORY_ATTRIBUTES are available. + 9. Known KVM API problems =========================arch/x86/kvm/Kconfig +1
-0@@ -49,6 +49,7 @@ config KVM select SRCU select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM + select HAVE_KVM_MEMORY_ATTRIBUTES help Support hosting fully virtualized guest machines using hardware virtualization extensions. You will need a fairly recentinclude/linux/kvm_host.h +3
-0@@ -800,6 +800,9 @@ struct kvm {#ifdef CONFIG_HAVE_KVM_PM_NOTIFIER struct notifier_block pm_notifier; +#endif +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +struct xarray mem_attr_array;#endif char stats_id[KVM_STATS_NAME_SIZE ]; };include/uapi/linux/kvm.h +6
-0@@ -1182,6 +1182,7 @@ struct kvm_ppc_resize_hpt {#define KVM_CAP_S390_CPU_TOPOLOGY 222#define KVM_CAP_DIRTY_LOG_RING_ACQ_REL 223#define KVM_CAP_S390_PROTECTED_ASYNC_DISABLE 224 +#define KVM_CAP_MEMORY_ATTRIBUTES 225#ifdef KVM_CAP_IRQ_ROUTING @@ -2238,4 +2239,20 @@ struct kvm_s390_zpci_op {/* flags for kvm_s390_zpci_op->u.reg_aen.flags */ #define KVM_S390_ZPCIOP_REGAEN_HOST (1 << 0) +/* Available with KVM_CAP_MEMORY_ATTRIBUTES */ +#define KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES _IOR(KVMIO, 0xd2, __u64) +#define KVM_SET_MEMORY_ATTRIBUTES _IOWR(KVMIO, 0xd3, struct kvm_memory_attributes) + +struct kvm_memory_attributes {
include/uapi/linux/kvm.h struct kvm_s390_zpci_op { · line 2256
Quoted 10 lines
include/uapi/linux/kvm.h +10
-0+__u64 address; +__u64 size; +__u64 attributes; +__u64 flags; +}; + +#define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) +#define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) +#define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) +#define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3)
nit: how about using the BIT() macro for these?
Quoted 49 lines
include/uapi/linux/kvm.h +1
-0+#endif /* __LINUX_KVM_H */ virt/kvm/Kconfig +3
-0@@ -19,6 +19,9 @@ config HAVE_KVM_IRQ_ROUTING config HAVE_KVM_DIRTY_RING bool +config HAVE_KVM_MEMORY_ATTRIBUTES + bool + # Only strongly ordered architectures can select this, as it doesn't # put any explicit constraint on userspace ordering. They can also # select the _ACQ_REL version.virt/kvm/kvm_main.c +11
-0@@ -1150,6 +1150,9 @@ static struct kvm *kvm_create_vm(unsigned long type, const char *fdname)spin_lock_init (&kvm->mn_invalidate_lock);rcuwait_init (&kvm->mn_memslots_update_rcuwait);xa_init (&kvm->vcpu_array); +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +xa_init (&kvm->mem_attr_array); +#endif INIT_LIST_HEAD (&kvm->gpc_list);spin_lock_init (&kvm->gpc_lock);@@ -1323,6 +1326,9 @@ static void kvm_destroy_vm(struct kvm *kvm)kvm_free_memslots (kvm, &kvm->__memslots[i][0 ]);kvm_free_memslots (kvm, &kvm->__memslots[i][1 ]); } +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +xa_destroy (&kvm->mem_attr_array); +#endif cleanup_srcu_struct (&kvm->irq_srcu);cleanup_srcu_struct (&kvm->srcu);kvm_arch_free_vm (kvm);@@ -2323,6 +2329,49 @@ static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, }#endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */ +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +static u64 kvm_supported_mem_attributes (struct kvm *kvm) +{ +return 0 ; +}
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2346
Quoted 10 lines
virt/kvm/kvm_main.c +10
-0+ +static int kvm_vm_ioctl_set_mem_attributes (struct kvm *kvm, +struct kvm_memory_attributes *attrs) +{ +gfn_t start, end; +unsigned long i; +void *entry; +u64 supported_attrs =kvm_supported_mem_attributes (kvm); + +/* flags is currently not used. */
nit: "is reserved"? I think it makes it a bit clearer what its purpose is.
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2357
Quoted 11 lines
virt/kvm/kvm_main.c +11
-0+if (attrs->flags) +return -EINVAL ; +if (attrs->attributes & ~supported_attrs) +return -EINVAL ; +if (attrs->size ==0 || attrs->address + attrs->size < attrs->address) +return -EINVAL ; +if (!PAGE_ALIGNED (attrs->address) || !PAGE_ALIGNED (attrs->size)) +return -EINVAL ; + + start = attrs->address >>PAGE_SHIFT ; + end = (attrs->address + attrs->size -1 +PAGE_SIZE ) >>PAGE_SHIFT ;
Would using existing helpers be better for getting the frame numbers? Also, the code checks that the address and size are page aligned, so the end rounding up seems redundant, and might even be wrong if the address+size-1 is close to the gfn_t limit (which this code tries to avoid in an earlier check).
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2369
Quoted 11 lines
virt/kvm/kvm_main.c +11
-0+ entry = attrs->attributes ?xa_mk_value (attrs->attributes) :NULL ; + +mutex_lock (&kvm->lock); +for (i = start; i < end; i++) +if (xa_err (xa_store (&kvm->mem_attr_array, i, entry, +GFP_KERNEL_ACCOUNT ))) +break ; +mutex_unlock (&kvm->lock); + + attrs->address = i <<PAGE_SHIFT ; + attrs->size = (end - i) <<PAGE_SHIFT ;
nit: helpers for these too?
With the end calculation fixed,
After adding the necessary configs for arm64 (on qemu/arm64):
Cheers,
/fuad
Quoted 52 lines
virt/kvm/kvm_main.c +32
-1+ + return 0; +} +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ +struct kvm_memory_slot *gfn_to_memslot (struct kvm *kvm,gfn_t gfn) {return __gfn_to_memslot (kvm_memslots (kvm), gfn);@@ -4459,6 +4508,9 @@ static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)#ifdef CONFIG_HAVE_KVM_MSI case KVM_CAP_SIGNAL_MSI :#endif +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +case KVM_CAP_MEMORY_ATTRIBUTES : +#endif #ifdef CONFIG_HAVE_KVM_IRQFD case KVM_CAP_IRQFD :case KVM_CAP_IRQFD_RESAMPLE :@@ -4804,6 +4856,30 @@ static long kvm_vm_ioctl(struct file *filp, break; }#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */ +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +case KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES : { +u64 attrs =kvm_supported_mem_attributes (kvm); + + r = -EFAULT ; +if (copy_to_user (argp, &attrs,sizeof (attrs))) + goto out; + r =0 ; +break ; + } +case KVM_SET_MEMORY_ATTRIBUTES : { +struct kvm_memory_attributes attrs; + + r = -EFAULT ; +if (copy_from_user (&attrs, argp,sizeof (attrs))) + goto out; + + r =kvm_vm_ioctl_set_mem_attributes (kvm, &attrs); + +if (!r &©_to_user (argp, &attrs,sizeof (attrs))) + r = -EFAULT ; +break ; + } +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ case KVM_CREATE_DEVICE : {struct kvm_create_device cd; --2.25.1
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 163 lines · Fuad Tabba
Hi,
Quoted 160 lines · Chao Peng
In confidential computing usages, whether a page is private or shared is necessary information for KVM to perform operations like page fault handling, page zapping etc. There are other potential use cases for per-page memory attributes, e.g. to make memory read-only (or no-exec, or exec-only, etc.) without having to modify memslots.
Introduce two ioctls (advertised by
KVM_CAP_MEMORY_ATTRIBUTES) to allow userspace to operate on the per-page memory attributes.
-KVM_SET_MEMORY_ATTRIBUTESto set the per-page memory attributes to a guest memory range.
-KVM_GET_SUPPORTED_MEMORY_ATTRIBUTESto return the KVM supported memory attributes.KVM internally uses xarray to store the per-page memory attributes.
Suggested-by Sean Christopherson <[email protected]>Signed-off-by Chao Peng <[email protected]>--- Documentation/virt/kvm/api.rst | 63 ++++++++++++++++++++++++++++ arch/x86/kvm/Kconfig | 1 + include/linux/kvm_host.h | 3 ++ include/uapi/linux/kvm.h | 17 ++++++++ virt/kvm/Kconfig | 3 ++ virt/kvm/kvm_main.c | 76 ++++++++++++++++++++++++++++++++++ 6 files changed, 163 insertions(+)Documentation/virt/kvm/api.rst +63
-0@@ -5952,6 +5952,59 @@ delivery must be provided via the "reg_aen" struct. The "pad" and "reserved" fields may be used for future extensions and should be set to 0s by userspace. +4.138 KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: u64 memory attributes bitmask(out) +:Returns: 0 on success, <0 on error + +Returns supported memory attributes bitmask. Supported memory attributes will +have the corresponding bits set in u64 memory attributes bitmask. + +The following memory attributes are defined:: + + #define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) + #define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) + #define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) + #define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) + +4.139 KVM_SET_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: struct kvm_memory_attributes(in/out) +:Returns: 0 on success, <0 on error + +Sets memory attributes for pages in a guest memory range. Parameters are +specified via the following structure:: + + struct kvm_memory_attributes { + __u64 address; + __u64 size; + __u64 attributes; + __u64 flags; + }; + +The user sets the per-page memory attributes to a guest memory range indicated +by address/size, and in return KVM adjusts address and size to reflect the +actual pages of the memory range have been successfully set to the attributes. +If the call returns 0, "address" is updated to the last successful address + 1 +and "size" is updated to the remaining address size that has not been set +successfully. The user should check the return value as well as the size to +decide if the operation succeeded for the whole range or not. The user may want +to retry the operation with the returned address/size if the previous range was +partially successful. + +Both address and size should be page aligned and the supported attributes can be +retrieved with KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES. + +The "flags" field may be used for future extensions and should be set to 0s. + 5. The kvm_run structure ========================@@ -8270,6 +8323,16 @@ structure. When getting the Modified Change Topology Report value, the attr->addr must point to a byte where the value will be stored or retrieved from. +8.40 KVM_CAP_MEMORY_ATTRIBUTES +------------------------------ + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm + +This capability indicates KVM supports per-page memory attributes and ioctls +KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES/KVM_SET_MEMORY_ATTRIBUTES are available. + 9. Known KVM API problems =========================arch/x86/kvm/Kconfig +1
-0@@ -49,6 +49,7 @@ config KVM select SRCU select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM + select HAVE_KVM_MEMORY_ATTRIBUTES help Support hosting fully virtualized guest machines using hardware virtualization extensions. You will need a fairly recentinclude/linux/kvm_host.h +3
-0@@ -800,6 +800,9 @@ struct kvm {#ifdef CONFIG_HAVE_KVM_PM_NOTIFIER struct notifier_block pm_notifier; +#endif +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +struct xarray mem_attr_array;#endif char stats_id[KVM_STATS_NAME_SIZE ]; };include/uapi/linux/kvm.h +10
-0@@ -1182,6 +1182,7 @@ struct kvm_ppc_resize_hpt {#define KVM_CAP_S390_CPU_TOPOLOGY 222#define KVM_CAP_DIRTY_LOG_RING_ACQ_REL 223#define KVM_CAP_S390_PROTECTED_ASYNC_DISABLE 224 +#define KVM_CAP_MEMORY_ATTRIBUTES 225#ifdef KVM_CAP_IRQ_ROUTING @@ -2238,4 +2239,20 @@ struct kvm_s390_zpci_op {/* flags for kvm_s390_zpci_op->u.reg_aen.flags */ #define KVM_S390_ZPCIOP_REGAEN_HOST (1 << 0) +/* Available with KVM_CAP_MEMORY_ATTRIBUTES */ +#define KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES _IOR(KVMIO, 0xd2, __u64) +#define KVM_SET_MEMORY_ATTRIBUTES _IOWR(KVMIO, 0xd3, struct kvm_memory_attributes) + +struct kvm_memory_attributes { +__u64 address; +__u64 size; +__u64 attributes; +__u64 flags;
Quoted 8 lines
include/uapi/linux/kvm.h struct kvm_s390_zpci_op { · line 2256
Quoted 6 lines
include/uapi/linux/kvm.h +6
-0+}; + +#define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) +#define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) +#define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) +#define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3)nit: how about using the
BIT()macro for these?
Might be the _BITULL() in include/uapi/linux/const.h since it will be used by userspace also.
Quoted 54 lines
Quoted 54 lines
include/uapi/linux/kvm.h +1
-0+#endif /* __LINUX_KVM_H */ virt/kvm/Kconfig +3
-0@@ -19,6 +19,9 @@ config HAVE_KVM_IRQ_ROUTING config HAVE_KVM_DIRTY_RING bool +config HAVE_KVM_MEMORY_ATTRIBUTES + bool + # Only strongly ordered architectures can select this, as it doesn't # put any explicit constraint on userspace ordering. They can also # select the _ACQ_REL version.virt/kvm/kvm_main.c +15
-0@@ -1150,6 +1150,9 @@ static struct kvm *kvm_create_vm(unsigned long type, const char *fdname)spin_lock_init (&kvm->mn_invalidate_lock);rcuwait_init (&kvm->mn_memslots_update_rcuwait);xa_init (&kvm->vcpu_array); +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +xa_init (&kvm->mem_attr_array); +#endif INIT_LIST_HEAD (&kvm->gpc_list);spin_lock_init (&kvm->gpc_lock);@@ -1323,6 +1326,9 @@ static void kvm_destroy_vm(struct kvm *kvm)kvm_free_memslots (kvm, &kvm->__memslots[i][0 ]);kvm_free_memslots (kvm, &kvm->__memslots[i][1 ]); } +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +xa_destroy (&kvm->mem_attr_array); +#endif cleanup_srcu_struct (&kvm->irq_srcu);cleanup_srcu_struct (&kvm->srcu);kvm_arch_free_vm (kvm);@@ -2323,6 +2329,49 @@ static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, }#endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */ +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +static u64 kvm_supported_mem_attributes (struct kvm *kvm) +{ +return 0 ; +} + +static int kvm_vm_ioctl_set_mem_attributes (struct kvm *kvm, +struct kvm_memory_attributes *attrs) +{
Quoted 8 lines
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2346
Quoted 6 lines
virt/kvm/kvm_main.c +6
-0+gfn_t start, end; +unsigned long i; +void *entry; +u64 supported_attrs =kvm_supported_mem_attributes (kvm); + +/* flags is currently not used. */ nit: "is reserved"? I think it makes it a bit clearer what its purpose is.
OK, then:
flags is reserved for future extention and currently is not used.
Quoted 13 lines
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2357
Quoted 12 lines
virt/kvm/kvm_main.c +11
-0+if (attrs->flags) +return -EINVAL ; +if (attrs->attributes & ~supported_attrs) +return -EINVAL ; +if (attrs->size ==0 || attrs->address + attrs->size < attrs->address) +return -EINVAL ; +if (!PAGE_ALIGNED (attrs->address) || !PAGE_ALIGNED (attrs->size)) +return -EINVAL ; + + start = attrs->address >>PAGE_SHIFT ; + end = (attrs->address + attrs->size -1 +PAGE_SIZE ) >>PAGE_SHIFT ;
Quoted 1 line
Would using existing helpers be better for getting the frame numbers?
Yes, gpa_to_gfn() can be used.
Quoted 4 lines
Also, the code checks that the address and size are page aligned, so the end rounding up seems redundant, and might even be wrong if the address+size-1 is close to the
gfn_tlimit (which this code tries to avoid in an earlier check).
That's right.
Quoted 14 lines
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2369
Quoted 12 lines
virt/kvm/kvm_main.c +11
-0+ entry = attrs->attributes ?xa_mk_value (attrs->attributes) :NULL ; + +mutex_lock (&kvm->lock); +for (i = start; i < end; i++) +if (xa_err (xa_store (&kvm->mem_attr_array, i, entry, +GFP_KERNEL_ACCOUNT ))) +break ; +mutex_unlock (&kvm->lock); + + attrs->address = i <<PAGE_SHIFT ; + attrs->size = (end - i) <<PAGE_SHIFT ;nit: helpers for these too?
Similarly, gfn_to_gpa() will be used.
Quoted 6 lines
With the end calculation fixed,
Reviewed-by Fuad Tabba <[email protected]>After adding the necessary configs for arm64 (on qemu/arm64):
Tested-by Fuad Tabba <[email protected]>
Thanks.
Chao
Quoted 56 lines
Cheers,
/fuadQuoted 52 lines
virt/kvm/kvm_main.c +32
-1+ + return 0; +} +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ +struct kvm_memory_slot *gfn_to_memslot (struct kvm *kvm,gfn_t gfn) {return __gfn_to_memslot (kvm_memslots (kvm), gfn);@@ -4459,6 +4508,9 @@ static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)#ifdef CONFIG_HAVE_KVM_MSI case KVM_CAP_SIGNAL_MSI :#endif +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +case KVM_CAP_MEMORY_ATTRIBUTES : +#endif #ifdef CONFIG_HAVE_KVM_IRQFD case KVM_CAP_IRQFD :case KVM_CAP_IRQFD_RESAMPLE :@@ -4804,6 +4856,30 @@ static long kvm_vm_ioctl(struct file *filp, break; }#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */ +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +case KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES : { +u64 attrs =kvm_supported_mem_attributes (kvm); + + r = -EFAULT ; +if (copy_to_user (argp, &attrs,sizeof (attrs))) + goto out; + r =0 ; +break ; + } +case KVM_SET_MEMORY_ATTRIBUTES : { +struct kvm_memory_attributes attrs; + + r = -EFAULT ; +if (copy_from_user (&attrs, argp,sizeof (attrs))) + goto out; + + r =kvm_vm_ioctl_set_mem_attributes (kvm, &attrs); + +if (!r &©_to_user (argp, &attrs,sizeof (attrs))) + r = -EFAULT ; +break ; + } +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ case KVM_CREATE_DEVICE : {struct kvm_create_device cd; --2.25.1
Borislav Petkov
maintainerRe: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
In reply to Chao Pengvirt/kvm/kvm_main.c static struct kvm *kvm_create_vm(unsigned long type, const char *fdname) · line 1155
Quoted 11 lines · Chao Peng
virt/kvm/kvm_main.c +3
-0@@ -1150,6 +1150,9 @@ static struct kvm *kvm_create_vm(unsigned long type, const char *fdname)spin_lock_init (&kvm->mn_invalidate_lock);rcuwait_init (&kvm->mn_memslots_update_rcuwait);xa_init (&kvm->vcpu_array); +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +xa_init (&kvm->mem_attr_array); +#endif
if (IS_ENABLED(CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES)) ...
would at least remove the ugly ifdeffery.
Or you could create wrapper functions for that xa_init() and xa_destroy() and put the ifdeffery in there.
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2333
Quoted 6 lines
virt/kvm/kvm_main.c +2
-0@@ -2323,6 +2329,49 @@ static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, }#endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */ +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +static u64 kvm_supported_mem_attributes (struct kvm *kvm)
I guess that function should have a verb in the name:
kvm_get_supported_mem_attributes()
Quoted 7 lines
virt/kvm/kvm_main.c +7
-0+static int kvm_vm_ioctl_set_mem_attributes (struct kvm *kvm, +struct kvm_memory_attributes *attrs) +{ +gfn_t start, end; +unsigned long i; +void *entry; +u64 supported_attrs =kvm_supported_mem_attributes (kvm);
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2354
Quoted 10 lines
virt/kvm/kvm_main.c +10
-0+ +/* flags is currently not used. */ +if (attrs->flags) +return -EINVAL ; +if (attrs->attributes & ~supported_attrs) +return -EINVAL ; +if (attrs->size ==0 || attrs->address + attrs->size < attrs->address) +return -EINVAL ; +if (!PAGE_ALIGNED (attrs->address) || !PAGE_ALIGNED (attrs->size)) +return -EINVAL ;
Dunno, shouldn't those issue some sort of an error message so that the caller knows where it failed? Or at least return different retvals which signal what the problem is?
Quoted 17 lines
virt/kvm/kvm_main.c +17
-0+ start = attrs->address >>PAGE_SHIFT ; + end = (attrs->address + attrs->size -1 +PAGE_SIZE ) >>PAGE_SHIFT ; + + entry = attrs->attributes ?xa_mk_value (attrs->attributes) :NULL ; + +mutex_lock (&kvm->lock); +for (i = start; i < end; i++) +if (xa_err (xa_store (&kvm->mem_attr_array, i, entry, +GFP_KERNEL_ACCOUNT ))) +break ; +mutex_unlock (&kvm->lock); + + attrs->address = i <<PAGE_SHIFT ; + attrs->size = (end - i) <<PAGE_SHIFT ; + +return 0 ; +}
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteRe: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 16 lines · Borislav Petkov
virt/kvm/kvm_main.c static struct kvm *kvm_create_vm(unsigned long type, const char *fdname) · line 1155
Quoted 11 lines · Chao Peng
virt/kvm/kvm_main.c +3
-0@@ -1150,6 +1150,9 @@ static struct kvm *kvm_create_vm(unsigned long type, const char *fdname)spin_lock_init (&kvm->mn_invalidate_lock);rcuwait_init (&kvm->mn_memslots_update_rcuwait);xa_init (&kvm->vcpu_array); +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +xa_init (&kvm->mem_attr_array); +#endif if (IS_ENABLED(CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES)) ...
Quoted 4 lines
would at least remove the ugly ifdeffery.
Or you could create wrapper functions for that
xa_init()andxa_destroy()and put the ifdeffery in there.
Agreed.
Quoted 11 lines
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2333
Quoted 7 lines
virt/kvm/kvm_main.c +2
-0@@ -2323,6 +2329,49 @@ static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, }#endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */ +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +static u64 kvm_supported_mem_attributes (struct kvm *kvm)I guess that function should have a verb in the name:
kvm_get_supported_mem_attributes()
Right!
Quoted 14 lines
Quoted 14 lines
virt/kvm/kvm_main.c +13
-0+static int kvm_vm_ioctl_set_mem_attributes (struct kvm *kvm, +struct kvm_memory_attributes *attrs) +{ +gfn_t start, end; +unsigned long i; +void *entry; +u64 supported_attrs =kvm_supported_mem_attributes (kvm); + +/* flags is currently not used. */ +if (attrs->flags) +return -EINVAL ; +if (attrs->attributes & ~supported_attrs) +return -EINVAL ;
Quoted 8 lines
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2354
Quoted 4 lines
virt/kvm/kvm_main.c +4
-0+if (attrs->size ==0 || attrs->address + attrs->size < attrs->address) +return -EINVAL ; +if (!PAGE_ALIGNED (attrs->address) || !PAGE_ALIGNED (attrs->size)) +return -EINVAL ;Dunno, shouldn't those issue some sort of an error message so that the caller knows where it failed? Or at least return different retvals which signal what the problem is?
Tamping down with error number a bit:
if (attrs->flags)
return -ENXIO;
if (attrs->attributes & ~supported_attrs)
return -EOPNOTSUPP;
if (!PAGE_ALIGNED(attrs->address) || !PAGE_ALIGNED(attrs->size) ||
attrs->size == 0)
return -EINVAL;
if (attrs->address + attrs->size < attrs->address)
return -E2BIG;Chao
Quoted 24 lines
Quoted 18 lines
virt/kvm/kvm_main.c +17
-0+ start = attrs->address >>PAGE_SHIFT ; + end = (attrs->address + attrs->size -1 +PAGE_SIZE ) >>PAGE_SHIFT ; + + entry = attrs->attributes ?xa_mk_value (attrs->attributes) :NULL ; + +mutex_lock (&kvm->lock); +for (i = start; i < end; i++) +if (xa_err (xa_store (&kvm->mem_attr_array, i, entry, +GFP_KERNEL_ACCOUNT ))) +break ; +mutex_unlock (&kvm->lock); + + attrs->address = i <<PAGE_SHIFT ; + attrs->size = (end - i) <<PAGE_SHIFT ; + +return 0 ; +}Signature · 4 lines
Regards/Gruss, Boris. https://people.kernel.org/tglx/notes-about-netiquette
Borislav Petkov
maintainerRe: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 11 lines · Chao Peng
Tamping down with error number a bit:
if (attrs->flags) return -ENXIO; if (attrs->attributes & ~supported_attrs) return -EOPNOTSUPP; if (!PAGE_ALIGNED(attrs->address) || !PAGE_ALIGNED(attrs->size) || attrs->size == 0) return -EINVAL; if (attrs->address + attrs->size < attrs->address) return -E2BIG;
Yap, better.
I guess you should add those to the documentation of the ioctl too so that people can find out why it fails. Or, well, they can look at the code directly too but still... imagine some blurb about user-friendliness here...
:-)
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteRe: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 13 lines · Borislav Petkov
Quoted 11 lines · Chao Peng
Tamping down with error number a bit:
if (attrs->flags) return -ENXIO; if (attrs->attributes & ~supported_attrs) return -EOPNOTSUPP; if (!PAGE_ALIGNED(attrs->address) || !PAGE_ALIGNED(attrs->size) || attrs->size == 0) return -EINVAL; if (attrs->address + attrs->size < attrs->address) return -E2BIG;
Quoted 6 lines
Yap, better.
I guess you should add those to the documentation of the ioctl too so that people can find out why it fails. Or, well, they can look at the code directly too but still... imagine some blurb about user-friendliness here...
Thanks for reminding. Yes KVM api doc is the right place to put these documentation in.
Thanks,
Chao
Quoted 8 lines
:-)
Signature · 4 lines
Regards/Gruss, Boris. https://people.kernel.org/tglx/notes-about-netiquette
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
In reply to Chao PengQuoted 228 lines · Chao Peng
In confidential computing usages, whether a page is private or shared is necessary information for KVM to perform operations like page fault handling, page zapping etc. There are other potential use cases for per-page memory attributes, e.g. to make memory read-only (or no-exec, or exec-only, etc.) without having to modify memslots.
Introduce two ioctls (advertised by
KVM_CAP_MEMORY_ATTRIBUTES) to allow userspace to operate on the per-page memory attributes.
-KVM_SET_MEMORY_ATTRIBUTESto set the per-page memory attributes to a guest memory range.
-KVM_GET_SUPPORTED_MEMORY_ATTRIBUTESto return the KVM supported memory attributes.KVM internally uses xarray to store the per-page memory attributes.
Suggested-by Sean Christopherson <[email protected]>Signed-off-by Chao Peng <[email protected]>--- Documentation/virt/kvm/api.rst | 63 ++++++++++++++++++++++++++++ arch/x86/kvm/Kconfig | 1 + include/linux/kvm_host.h | 3 ++ include/uapi/linux/kvm.h | 17 ++++++++ virt/kvm/Kconfig | 3 ++ virt/kvm/kvm_main.c | 76 ++++++++++++++++++++++++++++++++++ 6 files changed, 163 insertions(+)Documentation/virt/kvm/api.rst +63
-0@@ -5952,6 +5952,59 @@ delivery must be provided via the "reg_aen" struct. The "pad" and "reserved" fields may be used for future extensions and should be set to 0s by userspace. +4.138 KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: u64 memory attributes bitmask(out) +:Returns: 0 on success, <0 on error + +Returns supported memory attributes bitmask. Supported memory attributes will +have the corresponding bits set in u64 memory attributes bitmask. + +The following memory attributes are defined:: + + #define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) + #define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) + #define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) + #define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) + +4.139 KVM_SET_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: struct kvm_memory_attributes(in/out) +:Returns: 0 on success, <0 on error + +Sets memory attributes for pages in a guest memory range. Parameters are +specified via the following structure:: + + struct kvm_memory_attributes { + __u64 address; + __u64 size; + __u64 attributes; + __u64 flags; + }; + +The user sets the per-page memory attributes to a guest memory range indicated +by address/size, and in return KVM adjusts address and size to reflect the +actual pages of the memory range have been successfully set to the attributes. +If the call returns 0, "address" is updated to the last successful address + 1 +and "size" is updated to the remaining address size that has not been set +successfully. The user should check the return value as well as the size to +decide if the operation succeeded for the whole range or not. The user may want +to retry the operation with the returned address/size if the previous range was +partially successful. + +Both address and size should be page aligned and the supported attributes can be +retrieved with KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES. + +The "flags" field may be used for future extensions and should be set to 0s. + 5. The kvm_run structure ========================@@ -8270,6 +8323,16 @@ structure. When getting the Modified Change Topology Report value, the attr->addr must point to a byte where the value will be stored or retrieved from. +8.40 KVM_CAP_MEMORY_ATTRIBUTES +------------------------------ + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm + +This capability indicates KVM supports per-page memory attributes and ioctls +KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES/KVM_SET_MEMORY_ATTRIBUTES are available. + 9. Known KVM API problems =========================arch/x86/kvm/Kconfig +1
-0@@ -49,6 +49,7 @@ config KVM select SRCU select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM + select HAVE_KVM_MEMORY_ATTRIBUTES help Support hosting fully virtualized guest machines using hardware virtualization extensions. You will need a fairly recentinclude/linux/kvm_host.h +3
-0@@ -800,6 +800,9 @@ struct kvm {#ifdef CONFIG_HAVE_KVM_PM_NOTIFIER struct notifier_block pm_notifier; +#endif +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +struct xarray mem_attr_array;#endif char stats_id[KVM_STATS_NAME_SIZE ]; };include/uapi/linux/kvm.h +17
-0@@ -1182,6 +1182,7 @@ struct kvm_ppc_resize_hpt {#define KVM_CAP_S390_CPU_TOPOLOGY 222#define KVM_CAP_DIRTY_LOG_RING_ACQ_REL 223#define KVM_CAP_S390_PROTECTED_ASYNC_DISABLE 224 +#define KVM_CAP_MEMORY_ATTRIBUTES 225#ifdef KVM_CAP_IRQ_ROUTING @@ -2238,4 +2239,20 @@ struct kvm_s390_zpci_op {/* flags for kvm_s390_zpci_op->u.reg_aen.flags */ #define KVM_S390_ZPCIOP_REGAEN_HOST (1 << 0) +/* Available with KVM_CAP_MEMORY_ATTRIBUTES */ +#define KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES _IOR(KVMIO, 0xd2, __u64) +#define KVM_SET_MEMORY_ATTRIBUTES _IOWR(KVMIO, 0xd3, struct kvm_memory_attributes) + +struct kvm_memory_attributes { +__u64 address; +__u64 size; +__u64 attributes; +__u64 flags; +}; + +#define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) +#define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) +#define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) +#define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) +#endif /* __LINUX_KVM_H */ virt/kvm/Kconfig +3
-0@@ -19,6 +19,9 @@ config HAVE_KVM_IRQ_ROUTING config HAVE_KVM_DIRTY_RING bool +config HAVE_KVM_MEMORY_ATTRIBUTES + bool + # Only strongly ordered architectures can select this, as it doesn't # put any explicit constraint on userspace ordering. They can also # select the _ACQ_REL version.virt/kvm/kvm_main.c +25
-0@@ -1150,6 +1150,9 @@ static struct kvm *kvm_create_vm(unsigned long type, const char *fdname)spin_lock_init (&kvm->mn_invalidate_lock);rcuwait_init (&kvm->mn_memslots_update_rcuwait);xa_init (&kvm->vcpu_array); +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +xa_init (&kvm->mem_attr_array); +#endif INIT_LIST_HEAD (&kvm->gpc_list);spin_lock_init (&kvm->gpc_lock);@@ -1323,6 +1326,9 @@ static void kvm_destroy_vm(struct kvm *kvm)kvm_free_memslots (kvm, &kvm->__memslots[i][0 ]);kvm_free_memslots (kvm, &kvm->__memslots[i][1 ]); } +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +xa_destroy (&kvm->mem_attr_array); +#endif cleanup_srcu_struct (&kvm->irq_srcu);cleanup_srcu_struct (&kvm->srcu);kvm_arch_free_vm (kvm);@@ -2323,6 +2329,49 @@ static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, }#endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */ +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +static u64 kvm_supported_mem_attributes (struct kvm *kvm) +{ +return 0 ; +} + +static int kvm_vm_ioctl_set_mem_attributes (struct kvm *kvm, +struct kvm_memory_attributes *attrs) +{ +gfn_t start, end; +unsigned long i; +void *entry; +u64 supported_attrs =kvm_supported_mem_attributes (kvm); + +/* flags is currently not used. */ +if (attrs->flags) +return -EINVAL ; +if (attrs->attributes & ~supported_attrs) +return -EINVAL ;
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2360
Quoted 10 lines
virt/kvm/kvm_main.c +10
-0+if (attrs->size ==0 || attrs->address + attrs->size < attrs->address) +return -EINVAL ; +if (!PAGE_ALIGNED (attrs->address) || !PAGE_ALIGNED (attrs->size)) +return -EINVAL ; + + start = attrs->address >>PAGE_SHIFT ; + end = (attrs->address + attrs->size -1 +PAGE_SIZE ) >>PAGE_SHIFT ; + + entry = attrs->attributes ?xa_mk_value (attrs->attributes) :NULL ; +
Because guest memory defaults to private, and now this patch stores the attributes with KVM_MEMORY_ATTRIBUTE_PRIVATE instead of _SHARED, it would bring more KVM_EXIT_MEMORY_FAULT exits at the beginning of boot time. Maybe it can be optimized somehow in other places? e.g. set mem attr in advance.
Quoted 17 lines
virt/kvm/kvm_main.c +14
-0+mutex_lock (&kvm->lock); +for (i = start; i < end; i++) +if (xa_err (xa_store (&kvm->mem_attr_array, i, entry, +GFP_KERNEL_ACCOUNT ))) +break ; +mutex_unlock (&kvm->lock); + + attrs->address = i <<PAGE_SHIFT ; + attrs->size = (end - i) <<PAGE_SHIFT ; + + return 0; +} +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ +struct kvm_memory_slot *gfn_to_memslot (struct kvm *kvm,gfn_t gfn) {return __gfn_to_memslot (kvm_memslots (kvm), gfn);
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
On Wed, Dec 28, 2022 at 04:28:01PM +0800, Chenyi Qiang wrote:
...
Quoted 21 lines
Quoted 21 lines
virt/kvm/kvm_main.c +21
-0+static int kvm_vm_ioctl_set_mem_attributes (struct kvm *kvm, +struct kvm_memory_attributes *attrs) +{ +gfn_t start, end; +unsigned long i; +void *entry; +u64 supported_attrs =kvm_supported_mem_attributes (kvm); + +/* flags is currently not used. */ +if (attrs->flags) +return -EINVAL ; +if (attrs->attributes & ~supported_attrs) +return -EINVAL ; +if (attrs->size ==0 || attrs->address + attrs->size < attrs->address) +return -EINVAL ; +if (!PAGE_ALIGNED (attrs->address) || !PAGE_ALIGNED (attrs->size)) +return -EINVAL ; + + start = attrs->address >>PAGE_SHIFT ; + end = (attrs->address + attrs->size -1 +PAGE_SIZE ) >>PAGE_SHIFT ; +
Quoted 8 lines
Review
Quoted 2 lines
(quoted diff) +2
-0+ entry = attrs->attributes ? xa_mk_value(attrs->attributes) : NULL; +Because guest memory defaults to private, and now this patch stores the attributes with
KVM_MEMORY_ATTRIBUTE_PRIVATEinstead of_SHARED, it would bring moreKVM_EXIT_MEMORY_FAULTexits at the beginning of boot time. Maybe it can be optimized somehow in other places? e.g. set mem attr in advance.
KVM defaults to 'shared' because this ioctl can also be potentially used by normal VMs and 'shared' sounds a value meaningful for both normal VMs and confidential VMs. As for more KVM_EXIT_MEMORY_FAULT exits during the booting time, yes, setting all memory to 'private' for confidential VMs through this ioctl in userspace before guest launch is an approach for KVM userspace to 'override' the KVM default and reduce the number of implicit conversions.
Thanks,
Chao
Quoted 18 lines
Quoted 18 lines
virt/kvm/kvm_main.c +14
-0+mutex_lock (&kvm->lock); +for (i = start; i < end; i++) +if (xa_err (xa_store (&kvm->mem_attr_array, i, entry, +GFP_KERNEL_ACCOUNT ))) +break ; +mutex_unlock (&kvm->lock); + + attrs->address = i <<PAGE_SHIFT ; + attrs->size = (end - i) <<PAGE_SHIFT ; + + return 0; +} +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ +struct kvm_memory_slot *gfn_to_memslot (struct kvm *kvm,gfn_t gfn) {return __gfn_to_memslot (kvm_memslots (kvm), gfn);
RE: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 10 lines · Chao Peng
Quoted 2 lines
Because guest memory defaults to private, and now this patch stores the attributes with
KVM_MEMORY_ATTRIBUTE_PRIVATEinstead of
_SHARED,Quoted 3 lines
it would bring more
KVM_EXIT_MEMORY_FAULTexits at the beginning of boot time. Maybe it can be optimized somehow in other places? e.g. set mem attr in advance.KVM defaults to 'shared' because this ioctl can also be potentially used by normal VMs and 'shared' sounds a value meaningful for both normal VMs and confidential VMs.
Do you mean a normal VM could have pages marked private? What's the usage? (If all the pages are just marked shared for normal VMs, then why do we need it)
Quoted 4 lines
As for more
KVM_EXIT_MEMORY_FAULTexits during the
booting time, yes, setting all memory to 'private' for confidential VMs through this ioctl in userspace before guest launch is an approach for KVM userspace to 'override' the KVM default and reduce the number of implicit conversions.
Most pages of a confidential VM are likely to be private pages. It seems more efficient (and not difficult to check vm_type) to have KVM defaults to "private" for confidential VMs and defaults to "shared" for normal VMs.
Sean Christopherson
maintainerRe: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 8 lines · Wei W
Quoted 7 lines · Chao Peng
Quoted 2 lines
Because guest memory defaults to private, and now this patch stores the attributes with
KVM_MEMORY_ATTRIBUTE_PRIVATEinstead of
_SHARED,Quoted 3 lines
it would bring more
KVM_EXIT_MEMORY_FAULTexits at the beginning of boot time. Maybe it can be optimized somehow in other places? e.g. set mem attr in advance.
Quoted 6 lines
Quoted 3 lines
KVM defaults to 'shared' because this ioctl can also be potentially used by normal VMs and 'shared' sounds a value meaningful for both normal VMs and confidential VMs.
Do you mean a normal VM could have pages marked private? What's the usage? (If all the pages are just marked shared for normal VMs, then why do we need it)
No, there are potential use cases for per-page attribute/permissions, e.g. to make select pages read-only, exec-only, no-exec, etc...
Quoted 8 lines
Quoted 4 lines
As for more
KVM_EXIT_MEMORY_FAULTexits during the
booting time, yes, setting all memory to 'private' for confidential VMs through this ioctl in userspace before guest launch is an approach for KVM userspace to 'override' the KVM default and reduce the number of implicit conversions.Most pages of a confidential VM are likely to be private pages. It seems more efficient (and not difficult to check
vm_type) to have KVM defaults to "private" for confidential VMs and defaults to "shared" for normal VMs.
If done right, the default shouldn't matter all that much for efficiency. KVM needs to be able to effeciently track large ranges regardless of the default, otherwise the memory overhead and the presumably cost of lookups will be painful. E.g. converting a 1GiB chunk to shared should ideally require one entry, not 256k entries.
Looks like that behavior was changed in v8 in response to feedback[*] that doing xa_store_range() on a subset of an existing range (entry) would overwrite the entire existing range (entry), not just the smaller subset. xa_store_range() does appear to be too simplistic for this use case, but looking at __filemap_add_folio(), splitting an existing entry isn't super complex.
Using xa_store() for the very initial implementation is ok, and probably a good idea since it's more obviously correct and will give us a bisection point. But we definitely want a more performant implementation sooner than later. The hardest part will likely be merging existing entries, but that can be done separately too, and is probably lower priority.
E.g. (1) use xa_store() and always track at 4KiB granularity, (2) support storing metadata in multi-index entries, and finally (3) support merging adjacent entries with identical values.
[*] https://lore.kernel.org/all/CAGtprH9xyw6bt4=RBWF6-v2CSpabOCpKq5rPz+e-9co7EisoVQ@mail.gmail.com
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 13 lines · Sean Christopherson
Quoted 12 lines · Wei W
Quoted 10 lines · Chao Peng
Quoted 2 lines
Because guest memory defaults to private, and now this patch stores the attributes with
KVM_MEMORY_ATTRIBUTE_PRIVATEinstead of
_SHARED,Quoted 3 lines
it would bring more
KVM_EXIT_MEMORY_FAULTexits at the beginning of boot time. Maybe it can be optimized somehow in other places? e.g. set mem attr in advance.KVM defaults to 'shared' because this ioctl can also be potentially used by normal VMs and 'shared' sounds a value meaningful for both normal VMs and confidential VMs.
Quoted 5 lines
Quoted 2 lines
Do you mean a normal VM could have pages marked private? What's the usage? (If all the pages are just marked shared for normal VMs, then why do we need it)
No, there are potential use cases for per-page attribute/permissions, e.g. to make select pages read-only, exec-only, no-exec, etc...
Right, normal VMs are not likely use private/shared bit. Not sure pKVM, but perhaps not call it 'normal' VMs in this context. But since the ioctl can be used by normal VMs for other bits (read-only, exec-only, no-exec, etc), a default 'private' looks strange for them. That's why I default it to 'shared' and for confidential guest, we can issue another call to this ioctl to set all the memory to 'private' before guest booting, if default 'private' is needed for guest.
Like Wei mentioned, it's also possible to make the default dependents on vm_type, but that looks awkward to me from the API definition as well as the implementation, also the vm_type has not been introduced at this time.
Quoted 10 lines
Quoted 9 lines
Quoted 5 lines
As for more
KVM_EXIT_MEMORY_FAULTexits during the
booting time, yes, setting all memory to 'private' for confidential VMs through this ioctl in userspace before guest launch is an approach for KVM userspace to 'override' the KVM default and reduce the number of implicit conversions.Most pages of a confidential VM are likely to be private pages. It seems more efficient (and not difficult to check
vm_type) to have KVM defaults to "private" for confidential VMs and defaults to "shared" for normal VMs.
Quoted 5 lines
If done right, the default shouldn't matter all that much for efficiency. KVM needs to be able to effeciently track large ranges regardless of the default, otherwise the memory overhead and the presumably cost of lookups will be painful. E.g. converting a 1GiB chunk to shared should ideally require one entry, not 256k entries.
I agree, KVM should have the ability to track large ranges efficiently.
Quoted 6 lines
Looks like that behavior was changed in v8 in response to feedback[*] that doing
xa_store_range()on a subset of an existing range (entry) would overwrite the entire existing range (entry), not just the smaller subset.xa_store_range()does appear to be too simplistic for this use case, but looking at__filemap_add_folio(), splitting an existing entry isn't super complex.
Yes, xa_store_range() looks a perfect match for us initially but the 'overwriting the entire entry' behavior makes it incorrect for us when storing a subset on an existing large entry. xarray lib has utilities for splitting, the hard part is merging existing entries, as you also said below. Thanks for pointing out the __filemap_add_folio() example, it does look not too complex for splitting.
Quoted 10 lines
Using
xa_store()for the very initial implementation is ok, and probably a good idea since it's more obviously correct and will give us a bisection point. But we definitely want a more performant implementation sooner than later. The hardest part will likely be merging existing entries, but that can be done separately too, and is probably lower priority.E.g. (1) use
xa_store()and always track at 4KiB granularity, (2) support storing metadata in multi-index entries, and finally (3) support merging adjacent entries with identical values.
This path looks good to me.
Thanks,
Chao
Sean Christopherson
maintainerRe: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
In reply to Chao Pengarch/x86/kvm/Kconfig config KVM · line 52
Quoted 9 lines · Chao Peng
arch/x86/kvm/Kconfig +1
-0@@ -49,6 +49,7 @@ config KVM select SRCU select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM + select HAVE_KVM_MEMORY_ATTRIBUTES
I would prefer to call this KVM_GENERIC_MEMORY_ATTRIBUTES. Similar to KVM_GENERIC_HARDWARE_ENABLING, ARM does need/have hardware enabling, it just doesn't want KVM's generic implementation. In this case, pKVM does support memory attributes, but uses stage-2 tables to track ownership and doesn't need/want the overhead of the generic implementation.
Quoted 1 line
arch/x86/kvm/Kconfig +0
-0help
...
arch/x86/kvm/Kconfig
Quoted 4 lines
arch/x86/kvm/Kconfig +4
-0+#define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) +#define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) +#define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) +#define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3)
I think we should carve out bits 0-2 for RWX, but I don't think we should actually define them until they're actually accepted by KVM.
arch/x86/kvm/Kconfig
Quoted 12 lines
arch/x86/kvm/Kconfig +12
-0+static int kvm_vm_ioctl_set_mem_attributes(struct kvm *kvm, + struct kvm_memory_attributes *attrs) +{ + gfn_t start, end; + unsigned long i; + void *entry; + u64 supported_attrs = kvm_supported_mem_attributes(kvm); + + /* flags is currently not used. */ + if (attrs->flags) + return -EINVAL; + if (attrs->attributes & ~supported_attrs)
Nit, no need for "supported_attrs", just consume kvm_supported_mem_attributes() directly.
arch/x86/kvm/Kconfig
Quoted 12 lines
arch/x86/kvm/Kconfig +12
-0+ return -EINVAL; + if (attrs->size == 0 || attrs->address + attrs->size < attrs->address) + return -EINVAL; + if (!PAGE_ALIGNED(attrs->address) || !PAGE_ALIGNED(attrs->size)) + return -EINVAL; + + start = attrs->address >> PAGE_SHIFT; + end = (attrs->address + attrs->size - 1 + PAGE_SIZE) >> PAGE_SHIFT; + + entry = attrs->attributes ? xa_mk_value(attrs->attributes) : NULL; + + mutex_lock(&kvm->lock);
Peeking forward multiple patches, this needs to take kvm->slots_lock, not kvm->lock. There's a bug in the lpage_disallowed patch that I believe can most easily be solved by making this mutually exclusive with memslot changes.
When a memslot is created, KVM needs to walk through the attributes to detect whether or not the attributes are identical for the entire slot. To avoid races, that means taking slots_lock.
The alternative would be to query the attributes when adjusting the hugepage level and avoid lpage_disallowed entirely, but in the (very brief) time I've thought about this I haven't come up with a way to do that in a performant manner.
arch/x86/kvm/Kconfig
Quoted 1 line
arch/x86/kvm/Kconfig +1
-0+ for (i = start; i < end; i++)
Curly braces needed on the for-loop.
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
In reply to Chao PengQuoted 15 lines · Chao Peng
In confidential computing usages, whether a page is private or shared is necessary information for KVM to perform operations like page fault handling, page zapping etc. There are other potential use cases for per-page memory attributes, e.g. to make memory read-only (or no-exec, or exec-only, etc.) without having to modify memslots.
Introduce two ioctls (advertised by
KVM_CAP_MEMORY_ATTRIBUTES) to allow userspace to operate on the per-page memory attributes.
-KVM_SET_MEMORY_ATTRIBUTESto set the per-page memory attributes to a guest memory range.
-KVM_GET_SUPPORTED_MEMORY_ATTRIBUTESto return the KVM supported memory attributes.KVM internally uses xarray to store the per-page memory attributes.
Quoted 8 lines
Suggested-by Sean Christopherson <[email protected]>Signed-off-by Chao Peng <[email protected]>--- Documentation/virt/kvm/api.rst | 63 ++++++++++++++++++++++++++++ arch/x86/kvm/Kconfig | 1 + include/linux/kvm_host.h | 3 ++ include/uapi/linux/kvm.h | 17 ++++++++
Should the changes introduced in this file also need to be added in tools/include/uapi/linux/kvm.h ?
Quoted 273 lines
virt/kvm/Kconfig | 3 ++ virt/kvm/kvm_main.c | 76 ++++++++++++++++++++++++++++++++++ 6 files changed, 163 insertions(+)Documentation/virt/kvm/api.rst +63
-0@@ -5952,6 +5952,59 @@ delivery must be provided via the "reg_aen" struct. The "pad" and "reserved" fields may be used for future extensions and should be set to 0s by userspace. +4.138 KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: u64 memory attributes bitmask(out) +:Returns: 0 on success, <0 on error + +Returns supported memory attributes bitmask. Supported memory attributes will +have the corresponding bits set in u64 memory attributes bitmask. + +The following memory attributes are defined:: + + #define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) + #define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) + #define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) + #define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) + +4.139 KVM_SET_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: struct kvm_memory_attributes(in/out) +:Returns: 0 on success, <0 on error + +Sets memory attributes for pages in a guest memory range. Parameters are +specified via the following structure:: + + struct kvm_memory_attributes { + __u64 address; + __u64 size; + __u64 attributes; + __u64 flags; + }; + +The user sets the per-page memory attributes to a guest memory range indicated +by address/size, and in return KVM adjusts address and size to reflect the +actual pages of the memory range have been successfully set to the attributes. +If the call returns 0, "address" is updated to the last successful address + 1 +and "size" is updated to the remaining address size that has not been set +successfully. The user should check the return value as well as the size to +decide if the operation succeeded for the whole range or not. The user may want +to retry the operation with the returned address/size if the previous range was +partially successful. + +Both address and size should be page aligned and the supported attributes can be +retrieved with KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES. + +The "flags" field may be used for future extensions and should be set to 0s. + 5. The kvm_run structure ========================@@ -8270,6 +8323,16 @@ structure. When getting the Modified Change Topology Report value, the attr->addr must point to a byte where the value will be stored or retrieved from. +8.40 KVM_CAP_MEMORY_ATTRIBUTES +------------------------------ + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm + +This capability indicates KVM supports per-page memory attributes and ioctls +KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES/KVM_SET_MEMORY_ATTRIBUTES are available. + 9. Known KVM API problems =========================arch/x86/kvm/Kconfig +1
-0@@ -49,6 +49,7 @@ config KVM select SRCU select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM + select HAVE_KVM_MEMORY_ATTRIBUTES help Support hosting fully virtualized guest machines using hardware virtualization extensions. You will need a fairly recentinclude/linux/kvm_host.h +3
-0@@ -800,6 +800,9 @@ struct kvm {#ifdef CONFIG_HAVE_KVM_PM_NOTIFIER struct notifier_block pm_notifier; +#endif +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +struct xarray mem_attr_array;#endif char stats_id[KVM_STATS_NAME_SIZE ]; };include/uapi/linux/kvm.h +17
-0@@ -1182,6 +1182,7 @@ struct kvm_ppc_resize_hpt {#define KVM_CAP_S390_CPU_TOPOLOGY 222#define KVM_CAP_DIRTY_LOG_RING_ACQ_REL 223#define KVM_CAP_S390_PROTECTED_ASYNC_DISABLE 224 +#define KVM_CAP_MEMORY_ATTRIBUTES 225#ifdef KVM_CAP_IRQ_ROUTING @@ -2238,4 +2239,20 @@ struct kvm_s390_zpci_op {/* flags for kvm_s390_zpci_op->u.reg_aen.flags */ #define KVM_S390_ZPCIOP_REGAEN_HOST (1 << 0) +/* Available with KVM_CAP_MEMORY_ATTRIBUTES */ +#define KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES _IOR(KVMIO, 0xd2, __u64) +#define KVM_SET_MEMORY_ATTRIBUTES _IOWR(KVMIO, 0xd3, struct kvm_memory_attributes) + +struct kvm_memory_attributes { +__u64 address; +__u64 size; +__u64 attributes; +__u64 flags; +}; + +#define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) +#define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) +#define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) +#define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) +#endif /* __LINUX_KVM_H */ virt/kvm/Kconfig +3
-0@@ -19,6 +19,9 @@ config HAVE_KVM_IRQ_ROUTING config HAVE_KVM_DIRTY_RING bool +config HAVE_KVM_MEMORY_ATTRIBUTES + bool + # Only strongly ordered architectures can select this, as it doesn't # put any explicit constraint on userspace ordering. They can also # select the _ACQ_REL version.virt/kvm/kvm_main.c +76
-0@@ -1150,6 +1150,9 @@ static struct kvm *kvm_create_vm(unsigned long type, const char *fdname)spin_lock_init (&kvm->mn_invalidate_lock);rcuwait_init (&kvm->mn_memslots_update_rcuwait);xa_init (&kvm->vcpu_array); +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +xa_init (&kvm->mem_attr_array); +#endif INIT_LIST_HEAD (&kvm->gpc_list);spin_lock_init (&kvm->gpc_lock);@@ -1323,6 +1326,9 @@ static void kvm_destroy_vm(struct kvm *kvm)kvm_free_memslots (kvm, &kvm->__memslots[i][0 ]);kvm_free_memslots (kvm, &kvm->__memslots[i][1 ]); } +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +xa_destroy (&kvm->mem_attr_array); +#endif cleanup_srcu_struct (&kvm->irq_srcu);cleanup_srcu_struct (&kvm->srcu);kvm_arch_free_vm (kvm);@@ -2323,6 +2329,49 @@ static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, }#endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */ +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +static u64 kvm_supported_mem_attributes (struct kvm *kvm) +{ +return 0 ; +} + +static int kvm_vm_ioctl_set_mem_attributes (struct kvm *kvm, +struct kvm_memory_attributes *attrs) +{ +gfn_t start, end; +unsigned long i; +void *entry; +u64 supported_attrs =kvm_supported_mem_attributes (kvm); + +/* flags is currently not used. */ +if (attrs->flags) +return -EINVAL ; +if (attrs->attributes & ~supported_attrs) +return -EINVAL ; +if (attrs->size ==0 || attrs->address + attrs->size < attrs->address) +return -EINVAL ; +if (!PAGE_ALIGNED (attrs->address) || !PAGE_ALIGNED (attrs->size)) +return -EINVAL ; + + start = attrs->address >>PAGE_SHIFT ; + end = (attrs->address + attrs->size -1 +PAGE_SIZE ) >>PAGE_SHIFT ; + + entry = attrs->attributes ?xa_mk_value (attrs->attributes) :NULL ; + +mutex_lock (&kvm->lock); +for (i = start; i < end; i++) +if (xa_err (xa_store (&kvm->mem_attr_array, i, entry, +GFP_KERNEL_ACCOUNT ))) +break ; +mutex_unlock (&kvm->lock); + + attrs->address = i <<PAGE_SHIFT ; + attrs->size = (end - i) <<PAGE_SHIFT ; + +return 0 ; +} +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ +struct kvm_memory_slot *gfn_to_memslot (struct kvm *kvm,gfn_t gfn) {return __gfn_to_memslot (kvm_memslots (kvm), gfn);@@ -4459,6 +4508,9 @@ static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)#ifdef CONFIG_HAVE_KVM_MSI case KVM_CAP_SIGNAL_MSI :#endif +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +case KVM_CAP_MEMORY_ATTRIBUTES : +#endif #ifdef CONFIG_HAVE_KVM_IRQFD case KVM_CAP_IRQFD :case KVM_CAP_IRQFD_RESAMPLE :@@ -4804,6 +4856,30 @@ static long kvm_vm_ioctl(struct file *filp, break; }#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */ +#ifdef CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES +case KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES : { +u64 attrs =kvm_supported_mem_attributes (kvm); + + r = -EFAULT ; +if (copy_to_user (argp, &attrs,sizeof (attrs))) + goto out; + r =0 ; +break ; + } +case KVM_SET_MEMORY_ATTRIBUTES : { +struct kvm_memory_attributes attrs; + + r = -EFAULT ; +if (copy_from_user (&attrs, argp,sizeof (attrs))) + goto out; + + r =kvm_vm_ioctl_set_mem_attributes (kvm, &attrs); + +if (!r &©_to_user (argp, &attrs,sizeof (attrs))) + r = -EFAULT ; +break ; + } +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ case KVM_CREATE_DEVICE : {struct kvm_create_device cd;
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 26 lines · Binbin Wu
Quoted 15 lines · Chao Peng
In confidential computing usages, whether a page is private or shared is necessary information for KVM to perform operations like page fault handling, page zapping etc. There are other potential use cases for per-page memory attributes, e.g. to make memory read-only (or no-exec, or exec-only, etc.) without having to modify memslots.
Introduce two ioctls (advertised by
KVM_CAP_MEMORY_ATTRIBUTES) to allow userspace to operate on the per-page memory attributes.
-KVM_SET_MEMORY_ATTRIBUTESto set the per-page memory attributes to a guest memory range.
-KVM_GET_SUPPORTED_MEMORY_ATTRIBUTESto return the KVM supported memory attributes.KVM internally uses xarray to store the per-page memory attributes.
Quoted 8 lines
Suggested-by Sean Christopherson <[email protected]>Signed-off-by Chao Peng <[email protected]>--- Documentation/virt/kvm/api.rst | 63 ++++++++++++++++++++++++++++ arch/x86/kvm/Kconfig | 1 + include/linux/kvm_host.h | 3 ++ include/uapi/linux/kvm.h | 17 ++++++++
Quoted 2 lines
Should the changes introduced in this file also need to be added in
tools/include/uapi/linux/kvm.h?
Yes I think. But I'm hesitate to include in this patch or not. I see many commits sync kernel kvm.h to tools's copy. Looks that is done periodically and with a 'pull' model.
Chao
Sean Christopherson
maintainerRe: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 27 lines · Chao Peng
Quoted 26 lines · Binbin Wu
Quoted 23 lines · Chao Peng
In confidential computing usages, whether a page is private or shared is necessary information for KVM to perform operations like page fault handling, page zapping etc. There are other potential use cases for per-page memory attributes, e.g. to make memory read-only (or no-exec, or exec-only, etc.) without having to modify memslots.
Introduce two ioctls (advertised by
KVM_CAP_MEMORY_ATTRIBUTES) to allow userspace to operate on the per-page memory attributes.
-KVM_SET_MEMORY_ATTRIBUTESto set the per-page memory attributes to a guest memory range.
-KVM_GET_SUPPORTED_MEMORY_ATTRIBUTESto return the KVM supported memory attributes.KVM internally uses xarray to store the per-page memory attributes.
Suggested-by Sean Christopherson <[email protected]>Signed-off-by Chao Peng <[email protected]>--- Documentation/virt/kvm/api.rst | 63 ++++++++++++++++++++++++++++ arch/x86/kvm/Kconfig | 1 + include/linux/kvm_host.h | 3 ++ include/uapi/linux/kvm.h | 17 ++++++++
Quoted 4 lines
Quoted 2 lines
Should the changes introduced in this file also need to be added in
tools/include/uapi/linux/kvm.h?Yes I think.
I'm not sure how Paolo or others feel, but my preference is to never update KVM's uapi headers in tools/ in KVM's tree. Nothing KVM-related in tools/ actually relies on the headers being copied into tools/, e.g. KVM selftests pulls KVM's headers from the .../usr/include/ directory that's populated by make headers_install.
Perf's tooling is what actually "needs" the headers to be copied into tools/, so my preference is to let the tools/perf maintainers deal with the headache of keeping everything up-to-date.
Quoted 3 lines
But I'm hesitate to include in this patch or not. I see many commits sync kernel
kvm.hto tools's copy. Looks that is done periodically and with a 'pull' model.
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
In reply to Chao PengQuoted 27 lines · Chao Peng
virt/kvm/kvm_main.c +27
-0+static int kvm_vm_ioctl_set_mem_attributes (struct kvm *kvm, +struct kvm_memory_attributes *attrs) +{ +gfn_t start, end; +unsigned long i; +void *entry; +u64 supported_attrs =kvm_supported_mem_attributes (kvm); + +/* flags is currently not used. */ +if (attrs->flags) +return -EINVAL ; +if (attrs->attributes & ~supported_attrs) +return -EINVAL ; +if (attrs->size ==0 || attrs->address + attrs->size < attrs->address) +return -EINVAL ; +if (!PAGE_ALIGNED (attrs->address) || !PAGE_ALIGNED (attrs->size)) +return -EINVAL ; + + start = attrs->address >>PAGE_SHIFT ; + end = (attrs->address + attrs->size -1 +PAGE_SIZE ) >>PAGE_SHIFT ; + + entry = attrs->attributes ?xa_mk_value (attrs->attributes) :NULL ; + +mutex_lock (&kvm->lock); +for (i = start; i < end; i++) +if (xa_err (xa_store (&kvm->mem_attr_array, i, entry, +GFP_KERNEL_ACCOUNT )))
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2374
Quoted 10 lines
virt/kvm/kvm_main.c +10
-0+break ; +mutex_unlock (&kvm->lock); + + attrs->address = i <<PAGE_SHIFT ; + attrs->size = (end - i) <<PAGE_SHIFT ; + + return 0; +} +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ +
If memslot isn't private, it should return error if private attribute is set. Something like following check is needed.
+ if (attrs->flags & KVM_MEM_PRIVATE) {
+ /* non-private memory slot doesn't allow KVM_MEM_PRIVATE */
+ for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
+ struct kvm_memslot_iter iter;
+ struct kvm_memslots *slots;
+
+ slots = __kvm_memslots(kvm, i);
+ kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) {
+ if (!kvm_slot_can_be_private(iter.slot)) {
+ mutex_unlock(&kvm->slots_lock);
+ return -EINVAL;
+ }
+ }
+ }
+ }
+
Signature · 1 line
Isaku Yamahata <[email protected]>
Sean Christopherson
maintainerRe: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 34 lines · Isaku Yamahata
Quoted 31 lines · Chao Peng
virt/kvm/kvm_main.c +31
-0+static int kvm_vm_ioctl_set_mem_attributes (struct kvm *kvm, +struct kvm_memory_attributes *attrs) +{ +gfn_t start, end; +unsigned long i; +void *entry; +u64 supported_attrs =kvm_supported_mem_attributes (kvm); + +/* flags is currently not used. */ +if (attrs->flags) +return -EINVAL ; +if (attrs->attributes & ~supported_attrs) +return -EINVAL ; +if (attrs->size ==0 || attrs->address + attrs->size < attrs->address) +return -EINVAL ; +if (!PAGE_ALIGNED (attrs->address) || !PAGE_ALIGNED (attrs->size)) +return -EINVAL ; + + start = attrs->address >>PAGE_SHIFT ; + end = (attrs->address + attrs->size -1 +PAGE_SIZE ) >>PAGE_SHIFT ; + + entry = attrs->attributes ?xa_mk_value (attrs->attributes) :NULL ; + +mutex_lock (&kvm->lock); +for (i = start; i < end; i++) +if (xa_err (xa_store (&kvm->mem_attr_array, i, entry, +GFP_KERNEL_ACCOUNT ))) +break ; +mutex_unlock (&kvm->lock); + + attrs->address = i <<PAGE_SHIFT ;
Quoted 8 lines
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2374
Quoted 6 lines
virt/kvm/kvm_main.c +6
-0+ attrs->size = (end - i) <<PAGE_SHIFT ; + + return 0; +} +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ +If memslot isn't private, it should return error if private attribute is set.
Why? I'd rather keep the two things separate. If we enforce this sort of thing at KVM_SET_MEMORY_ATTRIBUTES, then we also have to enforce it at KVM_SET_USER_MEMORY_REGION.
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 44 lines · Sean Christopherson
Quoted 34 lines · Isaku Yamahata
Quoted 31 lines · Chao Peng
virt/kvm/kvm_main.c +31
-0+static int kvm_vm_ioctl_set_mem_attributes (struct kvm *kvm, +struct kvm_memory_attributes *attrs) +{ +gfn_t start, end; +unsigned long i; +void *entry; +u64 supported_attrs =kvm_supported_mem_attributes (kvm); + +/* flags is currently not used. */ +if (attrs->flags) +return -EINVAL ; +if (attrs->attributes & ~supported_attrs) +return -EINVAL ; +if (attrs->size ==0 || attrs->address + attrs->size < attrs->address) +return -EINVAL ; +if (!PAGE_ALIGNED (attrs->address) || !PAGE_ALIGNED (attrs->size)) +return -EINVAL ; + + start = attrs->address >>PAGE_SHIFT ; + end = (attrs->address + attrs->size -1 +PAGE_SIZE ) >>PAGE_SHIFT ; + + entry = attrs->attributes ?xa_mk_value (attrs->attributes) :NULL ; + +mutex_lock (&kvm->lock); +for (i = start; i < end; i++) +if (xa_err (xa_store (&kvm->mem_attr_array, i, entry, +GFP_KERNEL_ACCOUNT ))) +break ; +mutex_unlock (&kvm->lock); + + attrs->address = i <<PAGE_SHIFT ;Quoted 8 lines
virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2374
Quoted 6 lines
virt/kvm/kvm_main.c +6
-0+ attrs->size = (end - i) <<PAGE_SHIFT ; + + return 0; +} +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ +If memslot isn't private, it should return error if private attribute is set.
Quoted 3 lines
Why? I'd rather keep the two things separate. If we enforce this sort of thing at
KVM_SET_MEMORY_ATTRIBUTES, then we also have to enforce it atKVM_SET_USER_MEMORY_REGION.
For device assignment via shared GPA, non-private memory slot needs to be allowed.
Signature · 1 line
Isaku Yamahata <[email protected]>
Sean Christopherson
maintainerRe: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 47 lines · Isaku Yamahata
Quoted 44 lines · Sean Christopherson
Quoted 42 lines · Isaku Yamahata
Quoted 27 lines · Chao Peng
virt/kvm/kvm_main.c +27
-0+static int kvm_vm_ioctl_set_mem_attributes (struct kvm *kvm, +struct kvm_memory_attributes *attrs) +{ +gfn_t start, end; +unsigned long i; +void *entry; +u64 supported_attrs =kvm_supported_mem_attributes (kvm); + +/* flags is currently not used. */ +if (attrs->flags) +return -EINVAL ; +if (attrs->attributes & ~supported_attrs) +return -EINVAL ; +if (attrs->size ==0 || attrs->address + attrs->size < attrs->address) +return -EINVAL ; +if (!PAGE_ALIGNED (attrs->address) || !PAGE_ALIGNED (attrs->size)) +return -EINVAL ; + + start = attrs->address >>PAGE_SHIFT ; + end = (attrs->address + attrs->size -1 +PAGE_SIZE ) >>PAGE_SHIFT ; + + entry = attrs->attributes ?xa_mk_value (attrs->attributes) :NULL ; + +mutex_lock (&kvm->lock); +for (i = start; i < end; i++) +if (xa_err (xa_store (&kvm->mem_attr_array, i, entry, +GFP_KERNEL_ACCOUNT )))virt/kvm/kvm_main.c static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, · line 2374
Quoted 10 lines
virt/kvm/kvm_main.c +10
-0+break ; +mutex_unlock (&kvm->lock); + + attrs->address = i <<PAGE_SHIFT ; + attrs->size = (end - i) <<PAGE_SHIFT ; + + return 0; +} +#endif /* CONFIG_HAVE_KVM_MEMORY_ATTRIBUTES */ +If memslot isn't private, it should return error if private attribute is set.
Quoted 6 lines
Quoted 3 lines
Why? I'd rather keep the two things separate. If we enforce this sort of thing at
KVM_SET_MEMORY_ATTRIBUTES, then we also have to enforce it atKVM_SET_USER_MEMORY_REGION.For device assignment via shared GPA, non-private memory slot needs to be allowed.
That doesn't say anything about why setting attributes needs to poke into the memslot. The page fault path already kicks out to userspace if there's a discrepancy between the attributes and the memslot, why is that insufficient?
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
In reply to Chao PengHi,
On Fri Dec 2, 2022 at 6:13 AM UTC, Chao Peng wrote:
[...]
Quoted 42 lines
+4.138
KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES
+-----------------------------------------Documentation/virt/kvm/api.rst +40
-0+ +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: u64 memory attributes bitmask(out) +:Returns: 0 on success, <0 on error + +Returns supported memory attributes bitmask. Supported memory attributes will +have the corresponding bits set in u64 memory attributes bitmask. + +The following memory attributes are defined:: + + #define KVM_MEMORY_ATTRIBUTE_READ (1ULL << 0) + #define KVM_MEMORY_ATTRIBUTE_WRITE (1ULL << 1) + #define KVM_MEMORY_ATTRIBUTE_EXECUTE (1ULL << 2) + #define KVM_MEMORY_ATTRIBUTE_PRIVATE (1ULL << 3) + +4.139 KVM_SET_MEMORY_ATTRIBUTES +----------------------------------------- + +:Capability: KVM_CAP_MEMORY_ATTRIBUTES +:Architectures: x86 +:Type: vm ioctl +:Parameters: struct kvm_memory_attributes(in/out) +:Returns: 0 on success, <0 on error + +Sets memory attributes for pages in a guest memory range. Parameters are +specified via the following structure:: + + struct kvm_memory_attributes { + __u64 address; + __u64 size; + __u64 attributes; + __u64 flags; + }; + +The user sets the per-page memory attributes to a guest memory range indicated +by address/size, and in return KVM adjusts address and size to reflect the +actual pages of the memory range have been successfully set to the attributes. +If the call returns 0, "address" is updated to the last successful address + 1
Documentation/virt/kvm/api.rst delivery must be provided via the "reg_aen" struct. · line 6006
Quoted 10 lines
Documentation/virt/kvm/api.rst +10
-0+and "size" is updated to the remaining address size that has not been set +successfully. The user should check the return value as well as the size to +decide if the operation succeeded for the whole range or not. The user may want +to retry the operation with the returned address/size if the previous range was +partially successful. + +Both address and size should be page aligned and the supported attributes can be +retrieved with KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES. + +The "flags" field may be used for future extensions and should be set to 0s.
We have been looking into adding support for the Hyper-V VSM extensions which Windows uses to implement Credential Guard. This interface seems like a good fit for one of its underlying features. I just wanted to share a bit about it, and see if we can expand it to fit this use-case. Note that this was already briefly discussed between Sean and Alex some time ago[1].
VSM introduces isolated guest execution contexts called Virtual Trust Levels (VTL) [2]. Each VTL has its own memory access protections, virtual processors states, interrupt controllers and overlay pages. VTLs are hierarchical and might enforce memory protections on less privileged VTLs. Memory protections are enforced on a per-GPA granularity.
The list of possible protections is:
- No access -- This needs a new memory attribute, I think.
- Read-only, no execute
- Read-only, execute
- Read/write, no execute
- Read/write, execute
We implemented this in the past by using a separate address space per VTL and updating memory regions on protection changes. But having to update the memory slot layout for every permission change scales poorly, especially as we have to perform 100.000s of these operations at boot (see [1] for a little more context).
I believe the biggest barrier for us to use memory attributes is not having the ability to target specific address spaces, or to the very least having some mechanism to maintain multiple independent layers of attributes.
Also sorry for not posting our VSM patches. They are not ready for upstream review yet, but we're working on it.
Nicolas
[1] https://patchwork.kernel.org/comment/25054908/
[2] See Chapter 15 of Microsoft's 'Hypervisor Top Level Functional Specification':
https://raw.githubusercontent.com/MicrosoftDocs/Virtualization-Documentation/main/tlfs/Hypervisor%20Top%20Level%20Functional%20Specification%20v6.0b.pdf
Sean Christopherson
maintainerRe: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 27 lines · Nicolas Saenz Julienne
Hi,
On Fri Dec 2, 2022 at 6:13 AM UTC, Chao Peng wrote:
[...]
Quoted 4 lines
Documentation/virt/kvm/api.rst +4
-0+The user sets the per-page memory attributes to a guest memory range indicated +by address/size, and in return KVM adjusts address and size to reflect the +actual pages of the memory range have been successfully set to the attributes. +If the call returns 0, "address" is updated to the last successful address + 1Documentation/virt/kvm/api.rst delivery must be provided via the "reg_aen" struct. · line 6006
Quoted 10 lines
Documentation/virt/kvm/api.rst +10
-0+and "size" is updated to the remaining address size that has not been set +successfully. The user should check the return value as well as the size to +decide if the operation succeeded for the whole range or not. The user may want +to retry the operation with the returned address/size if the previous range was +partially successful. + +Both address and size should be page aligned and the supported attributes can be +retrieved with KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES. + +The "flags" field may be used for future extensions and should be set to 0s.We have been looking into adding support for the Hyper-V VSM extensions which Windows uses to implement Credential Guard. This interface seems like a good fit for one of its underlying features. I just wanted to share a bit about it, and see if we can expand it to fit this use-case. Note that this was already briefly discussed between Sean and Alex some time ago[1].
Quoted 8 lines
VSM introduces isolated guest execution contexts called Virtual Trust Levels (VTL) [2]. Each VTL has its own memory access protections, virtual processors states, interrupt controllers and overlay pages. VTLs are hierarchical and might enforce memory protections on less privileged VTLs. Memory protections are enforced on a per-GPA granularity.
The list of possible protections is:
- No access -- This needs a new memory attribute, I think.
No, if KVM provides three bits for READ, WRITE, and EXECUTE, then userspace can get all the possible combinations. E.g. this is RWX=000b
Quoted 1 line
- Read-only, no execute
RWX=100b (using my completely arbitrary ordering of RWX bits :-) )
Quoted 1 line
- Read-only, execute
RWX=101b
Quoted 1 line
- Read/write, no execute
RWX=110b
Quoted 1 line
- Read/write, execute
RWX=111b
Quoted 10 lines
We implemented this in the past by using a separate address space per VTL and updating memory regions on protection changes. But having to update the memory slot layout for every permission change scales poorly, especially as we have to perform 100.000s of these operations at boot (see [1] for a little more context).
I believe the biggest barrier for us to use memory attributes is not having the ability to target specific address spaces, or to the very least having some mechanism to maintain multiple independent layers of attributes.
Can you elaborate on "specific address spaces"? In KVM, that usually means SMM, but the VTL comment above makes me think you're talking about something entirely different. E.g. can you provide a brief summary of the requirements/expectations?
Quoted 8 lines
Also sorry for not posting our VSM patches. They are not ready for upstream review yet, but we're working on it.
Nicolas
[1] https://patchwork.kernel.org/comment/25054908/
[2] See Chapter 15 of Microsoft's 'Hypervisor Top Level Functional Specification':
https://raw.githubusercontent.com/MicrosoftDocs/Virtualization-Documentation/main/tlfs/Hypervisor%20Top%20Level%20Functional%20Specification%20v6.0b.pdf
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Hi Sean,
Quoted 34 lines · Sean Christopherson
Quoted 33 lines · Nicolas Saenz Julienne
Hi,
On Fri Dec 2, 2022 at 6:13 AM UTC, Chao Peng wrote:
[...]
Quoted 4 lines
Documentation/virt/kvm/api.rst +4
-0+The user sets the per-page memory attributes to a guest memory range indicated +by address/size, and in return KVM adjusts address and size to reflect the +actual pages of the memory range have been successfully set to the attributes. +If the call returns 0, "address" is updated to the last successful address + 1Documentation/virt/kvm/api.rst delivery must be provided via the "reg_aen" struct. · line 6006
Quoted 10 lines
Documentation/virt/kvm/api.rst +10
-0+and "size" is updated to the remaining address size that has not been set +successfully. The user should check the return value as well as the size to +decide if the operation succeeded for the whole range or not. The user may want +to retry the operation with the returned address/size if the previous range was +partially successful. + +Both address and size should be page aligned and the supported attributes can be +retrieved with KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES. + +The "flags" field may be used for future extensions and should be set to 0s.We have been looking into adding support for the Hyper-V VSM extensions which Windows uses to implement Credential Guard. This interface seems like a good fit for one of its underlying features. I just wanted to share a bit about it, and see if we can expand it to fit this use-case. Note that this was already briefly discussed between Sean and Alex some time ago[1].
VSM introduces isolated guest execution contexts called Virtual Trust Levels (VTL) [2]. Each VTL has its own memory access protections, virtual processors states, interrupt controllers and overlay pages. VTLs are hierarchical and might enforce memory protections on less privileged VTLs. Memory protections are enforced on a per-GPA granularity.
Quoted 5 lines
Quoted 2 lines
The list of possible protections is:
- No access -- This needs a new memory attribute, I think.No, if KVM provides three bits for READ, WRITE, and EXECUTE, then userspace can get all the possible combinations. E.g. this is RWX=000b
That's not what the current implementation does, when attributes is equal 0 it clears the entries from the xarray:
static int kvm_vm_ioctl_set_mem_attributes(struct kvm *kvm,
struct kvm_memory_attributes *attrs)
{
entry = attrs->attributes ? xa_mk_value(attrs->attributes) : NULL;
[...]
for (i = start; i < end; i++)
if (xa_err(xa_store(&kvm->mem_attr_array, i, entry,
GFP_KERNEL_ACCOUNT)))
break;
}From Documentation/core-api/xarray.rst:
"There is no difference between an entry that has never
been stored to, one that has been erased and one that has most recently had ``NULL`` stored to it."
The way I understood the series, there needs to be a differentiation between no attributes (regular page fault) and no-access.
Quoted 6 lines
Quoted 6 lines
We implemented this in the past by using a separate address space per VTL and updating memory regions on protection changes. But having to update the memory slot layout for every permission change scales poorly, especially as we have to perform 100.000s of these operations at boot (see [1] for a little more context).
Quoted 8 lines
Quoted 4 lines
I believe the biggest barrier for us to use memory attributes is not having the ability to target specific address spaces, or to the very least having some mechanism to maintain multiple independent layers of attributes.
Can you elaborate on "specific address spaces"? In KVM, that usually means SMM, but the VTL comment above makes me think you're talking about something entirely different. E.g. can you provide a brief summary of the requirements/expectations?
I'll do so with a clear head on Monday. :)
Thanks!
Nicolas
Sean Christopherson
maintainerRe: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
Quoted 58 lines · Nicolas Saenz Julienne
Hi Sean,
Quoted 34 lines · Sean Christopherson
Quoted 33 lines · Nicolas Saenz Julienne
Hi,
On Fri Dec 2, 2022 at 6:13 AM UTC, Chao Peng wrote:
[...]
Quoted 4 lines
Documentation/virt/kvm/api.rst +4
-0+The user sets the per-page memory attributes to a guest memory range indicated +by address/size, and in return KVM adjusts address and size to reflect the +actual pages of the memory range have been successfully set to the attributes. +If the call returns 0, "address" is updated to the last successful address + 1Documentation/virt/kvm/api.rst delivery must be provided via the "reg_aen" struct. · line 6006
Quoted 10 lines
Documentation/virt/kvm/api.rst +10
-0+and "size" is updated to the remaining address size that has not been set +successfully. The user should check the return value as well as the size to +decide if the operation succeeded for the whole range or not. The user may want +to retry the operation with the returned address/size if the previous range was +partially successful. + +Both address and size should be page aligned and the supported attributes can be +retrieved with KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES. + +The "flags" field may be used for future extensions and should be set to 0s.We have been looking into adding support for the Hyper-V VSM extensions which Windows uses to implement Credential Guard. This interface seems like a good fit for one of its underlying features. I just wanted to share a bit about it, and see if we can expand it to fit this use-case. Note that this was already briefly discussed between Sean and Alex some time ago[1].
VSM introduces isolated guest execution contexts called Virtual Trust Levels (VTL) [2]. Each VTL has its own memory access protections, virtual processors states, interrupt controllers and overlay pages. VTLs are hierarchical and might enforce memory protections on less privileged VTLs. Memory protections are enforced on a per-GPA granularity.
Quoted 5 lines
Quoted 2 lines
The list of possible protections is:
- No access -- This needs a new memory attribute, I think.No, if KVM provides three bits for READ, WRITE, and EXECUTE, then userspace can get all the possible combinations. E.g. this is RWX=000b
That's not what the current implementation does, when attributes is equal 0 it clears the entries from the xarray:
static int kvm_vm_ioctl_set_mem_attributes(struct kvm *kvm,
structkvm_memory_attributes*attrs)
{entry = attrs->attributes ? xa_mk_value(attrs->attributes) : NULL; [...] for (i = start; i < end; i++) if (xa_err(xa_store(&kvm->mem_attr_array, i, entry, GFP_KERNEL_ACCOUNT))) break; }
Quoted 8 lines
Quoted 1 line
From
Documentation/core-api/xarray.rst:"There is no difference between an entry that has never
been stored to, one that has been erased and one that has most recently had ``NULL`` stored to it."The way I understood the series, there needs to be a differentiation between no attributes (regular page fault) and no-access.
Ah, I see what you're saying. There are multiple ways to solve things without a "no access" flag while still maintaining an empty xarray for the default case. E.g. invert the flags to be DENY flags[*], have an internal-only "entry valid" flag, etc.
[*] I vaguely recall suggesting a "deny" approach somewhere, but I may just be
making things up to make it look like I thought deeply about this ;-)
Re: [PATCH v10 2/9] KVM: Introduce per-page memory attributes
In reply to Sean ChristophersonHi Sean,
Quoted 3 lines · Sean Christopherson
Quoted 2 lines · Nicolas Saenz Julienne
Hi,
On Fri Dec 2, 2022 at 6:13 AM UTC, Chao Peng wrote:
[...]
Quoted 12 lines
Quoted 12 lines
VSM introduces isolated guest execution contexts called Virtual Trust Levels (VTL) [2]. Each VTL has its own memory access protections, virtual processors states, interrupt controllers and overlay pages. VTLs are hierarchical and might enforce memory protections on less privileged VTLs. Memory protections are enforced on a per-GPA granularity.
We implemented this in the past by using a separate address space per VTL and updating memory regions on protection changes. But having to update the memory slot layout for every permission change scales poorly, especially as we have to perform 100.000s of these operations at boot (see [1] for a little more context).
Quoted 8 lines
Quoted 4 lines
I believe the biggest barrier for us to use memory attributes is not having the ability to target specific address spaces, or to the very least having some mechanism to maintain multiple independent layers of attributes.
Can you elaborate on "specific address spaces"? In KVM, that usually means SMM, but the VTL comment above makes me think you're talking about something entirely different. E.g. can you provide a brief summary of the requirements/expectations?
Let me refresh some concepts first. VTLs are vCPU modes implemented by the hypervisor. Lower VTLs switch into higher VTLs [1] through a hypercall or asynchronously through interrupts. Each VTL has its own CPU architectural state, lapic and MSR state (applies to only some MSRs). These are saved/restored when switching VTLS [2]. Additionally, VTLs share a common GPA->HPA mapping, but protection bits differ depending on which VTL the CPU is on. Privileged VTLs might revoke R/W/X(+MBEC, optional) access bits from lower VTLs on a per-GPA basis.
In order to deal with the per-VTL memory protection bits, we extended the number of KVM address spaces and assigned one to each VTL. The hypervisor initializes all VTLs address spaces with the same mappings and protections, they are expected to diverge during runtime. Operations that rely on memory slots for GPA->HPA/HVA translations (including page faults) are already address space aware, so adding VTL support was fairly simple.
Ultimately, when a privileged VTL enforces memory protections on lower VTLs we update that VTL's address space memory regions to reflect them. Protection changes are requested through a hypercall, which expects the new protection to be visible system wide upon returning from it. These hypercalls happen around 100000+ times during boot, so we introduced an "atomic memory slot update" API similar to Emanuele's [3] that allows splitting memory regions/changing permissions concurrent with other vCPUs.
Now, if we had a way to map memory attributes to specific VTLs, we could use that instead. Actually, we wouldn't need to extend address spaces at all to support this (we might still need them to support Overlay Pages, but that's another story).
Hope it makes a little more sense now. :)
Nicolas
[1] In practice we've only seen VTL0 and VTL1 being used. The spec supports up to 16 VTLs.
[2] One can draw an analogy with arm's TrustZone. The hypervisor plays the role of EL3. Windows (VTL0) runs in Non-Secure (EL0/EL1) and the secure kernel (VTL1) in Secure World (EL1s/EL0s).
PATCH v10 3/9 KVM: Extend the memslot to support fd-based private memory
In reply to Chao PengIn memory encryption usage, guest memory may be encrypted with special key and can be accessed only by the guest itself. We call such memory private memory. It's valueless and sometimes can cause problem to allow userspace to access guest private memory. This new KVM memslot extension allows guest private memory being provided through a restrictedmem backed file descriptor(fd) and userspace is restricted to access the bookmarked memory in the fd.
This new extension, indicated by the new flag KVM_MEM_PRIVATE, adds two additional KVM memslot fields restricted_fd/restricted_offset to allow userspace to instruct KVM to provide guest memory through restricted_fd. 'guest_phys_addr' is mapped at the restricted_offset of restricted_fd and the size is 'memory_size'.
The extended memslot can still have the userspace_addr(hva). When use, a single memslot can maintain both private memory through restricted_fd and shared memory through userspace_addr. Whether the private or shared part is visible to guest is maintained by other KVM code.
A restrictedmem_notifier field is also added to the memslot structure to allow the restricted_fd's backing store to notify KVM the memory change, KVM then can invalidate its page table entries or handle memory errors.
Together with the change, a new config HAVE_KVM_RESTRICTED_MEM is added and right now it is selected on X86_64 only.
To make future maintenance easy, internally use a binary compatible alias struct kvm_user_mem_region to handle both the normal and the '_ext' variants.
--- Documentation/virt/kvm/api.rst | 40 ++++++++++++++++++++++----- arch/x86/kvm/Kconfig | 2 ++ arch/x86/kvm/x86.c | 2 +- include/linux/kvm_host.h | 8 ++++-- include/uapi/linux/kvm.h | 28 +++++++++++++++++++ virt/kvm/Kconfig | 3 +++ virt/kvm/kvm_main.c | 49 ++++++++++++++++++++++++++++------ 7 files changed, 114 insertions(+), 18 deletions(-)
Documentation/virt/kvm/api.rst +33 -7
@@ -1319,7 +1319,7 @@ yet and must be cleared on entry. :Capability: KVM_CAP_USER_MEMORY :Architectures: all :Type: vm ioctl -:Parameters: struct kvm_userspace_memory_region (in) +:Parameters: struct kvm_userspace_memory_region(_ext) (in) :Returns: 0 on success, -1 on error ::
@@ -1332,9 +1332,18 @@ yet and must be cleared on entry. __u64 userspace_addr; /* start of the userspace allocated memory */ }; + struct kvm_userspace_memory_region_ext { + struct kvm_userspace_memory_region region; + __u64 restricted_offset; + __u32 restricted_fd; + __u32 pad1; + __u64 pad2[14]; + }; + /* for kvm_memory_region::flags */ #define KVM_MEM_LOG_DIRTY_PAGES (1UL << 0) #define KVM_MEM_READONLY (1UL << 1) + #define KVM_MEM_PRIVATE (1UL << 2) This ioctl allows the user to create, modify or delete a guest physical memory slot. Bits 0-15 of "slot" specify the slot id and this value
@@ -1365,12 +1374,29 @@ It is recommended that the lower 21 bits of guest_phys_addr and userspace_addr be identical. This allows large pages in the guest to be backed by large pages in the host. -The flags field supports two flags: KVM_MEM_LOG_DIRTY_PAGES and -KVM_MEM_READONLY. The former can be set to instruct KVM to keep track of -writes to memory within the slot. See KVM_GET_DIRTY_LOG ioctl to know how to -use it. The latter can be set, if KVM_CAP_READONLY_MEM capability allows it, -to make a new slot read-only. In this case, writes to this memory will be -posted to userspace as KVM_EXIT_MMIO exits. +kvm_userspace_memory_region_ext struct includes all fields of +kvm_userspace_memory_region struct, while also adds additional fields for some +other features. See below description of flags field for more information. +It's recommended to use kvm_userspace_memory_region_ext in new userspace code. + +The flags field supports following flags: + +- KVM_MEM_LOG_DIRTY_PAGES to instruct KVM to keep track of writes to memory + within the slot. For more details, see KVM_GET_DIRTY_LOG ioctl. + +- KVM_MEM_READONLY, if KVM_CAP_READONLY_MEM allows, to make a new slot + read-only. In this case, writes to this memory will be posted to userspace as + KVM_EXIT_MMIO exits. + +- KVM_MEM_PRIVATE, if KVM_MEMORY_ATTRIBUTE_PRIVATE is supported (see + KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES ioctl), to indicate a new slot has private + memory backed by a file descriptor(fd) and userspace access to the fd may be + restricted. Userspace should use restricted_fd/restricted_offset in the + kvm_userspace_memory_region_ext to instruct KVM to provide private memory + to guest. Userspace should guarantee not to map the same host physical address + indicated by restricted_fd/restricted_offset to different guest physical + addresses within multiple memslots. Failed to do this may result undefined + behavior. When the KVM_CAP_SYNC_MMU capability is available, changes in the backing of the memory region are automatically reflected into the guest. For example, an
arch/x86/kvm/Kconfig +2 -0
@@ -50,6 +50,8 @@ config KVM select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM select HAVE_KVM_MEMORY_ATTRIBUTES + select HAVE_KVM_RESTRICTED_MEM if X86_64 + select RESTRICTEDMEM if HAVE_KVM_RESTRICTED_MEM help Support hosting fully virtualized guest machines using hardware virtualization extensions. You will need a fairly recent
arch/x86/kvm/x86.c +1 -1
@@ -12224,7 +12224,7 @@ void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, }for (i =0 ; i <KVM_ADDRESS_SPACE_NUM ; i++) { -struct kvm_userspace_memory_region m; +struct kvm_user_mem_region m; m.slot = id | (i <<16 ); m.flags =0 ;
include/linux/kvm_host.h +6 -2
@@ -44,6 +44,7 @@#include <asm/kvm_host.h> #include <linux/kvm_dirty_ring.h> +#include <linux/restrictedmem.h> #ifndef KVM_MAX_VCPU_IDS #define KVM_MAX_VCPU_IDS KVM_MAX_VCPUS
@@ -585,6 +586,9 @@ struct kvm_memory_slot {u32 flags;short id;u16 as_id; +struct file *restricted_file; +loff_t restricted_offset; +struct restrictedmem_notifier notifier; };static inline bool kvm_slot_dirty_track_enabled (const struct kvm_memory_slot *slot)
@@ -1123,9 +1127,9 @@ enum kvm_mr_change { };int kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem); +const struct kvm_user_mem_region *mem);int __kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem); +const struct kvm_user_mem_region *mem);void kvm_arch_free_memslot (struct kvm *kvm,struct kvm_memory_slot *slot);void kvm_arch_memslots_updated (struct kvm *kvm,u64 gen); int kvm_arch_prepare_memory_region(struct kvm *kvm,
include/uapi/linux/kvm.h +28 -0
@@ -103,6 +103,33 @@ struct kvm_userspace_memory_region {__u64 userspace_addr;/* start of the userspace allocated memory */ }; +struct kvm_userspace_memory_region_ext { +struct kvm_userspace_memory_region region; +__u64 restricted_offset; +__u32 restricted_fd; +__u32 pad1; +__u64 pad2[14 ]; +}; + +#ifdef __KERNEL__ +/* +* kvm_user_mem_region is a kernel-only alias of kvm_userspace_memory_region_ext +* that "unpacks" kvm_userspace_memory_region so that KVM can directly access +* all fields from the top-level "extended" region. +*/ +struct kvm_user_mem_region { +__u32 slot; +__u32 flags; +__u64 guest_phys_addr; +__u64 memory_size; +__u64 userspace_addr; +__u64 restricted_offset; +__u32 restricted_fd; +__u32 pad1; +__u64 pad2[14 ]; +}; +#endif +/* * The bit 0 ~ bit 15 of kvm_memory_region::flags are visible for userspace, * other bits are reserved for kvm internal use which are defined in
@@ -110,6 +137,7 @@ struct kvm_userspace_memory_region {*/ #define KVM_MEM_LOG_DIRTY_PAGES (1UL << 0)#define KVM_MEM_READONLY (1UL << 1) +#define KVM_MEM_PRIVATE (1UL << 2)/* for KVM_IRQ_LINE */ struct kvm_irq_level {
virt/kvm/Kconfig +3 -0
@@ -89,3 +89,6 @@ config KVM_XFER_TO_GUEST_WORK config HAVE_KVM_PM_NOTIFIER bool + +config HAVE_KVM_RESTRICTED_MEM + bool
virt/kvm/kvm_main.c +41 -8
89 lines not on this page · raw message
Signature · 1 line
2.25.1
Re: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Hi Chao,
Quoted 31 lines · Chao Peng
In memory encryption usage, guest memory may be encrypted with special key and can be accessed only by the guest itself. We call such memory private memory. It's valueless and sometimes can cause problem to allow userspace to access guest private memory. This new KVM memslot extension allows guest private memory being provided through a restrictedmem backed file descriptor(fd) and userspace is restricted to access the bookmarked memory in the fd.
This new extension, indicated by the new flag
KVM_MEM_PRIVATE, adds two additional KVM memslot fields restricted_fd/restricted_offset to allow userspace to instruct KVM to provide guest memory throughrestricted_fd. 'guest_phys_addr' is mapped at therestricted_offsetofrestricted_fdand the size is 'memory_size'.The extended memslot can still have the
userspace_addr(hva). When use, a single memslot can maintain both private memory throughrestricted_fdand shared memory throughuserspace_addr. Whether the private or shared part is visible to guest is maintained by other KVM code.A
restrictedmem_notifierfield is also added to the memslot structure to allow the restricted_fd's backing store to notify KVM the memory change, KVM then can invalidate its page table entries or handle memory errors.Together with the change, a new config
HAVE_KVM_RESTRICTED_MEMis added and right now it is selected onX86_64only.To make future maintenance easy, internally use a binary compatible alias struct
kvm_user_mem_regionto handle both the normal and the '_ext' variants.
Quoted 5 lines
Co-developed-by Yu Zhang <[email protected]>Signed-off-by Yu Zhang <[email protected]>Signed-off-by Chao Peng <[email protected]>Reviewed-by Fuad Tabba <[email protected]>Tested-by Fuad Tabba <[email protected]>
V9 of this patch [*] had KVM_CAP_PRIVATE_MEM, but it's not in this patch series anymore. Any reason you removed it, or is it just an omission?
[*] https://lore.kernel.org/linux-mm/[email protected]/
Thanks,
/fuad
Quoted 297 lines
--- Documentation/virt/kvm/api.rst | 40 ++++++++++++++++++++++----- arch/x86/kvm/Kconfig | 2 ++ arch/x86/kvm/x86.c | 2 +- include/linux/kvm_host.h | 8 ++++-- include/uapi/linux/kvm.h | 28 +++++++++++++++++++ virt/kvm/Kconfig | 3 +++ virt/kvm/kvm_main.c | 49 ++++++++++++++++++++++++++++------ 7 files changed, 114 insertions(+), 18 deletions(-)Documentation/virt/kvm/api.rst +33
-7@@ -1319,7 +1319,7 @@ yet and must be cleared on entry. :Capability: KVM_CAP_USER_MEMORY :Architectures: all :Type: vm ioctl -:Parameters: struct kvm_userspace_memory_region (in) +:Parameters: struct kvm_userspace_memory_region(_ext) (in) :Returns: 0 on success, -1 on error ::@@ -1332,9 +1332,18 @@ yet and must be cleared on entry. __u64 userspace_addr; /* start of the userspace allocated memory */ }; + struct kvm_userspace_memory_region_ext { + struct kvm_userspace_memory_region region; + __u64 restricted_offset; + __u32 restricted_fd; + __u32 pad1; + __u64 pad2[14]; + }; + /* for kvm_memory_region::flags */ #define KVM_MEM_LOG_DIRTY_PAGES (1UL << 0) #define KVM_MEM_READONLY (1UL << 1) + #define KVM_MEM_PRIVATE (1UL << 2) This ioctl allows the user to create, modify or delete a guest physical memory slot. Bits 0-15 of "slot" specify the slot id and this value@@ -1365,12 +1374,29 @@ It is recommended that the lower 21 bits of guest_phys_addr and userspace_addr be identical. This allows large pages in the guest to be backed by large pages in the host. -The flags field supports two flags: KVM_MEM_LOG_DIRTY_PAGES and -KVM_MEM_READONLY. The former can be set to instruct KVM to keep track of -writes to memory within the slot. See KVM_GET_DIRTY_LOG ioctl to know how to -use it. The latter can be set, if KVM_CAP_READONLY_MEM capability allows it, -to make a new slot read-only. In this case, writes to this memory will be -posted to userspace as KVM_EXIT_MMIO exits. +kvm_userspace_memory_region_ext struct includes all fields of +kvm_userspace_memory_region struct, while also adds additional fields for some +other features. See below description of flags field for more information. +It's recommended to use kvm_userspace_memory_region_ext in new userspace code. + +The flags field supports following flags: + +- KVM_MEM_LOG_DIRTY_PAGES to instruct KVM to keep track of writes to memory + within the slot. For more details, see KVM_GET_DIRTY_LOG ioctl. + +- KVM_MEM_READONLY, if KVM_CAP_READONLY_MEM allows, to make a new slot + read-only. In this case, writes to this memory will be posted to userspace as + KVM_EXIT_MMIO exits. + +- KVM_MEM_PRIVATE, if KVM_MEMORY_ATTRIBUTE_PRIVATE is supported (see + KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES ioctl), to indicate a new slot has private + memory backed by a file descriptor(fd) and userspace access to the fd may be + restricted. Userspace should use restricted_fd/restricted_offset in the + kvm_userspace_memory_region_ext to instruct KVM to provide private memory + to guest. Userspace should guarantee not to map the same host physical address + indicated by restricted_fd/restricted_offset to different guest physical + addresses within multiple memslots. Failed to do this may result undefined + behavior. When the KVM_CAP_SYNC_MMU capability is available, changes in the backing of the memory region are automatically reflected into the guest. For example, anarch/x86/kvm/Kconfig +2
-0@@ -50,6 +50,8 @@ config KVM select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM select HAVE_KVM_MEMORY_ATTRIBUTES + select HAVE_KVM_RESTRICTED_MEM if X86_64 + select RESTRICTEDMEM if HAVE_KVM_RESTRICTED_MEM help Support hosting fully virtualized guest machines using hardware virtualization extensions. You will need a fairly recentarch/x86/kvm/x86.c +1
-1@@ -12224,7 +12224,7 @@ void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, }for (i =0 ; i <KVM_ADDRESS_SPACE_NUM ; i++) { -struct kvm_userspace_memory_region m; +struct kvm_user_mem_region m; m.slot = id | (i <<16 ); m.flags =0 ;include/linux/kvm_host.h +6
-2@@ -44,6 +44,7 @@#include <asm/kvm_host.h> #include <linux/kvm_dirty_ring.h> +#include <linux/restrictedmem.h> #ifndef KVM_MAX_VCPU_IDS #define KVM_MAX_VCPU_IDS KVM_MAX_VCPUS@@ -585,6 +586,9 @@ struct kvm_memory_slot {u32 flags;short id;u16 as_id; +struct file *restricted_file; +loff_t restricted_offset; +struct restrictedmem_notifier notifier; };static inline bool kvm_slot_dirty_track_enabled (const struct kvm_memory_slot *slot)@@ -1123,9 +1127,9 @@ enum kvm_mr_change { };int kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem); +const struct kvm_user_mem_region *mem);int __kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem); +const struct kvm_user_mem_region *mem);void kvm_arch_free_memslot (struct kvm *kvm,struct kvm_memory_slot *slot);void kvm_arch_memslots_updated (struct kvm *kvm,u64 gen); int kvm_arch_prepare_memory_region(struct kvm *kvm,include/uapi/linux/kvm.h +28
-0@@ -103,6 +103,33 @@ struct kvm_userspace_memory_region {__u64 userspace_addr;/* start of the userspace allocated memory */ }; +struct kvm_userspace_memory_region_ext { +struct kvm_userspace_memory_region region; +__u64 restricted_offset; +__u32 restricted_fd; +__u32 pad1; +__u64 pad2[14 ]; +}; + +#ifdef __KERNEL__ +/* +* kvm_user_mem_region is a kernel-only alias of kvm_userspace_memory_region_ext +* that "unpacks" kvm_userspace_memory_region so that KVM can directly access +* all fields from the top-level "extended" region. +*/ +struct kvm_user_mem_region { +__u32 slot; +__u32 flags; +__u64 guest_phys_addr; +__u64 memory_size; +__u64 userspace_addr; +__u64 restricted_offset; +__u32 restricted_fd; +__u32 pad1; +__u64 pad2[14 ]; +}; +#endif +/* * The bit 0 ~ bit 15 of kvm_memory_region::flags are visible for userspace, * other bits are reserved for kvm internal use which are defined in @@ -110,6 +137,7 @@ struct kvm_userspace_memory_region {*/ #define KVM_MEM_LOG_DIRTY_PAGES (1UL << 0)#define KVM_MEM_READONLY (1UL << 1) +#define KVM_MEM_PRIVATE (1UL << 2)/* for KVM_IRQ_LINE */ struct kvm_irq_level {virt/kvm/Kconfig +3
-0@@ -89,3 +89,6 @@ config KVM_XFER_TO_GUEST_WORK config HAVE_KVM_PM_NOTIFIER bool + +config HAVE_KVM_RESTRICTED_MEM + boolvirt/kvm/kvm_main.c +41
-9@@ -1532,7 +1532,7 @@ static void kvm_replace_memslot(struct kvm *kvm, } } -static int check_memory_region_flags (const struct kvm_userspace_memory_region *mem) +static int check_memory_region_flags (const struct kvm_user_mem_region *mem) {u32 valid_flags =KVM_MEM_LOG_DIRTY_PAGES ;@@ -1934,7 +1934,7 @@ static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,* Must be called holding kvm->slots_lock for write. */ int __kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem) +const struct kvm_user_mem_region *mem) {struct kvm_memory_slot *old, *new;struct kvm_memslots *slots;@@ -2038,7 +2038,7 @@ int __kvm_set_memory_region(struct kvm *kvm,EXPORT_SYMBOL_GPL (__kvm_set_memory_region);int kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem) +const struct kvm_user_mem_region *mem) {int r;@@ -2050,7 +2050,7 @@ int kvm_set_memory_region(struct kvm *kvm,EXPORT_SYMBOL_GPL (kvm_set_memory_region);static int kvm_vm_ioctl_set_memory_region (struct kvm *kvm, -struct kvm_userspace_memory_region *mem) +struct kvm_user_mem_region *mem) {if ((u16 )mem->slot >=KVM_USER_MEM_SLOTS )return -EINVAL ;@@ -4698,6 +4698,33 @@ static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)return fd; } +#define SANITY_CHECK_MEM_REGION_FIELD (field) \ +do { \ + BUILD_BUG_ON(offsetof(struct kvm_user_mem_region, field) != \ + offsetof(struct kvm_userspace_memory_region, field)); \ + BUILD_BUG_ON(sizeof_field(struct kvm_user_mem_region, field) != \ + sizeof_field(struct kvm_userspace_memory_region, field)); \ +} while (0) + +#define SANITY_CHECK_MEM_REGION_EXT_FIELD (field) \ +do { \ + BUILD_BUG_ON(offsetof(struct kvm_user_mem_region, field) != \ + offsetof(struct kvm_userspace_memory_region_ext, field)); \ + BUILD_BUG_ON(sizeof_field(struct kvm_user_mem_region, field) != \ + sizeof_field(struct kvm_userspace_memory_region_ext, field)); \ +} while (0) + +static void kvm_sanity_check_user_mem_region_alias (void ) +{ +SANITY_CHECK_MEM_REGION_FIELD (slot); +SANITY_CHECK_MEM_REGION_FIELD (flags); +SANITY_CHECK_MEM_REGION_FIELD (guest_phys_addr); +SANITY_CHECK_MEM_REGION_FIELD (memory_size); +SANITY_CHECK_MEM_REGION_FIELD (userspace_addr); +SANITY_CHECK_MEM_REGION_EXT_FIELD (restricted_offset); +SANITY_CHECK_MEM_REGION_EXT_FIELD (restricted_fd); +} +static long kvm_vm_ioctl (struct file *filp,unsigned int ioctl,unsigned long arg) {@@ -4721,14 +4748,20 @@ static long kvm_vm_ioctl(struct file *filp,break ; }case KVM_SET_USER_MEMORY_REGION : { -struct kvm_userspace_memory_region kvm_userspace_mem; +struct kvm_user_mem_region mem; +unsigned long size =sizeof (struct kvm_userspace_memory_region ); + +kvm_sanity_check_user_mem_region_alias (); r = -EFAULT ; -if (copy_from_user (&kvm_userspace_mem, argp, -sizeof (kvm_userspace_mem))) +if (copy_from_user (&mem, argp, size)) + goto out; + + r = -EINVAL ; +if (mem.flags &KVM_MEM_PRIVATE ) goto out; - r =kvm_vm_ioctl_set_memory_region (kvm, &kvm_userspace_mem); + r =kvm_vm_ioctl_set_memory_region (kvm, &mem);break ; }case KVM_GET_DIRTY_LOG : { --2.25.1
Re: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Quoted 40 lines · Fuad Tabba
Hi Chao,
Quoted 31 lines · Chao Peng
In memory encryption usage, guest memory may be encrypted with special key and can be accessed only by the guest itself. We call such memory private memory. It's valueless and sometimes can cause problem to allow userspace to access guest private memory. This new KVM memslot extension allows guest private memory being provided through a restrictedmem backed file descriptor(fd) and userspace is restricted to access the bookmarked memory in the fd.
This new extension, indicated by the new flag
KVM_MEM_PRIVATE, adds two additional KVM memslot fields restricted_fd/restricted_offset to allow userspace to instruct KVM to provide guest memory throughrestricted_fd. 'guest_phys_addr' is mapped at therestricted_offsetofrestricted_fdand the size is 'memory_size'.The extended memslot can still have the
userspace_addr(hva). When use, a single memslot can maintain both private memory throughrestricted_fdand shared memory throughuserspace_addr. Whether the private or shared part is visible to guest is maintained by other KVM code.A
restrictedmem_notifierfield is also added to the memslot structure to allow the restricted_fd's backing store to notify KVM the memory change, KVM then can invalidate its page table entries or handle memory errors.Together with the change, a new config
HAVE_KVM_RESTRICTED_MEMis added and right now it is selected onX86_64only.To make future maintenance easy, internally use a binary compatible alias struct
kvm_user_mem_regionto handle both the normal and the '_ext' variants.Quoted 5 lines
Co-developed-by Yu Zhang <[email protected]>Signed-off-by Yu Zhang <[email protected]>Signed-off-by Chao Peng <[email protected]>Reviewed-by Fuad Tabba <[email protected]>Tested-by Fuad Tabba <[email protected]>
Quoted 3 lines
V9 of this patch [*] had
KVM_CAP_PRIVATE_MEM, but it's not in this patch series anymore. Any reason you removed it, or is it just an omission?
We had some discussion in v9 [1] to add generic memory attributes ioctls and KVM_CAP_PRIVATE_MEM can be implemented as a new KVM_MEMORY_ATTRIBUTE_PRIVATE flag via KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES() ioctl [2]. The api doc has been updated:
+- KVM_MEM_PRIVATE, if KVM_MEMORY_ATTRIBUTE_PRIVATE is supported (see + KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES ioctl) …
[1] https://lore.kernel.org/linux-mm/[email protected]/
[2]
https://lore.kernel.org/linux-mm/[email protected]/
Thanks,
Chao
Quoted 303 lines
[*] https://lore.kernel.org/linux-mm/[email protected]/
Thanks,
/fuadQuoted 297 lines
--- Documentation/virt/kvm/api.rst | 40 ++++++++++++++++++++++----- arch/x86/kvm/Kconfig | 2 ++ arch/x86/kvm/x86.c | 2 +- include/linux/kvm_host.h | 8 ++++-- include/uapi/linux/kvm.h | 28 +++++++++++++++++++ virt/kvm/Kconfig | 3 +++ virt/kvm/kvm_main.c | 49 ++++++++++++++++++++++++++++------ 7 files changed, 114 insertions(+), 18 deletions(-)Documentation/virt/kvm/api.rst +33
-7@@ -1319,7 +1319,7 @@ yet and must be cleared on entry. :Capability: KVM_CAP_USER_MEMORY :Architectures: all :Type: vm ioctl -:Parameters: struct kvm_userspace_memory_region (in) +:Parameters: struct kvm_userspace_memory_region(_ext) (in) :Returns: 0 on success, -1 on error ::@@ -1332,9 +1332,18 @@ yet and must be cleared on entry. __u64 userspace_addr; /* start of the userspace allocated memory */ }; + struct kvm_userspace_memory_region_ext { + struct kvm_userspace_memory_region region; + __u64 restricted_offset; + __u32 restricted_fd; + __u32 pad1; + __u64 pad2[14]; + }; + /* for kvm_memory_region::flags */ #define KVM_MEM_LOG_DIRTY_PAGES (1UL << 0) #define KVM_MEM_READONLY (1UL << 1) + #define KVM_MEM_PRIVATE (1UL << 2) This ioctl allows the user to create, modify or delete a guest physical memory slot. Bits 0-15 of "slot" specify the slot id and this value@@ -1365,12 +1374,29 @@ It is recommended that the lower 21 bits of guest_phys_addr and userspace_addr be identical. This allows large pages in the guest to be backed by large pages in the host. -The flags field supports two flags: KVM_MEM_LOG_DIRTY_PAGES and -KVM_MEM_READONLY. The former can be set to instruct KVM to keep track of -writes to memory within the slot. See KVM_GET_DIRTY_LOG ioctl to know how to -use it. The latter can be set, if KVM_CAP_READONLY_MEM capability allows it, -to make a new slot read-only. In this case, writes to this memory will be -posted to userspace as KVM_EXIT_MMIO exits. +kvm_userspace_memory_region_ext struct includes all fields of +kvm_userspace_memory_region struct, while also adds additional fields for some +other features. See below description of flags field for more information. +It's recommended to use kvm_userspace_memory_region_ext in new userspace code. + +The flags field supports following flags: + +- KVM_MEM_LOG_DIRTY_PAGES to instruct KVM to keep track of writes to memory + within the slot. For more details, see KVM_GET_DIRTY_LOG ioctl. + +- KVM_MEM_READONLY, if KVM_CAP_READONLY_MEM allows, to make a new slot + read-only. In this case, writes to this memory will be posted to userspace as + KVM_EXIT_MMIO exits. + +- KVM_MEM_PRIVATE, if KVM_MEMORY_ATTRIBUTE_PRIVATE is supported (see + KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES ioctl), to indicate a new slot has private + memory backed by a file descriptor(fd) and userspace access to the fd may be + restricted. Userspace should use restricted_fd/restricted_offset in the + kvm_userspace_memory_region_ext to instruct KVM to provide private memory + to guest. Userspace should guarantee not to map the same host physical address + indicated by restricted_fd/restricted_offset to different guest physical + addresses within multiple memslots. Failed to do this may result undefined + behavior. When the KVM_CAP_SYNC_MMU capability is available, changes in the backing of the memory region are automatically reflected into the guest. For example, anarch/x86/kvm/Kconfig +2
-0@@ -50,6 +50,8 @@ config KVM select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM select HAVE_KVM_MEMORY_ATTRIBUTES + select HAVE_KVM_RESTRICTED_MEM if X86_64 + select RESTRICTEDMEM if HAVE_KVM_RESTRICTED_MEM help Support hosting fully virtualized guest machines using hardware virtualization extensions. You will need a fairly recentarch/x86/kvm/x86.c +1
-1@@ -12224,7 +12224,7 @@ void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, }for (i =0 ; i <KVM_ADDRESS_SPACE_NUM ; i++) { -struct kvm_userspace_memory_region m; +struct kvm_user_mem_region m; m.slot = id | (i <<16 ); m.flags =0 ;include/linux/kvm_host.h +6
-2@@ -44,6 +44,7 @@#include <asm/kvm_host.h> #include <linux/kvm_dirty_ring.h> +#include <linux/restrictedmem.h> #ifndef KVM_MAX_VCPU_IDS #define KVM_MAX_VCPU_IDS KVM_MAX_VCPUS@@ -585,6 +586,9 @@ struct kvm_memory_slot {u32 flags;short id;u16 as_id; +struct file *restricted_file; +loff_t restricted_offset; +struct restrictedmem_notifier notifier; };static inline bool kvm_slot_dirty_track_enabled (const struct kvm_memory_slot *slot)@@ -1123,9 +1127,9 @@ enum kvm_mr_change { };int kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem); +const struct kvm_user_mem_region *mem);int __kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem); +const struct kvm_user_mem_region *mem);void kvm_arch_free_memslot (struct kvm *kvm,struct kvm_memory_slot *slot);void kvm_arch_memslots_updated (struct kvm *kvm,u64 gen); int kvm_arch_prepare_memory_region(struct kvm *kvm,include/uapi/linux/kvm.h +28
-0@@ -103,6 +103,33 @@ struct kvm_userspace_memory_region {__u64 userspace_addr;/* start of the userspace allocated memory */ }; +struct kvm_userspace_memory_region_ext { +struct kvm_userspace_memory_region region; +__u64 restricted_offset; +__u32 restricted_fd; +__u32 pad1; +__u64 pad2[14 ]; +}; + +#ifdef __KERNEL__ +/* +* kvm_user_mem_region is a kernel-only alias of kvm_userspace_memory_region_ext +* that "unpacks" kvm_userspace_memory_region so that KVM can directly access +* all fields from the top-level "extended" region. +*/ +struct kvm_user_mem_region { +__u32 slot; +__u32 flags; +__u64 guest_phys_addr; +__u64 memory_size; +__u64 userspace_addr; +__u64 restricted_offset; +__u32 restricted_fd; +__u32 pad1; +__u64 pad2[14 ]; +}; +#endif +/* * The bit 0 ~ bit 15 of kvm_memory_region::flags are visible for userspace, * other bits are reserved for kvm internal use which are defined in @@ -110,6 +137,7 @@ struct kvm_userspace_memory_region {*/ #define KVM_MEM_LOG_DIRTY_PAGES (1UL << 0)#define KVM_MEM_READONLY (1UL << 1) +#define KVM_MEM_PRIVATE (1UL << 2)/* for KVM_IRQ_LINE */ struct kvm_irq_level {virt/kvm/Kconfig +3
-0@@ -89,3 +89,6 @@ config KVM_XFER_TO_GUEST_WORK config HAVE_KVM_PM_NOTIFIER bool + +config HAVE_KVM_RESTRICTED_MEM + boolvirt/kvm/kvm_main.c +41
-9@@ -1532,7 +1532,7 @@ static void kvm_replace_memslot(struct kvm *kvm, } } -static int check_memory_region_flags (const struct kvm_userspace_memory_region *mem) +static int check_memory_region_flags (const struct kvm_user_mem_region *mem) {u32 valid_flags =KVM_MEM_LOG_DIRTY_PAGES ;@@ -1934,7 +1934,7 @@ static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,* Must be called holding kvm->slots_lock for write. */ int __kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem) +const struct kvm_user_mem_region *mem) {struct kvm_memory_slot *old, *new;struct kvm_memslots *slots;@@ -2038,7 +2038,7 @@ int __kvm_set_memory_region(struct kvm *kvm,EXPORT_SYMBOL_GPL (__kvm_set_memory_region);int kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem) +const struct kvm_user_mem_region *mem) {int r;@@ -2050,7 +2050,7 @@ int kvm_set_memory_region(struct kvm *kvm,EXPORT_SYMBOL_GPL (kvm_set_memory_region);static int kvm_vm_ioctl_set_memory_region (struct kvm *kvm, -struct kvm_userspace_memory_region *mem) +struct kvm_user_mem_region *mem) {if ((u16 )mem->slot >=KVM_USER_MEM_SLOTS )return -EINVAL ;@@ -4698,6 +4698,33 @@ static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)return fd; } +#define SANITY_CHECK_MEM_REGION_FIELD (field) \ +do { \ + BUILD_BUG_ON(offsetof(struct kvm_user_mem_region, field) != \ + offsetof(struct kvm_userspace_memory_region, field)); \ + BUILD_BUG_ON(sizeof_field(struct kvm_user_mem_region, field) != \ + sizeof_field(struct kvm_userspace_memory_region, field)); \ +} while (0) + +#define SANITY_CHECK_MEM_REGION_EXT_FIELD (field) \ +do { \ + BUILD_BUG_ON(offsetof(struct kvm_user_mem_region, field) != \ + offsetof(struct kvm_userspace_memory_region_ext, field)); \ + BUILD_BUG_ON(sizeof_field(struct kvm_user_mem_region, field) != \ + sizeof_field(struct kvm_userspace_memory_region_ext, field)); \ +} while (0) + +static void kvm_sanity_check_user_mem_region_alias (void ) +{ +SANITY_CHECK_MEM_REGION_FIELD (slot); +SANITY_CHECK_MEM_REGION_FIELD (flags); +SANITY_CHECK_MEM_REGION_FIELD (guest_phys_addr); +SANITY_CHECK_MEM_REGION_FIELD (memory_size); +SANITY_CHECK_MEM_REGION_FIELD (userspace_addr); +SANITY_CHECK_MEM_REGION_EXT_FIELD (restricted_offset); +SANITY_CHECK_MEM_REGION_EXT_FIELD (restricted_fd); +} +static long kvm_vm_ioctl (struct file *filp,unsigned int ioctl,unsigned long arg) {@@ -4721,14 +4748,20 @@ static long kvm_vm_ioctl(struct file *filp,break ; }case KVM_SET_USER_MEMORY_REGION : { -struct kvm_userspace_memory_region kvm_userspace_mem; +struct kvm_user_mem_region mem; +unsigned long size =sizeof (struct kvm_userspace_memory_region ); + +kvm_sanity_check_user_mem_region_alias (); r = -EFAULT ; -if (copy_from_user (&kvm_userspace_mem, argp, -sizeof (kvm_userspace_mem))) +if (copy_from_user (&mem, argp, size)) + goto out; + + r = -EINVAL ; +if (mem.flags &KVM_MEM_PRIVATE ) goto out; - r =kvm_vm_ioctl_set_memory_region (kvm, &kvm_userspace_mem); + r =kvm_vm_ioctl_set_memory_region (kvm, &mem);break ; }case KVM_GET_DIRTY_LOG : { --2.25.1
Re: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Hi Chao,
Quoted 51 lines · Chao Peng
Quoted 40 lines · Fuad Tabba
Hi Chao,
Quoted 31 lines · Chao Peng
In memory encryption usage, guest memory may be encrypted with special key and can be accessed only by the guest itself. We call such memory private memory. It's valueless and sometimes can cause problem to allow userspace to access guest private memory. This new KVM memslot extension allows guest private memory being provided through a restrictedmem backed file descriptor(fd) and userspace is restricted to access the bookmarked memory in the fd.
This new extension, indicated by the new flag
KVM_MEM_PRIVATE, adds two additional KVM memslot fields restricted_fd/restricted_offset to allow userspace to instruct KVM to provide guest memory throughrestricted_fd. 'guest_phys_addr' is mapped at therestricted_offsetofrestricted_fdand the size is 'memory_size'.The extended memslot can still have the
userspace_addr(hva). When use, a single memslot can maintain both private memory throughrestricted_fdand shared memory throughuserspace_addr. Whether the private or shared part is visible to guest is maintained by other KVM code.A
restrictedmem_notifierfield is also added to the memslot structure to allow the restricted_fd's backing store to notify KVM the memory change, KVM then can invalidate its page table entries or handle memory errors.Together with the change, a new config
HAVE_KVM_RESTRICTED_MEMis added and right now it is selected onX86_64only.To make future maintenance easy, internally use a binary compatible alias struct
kvm_user_mem_regionto handle both the normal and the '_ext' variants.Quoted 5 lines
Co-developed-by Yu Zhang <[email protected]>Signed-off-by Yu Zhang <[email protected]>Signed-off-by Chao Peng <[email protected]>Reviewed-by Fuad Tabba <[email protected]>Tested-by Fuad Tabba <[email protected]>Quoted 3 lines
V9 of this patch [*] had
KVM_CAP_PRIVATE_MEM, but it's not in this patch series anymore. Any reason you removed it, or is it just an omission?We had some discussion in v9 [1] to add generic memory attributes ioctls and
KVM_CAP_PRIVATE_MEMcan be implemented as a newKVM_MEMORY_ATTRIBUTE_PRIVATEflag viaKVM_GET_SUPPORTED_MEMORY_ATTRIBUTES()ioctl [2]. The api doc has been updated:
Quoted 7 lines
+- KVM_MEM_PRIVATE, if KVM_MEMORY_ATTRIBUTE_PRIVATE is supported (see + KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES ioctl) …[1] https://lore.kernel.org/linux-mm/[email protected]/
[2]
https://lore.kernel.org/linux-mm/[email protected]/
I see. I just retested it with KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES, and my Reviewed/Tested-by still apply.
Cheers,
/fuad
Quoted 306 lines
Thanks,
ChaoQuoted 303 lines
[*] https://lore.kernel.org/linux-mm/[email protected]/
Thanks,
/fuadQuoted 297 lines
--- Documentation/virt/kvm/api.rst | 40 ++++++++++++++++++++++----- arch/x86/kvm/Kconfig | 2 ++ arch/x86/kvm/x86.c | 2 +- include/linux/kvm_host.h | 8 ++++-- include/uapi/linux/kvm.h | 28 +++++++++++++++++++ virt/kvm/Kconfig | 3 +++ virt/kvm/kvm_main.c | 49 ++++++++++++++++++++++++++++------ 7 files changed, 114 insertions(+), 18 deletions(-)Documentation/virt/kvm/api.rst +33
-7@@ -1319,7 +1319,7 @@ yet and must be cleared on entry. :Capability: KVM_CAP_USER_MEMORY :Architectures: all :Type: vm ioctl -:Parameters: struct kvm_userspace_memory_region (in) +:Parameters: struct kvm_userspace_memory_region(_ext) (in) :Returns: 0 on success, -1 on error ::@@ -1332,9 +1332,18 @@ yet and must be cleared on entry. __u64 userspace_addr; /* start of the userspace allocated memory */ }; + struct kvm_userspace_memory_region_ext { + struct kvm_userspace_memory_region region; + __u64 restricted_offset; + __u32 restricted_fd; + __u32 pad1; + __u64 pad2[14]; + }; + /* for kvm_memory_region::flags */ #define KVM_MEM_LOG_DIRTY_PAGES (1UL << 0) #define KVM_MEM_READONLY (1UL << 1) + #define KVM_MEM_PRIVATE (1UL << 2) This ioctl allows the user to create, modify or delete a guest physical memory slot. Bits 0-15 of "slot" specify the slot id and this value@@ -1365,12 +1374,29 @@ It is recommended that the lower 21 bits of guest_phys_addr and userspace_addr be identical. This allows large pages in the guest to be backed by large pages in the host. -The flags field supports two flags: KVM_MEM_LOG_DIRTY_PAGES and -KVM_MEM_READONLY. The former can be set to instruct KVM to keep track of -writes to memory within the slot. See KVM_GET_DIRTY_LOG ioctl to know how to -use it. The latter can be set, if KVM_CAP_READONLY_MEM capability allows it, -to make a new slot read-only. In this case, writes to this memory will be -posted to userspace as KVM_EXIT_MMIO exits. +kvm_userspace_memory_region_ext struct includes all fields of +kvm_userspace_memory_region struct, while also adds additional fields for some +other features. See below description of flags field for more information. +It's recommended to use kvm_userspace_memory_region_ext in new userspace code. + +The flags field supports following flags: + +- KVM_MEM_LOG_DIRTY_PAGES to instruct KVM to keep track of writes to memory + within the slot. For more details, see KVM_GET_DIRTY_LOG ioctl. + +- KVM_MEM_READONLY, if KVM_CAP_READONLY_MEM allows, to make a new slot + read-only. In this case, writes to this memory will be posted to userspace as + KVM_EXIT_MMIO exits. + +- KVM_MEM_PRIVATE, if KVM_MEMORY_ATTRIBUTE_PRIVATE is supported (see + KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES ioctl), to indicate a new slot has private + memory backed by a file descriptor(fd) and userspace access to the fd may be + restricted. Userspace should use restricted_fd/restricted_offset in the + kvm_userspace_memory_region_ext to instruct KVM to provide private memory + to guest. Userspace should guarantee not to map the same host physical address + indicated by restricted_fd/restricted_offset to different guest physical + addresses within multiple memslots. Failed to do this may result undefined + behavior. When the KVM_CAP_SYNC_MMU capability is available, changes in the backing of the memory region are automatically reflected into the guest. For example, anarch/x86/kvm/Kconfig +2
-0@@ -50,6 +50,8 @@ config KVM select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM select HAVE_KVM_MEMORY_ATTRIBUTES + select HAVE_KVM_RESTRICTED_MEM if X86_64 + select RESTRICTEDMEM if HAVE_KVM_RESTRICTED_MEM help Support hosting fully virtualized guest machines using hardware virtualization extensions. You will need a fairly recentarch/x86/kvm/x86.c +1
-1@@ -12224,7 +12224,7 @@ void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, }for (i =0 ; i <KVM_ADDRESS_SPACE_NUM ; i++) { -struct kvm_userspace_memory_region m; +struct kvm_user_mem_region m; m.slot = id | (i <<16 ); m.flags =0 ;include/linux/kvm_host.h +6
-2@@ -44,6 +44,7 @@#include <asm/kvm_host.h> #include <linux/kvm_dirty_ring.h> +#include <linux/restrictedmem.h> #ifndef KVM_MAX_VCPU_IDS #define KVM_MAX_VCPU_IDS KVM_MAX_VCPUS@@ -585,6 +586,9 @@ struct kvm_memory_slot {u32 flags;short id;u16 as_id; +struct file *restricted_file; +loff_t restricted_offset; +struct restrictedmem_notifier notifier; };static inline bool kvm_slot_dirty_track_enabled (const struct kvm_memory_slot *slot)@@ -1123,9 +1127,9 @@ enum kvm_mr_change { };int kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem); +const struct kvm_user_mem_region *mem);int __kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem); +const struct kvm_user_mem_region *mem);void kvm_arch_free_memslot (struct kvm *kvm,struct kvm_memory_slot *slot);void kvm_arch_memslots_updated (struct kvm *kvm,u64 gen); int kvm_arch_prepare_memory_region(struct kvm *kvm,include/uapi/linux/kvm.h +28
-0@@ -103,6 +103,33 @@ struct kvm_userspace_memory_region {__u64 userspace_addr;/* start of the userspace allocated memory */ }; +struct kvm_userspace_memory_region_ext { +struct kvm_userspace_memory_region region; +__u64 restricted_offset; +__u32 restricted_fd; +__u32 pad1; +__u64 pad2[14 ]; +}; + +#ifdef __KERNEL__ +/* +* kvm_user_mem_region is a kernel-only alias of kvm_userspace_memory_region_ext +* that "unpacks" kvm_userspace_memory_region so that KVM can directly access +* all fields from the top-level "extended" region. +*/ +struct kvm_user_mem_region { +__u32 slot; +__u32 flags; +__u64 guest_phys_addr; +__u64 memory_size; +__u64 userspace_addr; +__u64 restricted_offset; +__u32 restricted_fd; +__u32 pad1; +__u64 pad2[14 ]; +}; +#endif +/* * The bit 0 ~ bit 15 of kvm_memory_region::flags are visible for userspace, * other bits are reserved for kvm internal use which are defined in @@ -110,6 +137,7 @@ struct kvm_userspace_memory_region {*/ #define KVM_MEM_LOG_DIRTY_PAGES (1UL << 0)#define KVM_MEM_READONLY (1UL << 1) +#define KVM_MEM_PRIVATE (1UL << 2)/* for KVM_IRQ_LINE */ struct kvm_irq_level {virt/kvm/Kconfig +3
-0@@ -89,3 +89,6 @@ config KVM_XFER_TO_GUEST_WORK config HAVE_KVM_PM_NOTIFIER bool + +config HAVE_KVM_RESTRICTED_MEM + boolvirt/kvm/kvm_main.c +41
-9@@ -1532,7 +1532,7 @@ static void kvm_replace_memslot(struct kvm *kvm, } } -static int check_memory_region_flags (const struct kvm_userspace_memory_region *mem) +static int check_memory_region_flags (const struct kvm_user_mem_region *mem) {u32 valid_flags =KVM_MEM_LOG_DIRTY_PAGES ;@@ -1934,7 +1934,7 @@ static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,* Must be called holding kvm->slots_lock for write. */ int __kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem) +const struct kvm_user_mem_region *mem) {struct kvm_memory_slot *old, *new;struct kvm_memslots *slots;@@ -2038,7 +2038,7 @@ int __kvm_set_memory_region(struct kvm *kvm,EXPORT_SYMBOL_GPL (__kvm_set_memory_region);int kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem) +const struct kvm_user_mem_region *mem) {int r;@@ -2050,7 +2050,7 @@ int kvm_set_memory_region(struct kvm *kvm,EXPORT_SYMBOL_GPL (kvm_set_memory_region);static int kvm_vm_ioctl_set_memory_region (struct kvm *kvm, -struct kvm_userspace_memory_region *mem) +struct kvm_user_mem_region *mem) {if ((u16 )mem->slot >=KVM_USER_MEM_SLOTS )return -EINVAL ;@@ -4698,6 +4698,33 @@ static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)return fd; } +#define SANITY_CHECK_MEM_REGION_FIELD (field) \ +do { \ + BUILD_BUG_ON(offsetof(struct kvm_user_mem_region, field) != \ + offsetof(struct kvm_userspace_memory_region, field)); \ + BUILD_BUG_ON(sizeof_field(struct kvm_user_mem_region, field) != \ + sizeof_field(struct kvm_userspace_memory_region, field)); \ +} while (0) + +#define SANITY_CHECK_MEM_REGION_EXT_FIELD (field) \ +do { \ + BUILD_BUG_ON(offsetof(struct kvm_user_mem_region, field) != \ + offsetof(struct kvm_userspace_memory_region_ext, field)); \ + BUILD_BUG_ON(sizeof_field(struct kvm_user_mem_region, field) != \ + sizeof_field(struct kvm_userspace_memory_region_ext, field)); \ +} while (0) + +static void kvm_sanity_check_user_mem_region_alias (void ) +{ +SANITY_CHECK_MEM_REGION_FIELD (slot); +SANITY_CHECK_MEM_REGION_FIELD (flags); +SANITY_CHECK_MEM_REGION_FIELD (guest_phys_addr); +SANITY_CHECK_MEM_REGION_FIELD (memory_size); +SANITY_CHECK_MEM_REGION_FIELD (userspace_addr); +SANITY_CHECK_MEM_REGION_EXT_FIELD (restricted_offset); +SANITY_CHECK_MEM_REGION_EXT_FIELD (restricted_fd); +} +static long kvm_vm_ioctl (struct file *filp,unsigned int ioctl,unsigned long arg) {@@ -4721,14 +4748,20 @@ static long kvm_vm_ioctl(struct file *filp,break ; }case KVM_SET_USER_MEMORY_REGION : { -struct kvm_userspace_memory_region kvm_userspace_mem; +struct kvm_user_mem_region mem; +unsigned long size =sizeof (struct kvm_userspace_memory_region ); + +kvm_sanity_check_user_mem_region_alias (); r = -EFAULT ; -if (copy_from_user (&kvm_userspace_mem, argp, -sizeof (kvm_userspace_mem))) +if (copy_from_user (&mem, argp, size)) + goto out; + + r = -EINVAL ; +if (mem.flags &KVM_MEM_PRIVATE ) goto out; - r =kvm_vm_ioctl_set_memory_region (kvm, &kvm_userspace_mem); + r =kvm_vm_ioctl_set_memory_region (kvm, &mem);break ; }case KVM_GET_DIRTY_LOG : { --2.25.1
Re: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Quoted 58 lines · Fuad Tabba
Hi Chao,
Quoted 55 lines · Chao Peng
Quoted 40 lines · Fuad Tabba
Hi Chao,
Quoted 31 lines · Chao Peng
In memory encryption usage, guest memory may be encrypted with special key and can be accessed only by the guest itself. We call such memory private memory. It's valueless and sometimes can cause problem to allow userspace to access guest private memory. This new KVM memslot extension allows guest private memory being provided through a restrictedmem backed file descriptor(fd) and userspace is restricted to access the bookmarked memory in the fd.
This new extension, indicated by the new flag
KVM_MEM_PRIVATE, adds two additional KVM memslot fields restricted_fd/restricted_offset to allow userspace to instruct KVM to provide guest memory throughrestricted_fd. 'guest_phys_addr' is mapped at therestricted_offsetofrestricted_fdand the size is 'memory_size'.The extended memslot can still have the
userspace_addr(hva). When use, a single memslot can maintain both private memory throughrestricted_fdand shared memory throughuserspace_addr. Whether the private or shared part is visible to guest is maintained by other KVM code.A
restrictedmem_notifierfield is also added to the memslot structure to allow the restricted_fd's backing store to notify KVM the memory change, KVM then can invalidate its page table entries or handle memory errors.Together with the change, a new config
HAVE_KVM_RESTRICTED_MEMis added and right now it is selected onX86_64only.To make future maintenance easy, internally use a binary compatible alias struct
kvm_user_mem_regionto handle both the normal and the '_ext' variants.Quoted 5 lines
Co-developed-by Yu Zhang <[email protected]>Signed-off-by Yu Zhang <[email protected]>Signed-off-by Chao Peng <[email protected]>Reviewed-by Fuad Tabba <[email protected]>Tested-by Fuad Tabba <[email protected]>Quoted 3 lines
V9 of this patch [*] had
KVM_CAP_PRIVATE_MEM, but it's not in this patch series anymore. Any reason you removed it, or is it just an omission?We had some discussion in v9 [1] to add generic memory attributes ioctls and
KVM_CAP_PRIVATE_MEMcan be implemented as a newKVM_MEMORY_ATTRIBUTE_PRIVATEflag viaKVM_GET_SUPPORTED_MEMORY_ATTRIBUTES()ioctl [2]. The api doc has been updated:+- KVM_MEM_PRIVATE, if KVM_MEMORY_ATTRIBUTE_PRIVATE is supported (see + KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES ioctl) …
Quoted 6 lines
Quoted 3 lines
[1] https://lore.kernel.org/linux-mm/[email protected]/
[2]
https://lore.kernel.org/linux-mm/[email protected]/I see. I just retested it with
KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES, and my Reviewed/Tested-by still apply.
Thanks for the info.
Chao
Quoted 310 lines
Cheers,
/fuadQuoted 306 lines
Thanks,
ChaoQuoted 303 lines
[*] https://lore.kernel.org/linux-mm/[email protected]/
Thanks,
/fuadQuoted 297 lines
--- Documentation/virt/kvm/api.rst | 40 ++++++++++++++++++++++----- arch/x86/kvm/Kconfig | 2 ++ arch/x86/kvm/x86.c | 2 +- include/linux/kvm_host.h | 8 ++++-- include/uapi/linux/kvm.h | 28 +++++++++++++++++++ virt/kvm/Kconfig | 3 +++ virt/kvm/kvm_main.c | 49 ++++++++++++++++++++++++++++------ 7 files changed, 114 insertions(+), 18 deletions(-)Documentation/virt/kvm/api.rst +33
-7@@ -1319,7 +1319,7 @@ yet and must be cleared on entry. :Capability: KVM_CAP_USER_MEMORY :Architectures: all :Type: vm ioctl -:Parameters: struct kvm_userspace_memory_region (in) +:Parameters: struct kvm_userspace_memory_region(_ext) (in) :Returns: 0 on success, -1 on error ::@@ -1332,9 +1332,18 @@ yet and must be cleared on entry. __u64 userspace_addr; /* start of the userspace allocated memory */ }; + struct kvm_userspace_memory_region_ext { + struct kvm_userspace_memory_region region; + __u64 restricted_offset; + __u32 restricted_fd; + __u32 pad1; + __u64 pad2[14]; + }; + /* for kvm_memory_region::flags */ #define KVM_MEM_LOG_DIRTY_PAGES (1UL << 0) #define KVM_MEM_READONLY (1UL << 1) + #define KVM_MEM_PRIVATE (1UL << 2) This ioctl allows the user to create, modify or delete a guest physical memory slot. Bits 0-15 of "slot" specify the slot id and this value@@ -1365,12 +1374,29 @@ It is recommended that the lower 21 bits of guest_phys_addr and userspace_addr be identical. This allows large pages in the guest to be backed by large pages in the host. -The flags field supports two flags: KVM_MEM_LOG_DIRTY_PAGES and -KVM_MEM_READONLY. The former can be set to instruct KVM to keep track of -writes to memory within the slot. See KVM_GET_DIRTY_LOG ioctl to know how to -use it. The latter can be set, if KVM_CAP_READONLY_MEM capability allows it, -to make a new slot read-only. In this case, writes to this memory will be -posted to userspace as KVM_EXIT_MMIO exits. +kvm_userspace_memory_region_ext struct includes all fields of +kvm_userspace_memory_region struct, while also adds additional fields for some +other features. See below description of flags field for more information. +It's recommended to use kvm_userspace_memory_region_ext in new userspace code. + +The flags field supports following flags: + +- KVM_MEM_LOG_DIRTY_PAGES to instruct KVM to keep track of writes to memory + within the slot. For more details, see KVM_GET_DIRTY_LOG ioctl. + +- KVM_MEM_READONLY, if KVM_CAP_READONLY_MEM allows, to make a new slot + read-only. In this case, writes to this memory will be posted to userspace as + KVM_EXIT_MMIO exits. + +- KVM_MEM_PRIVATE, if KVM_MEMORY_ATTRIBUTE_PRIVATE is supported (see + KVM_GET_SUPPORTED_MEMORY_ATTRIBUTES ioctl), to indicate a new slot has private + memory backed by a file descriptor(fd) and userspace access to the fd may be + restricted. Userspace should use restricted_fd/restricted_offset in the + kvm_userspace_memory_region_ext to instruct KVM to provide private memory + to guest. Userspace should guarantee not to map the same host physical address + indicated by restricted_fd/restricted_offset to different guest physical + addresses within multiple memslots. Failed to do this may result undefined + behavior. When the KVM_CAP_SYNC_MMU capability is available, changes in the backing of the memory region are automatically reflected into the guest. For example, anarch/x86/kvm/Kconfig +2
-0@@ -50,6 +50,8 @@ config KVM select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM select HAVE_KVM_MEMORY_ATTRIBUTES + select HAVE_KVM_RESTRICTED_MEM if X86_64 + select RESTRICTEDMEM if HAVE_KVM_RESTRICTED_MEM help Support hosting fully virtualized guest machines using hardware virtualization extensions. You will need a fairly recentarch/x86/kvm/x86.c +1
-1@@ -12224,7 +12224,7 @@ void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, }for (i =0 ; i <KVM_ADDRESS_SPACE_NUM ; i++) { -struct kvm_userspace_memory_region m; +struct kvm_user_mem_region m; m.slot = id | (i <<16 ); m.flags =0 ;include/linux/kvm_host.h +6
-2@@ -44,6 +44,7 @@#include <asm/kvm_host.h> #include <linux/kvm_dirty_ring.h> +#include <linux/restrictedmem.h> #ifndef KVM_MAX_VCPU_IDS #define KVM_MAX_VCPU_IDS KVM_MAX_VCPUS@@ -585,6 +586,9 @@ struct kvm_memory_slot {u32 flags;short id;u16 as_id; +struct file *restricted_file; +loff_t restricted_offset; +struct restrictedmem_notifier notifier; };static inline bool kvm_slot_dirty_track_enabled (const struct kvm_memory_slot *slot)@@ -1123,9 +1127,9 @@ enum kvm_mr_change { };int kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem); +const struct kvm_user_mem_region *mem);int __kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem); +const struct kvm_user_mem_region *mem);void kvm_arch_free_memslot (struct kvm *kvm,struct kvm_memory_slot *slot);void kvm_arch_memslots_updated (struct kvm *kvm,u64 gen); int kvm_arch_prepare_memory_region(struct kvm *kvm,include/uapi/linux/kvm.h +28
-0@@ -103,6 +103,33 @@ struct kvm_userspace_memory_region {__u64 userspace_addr;/* start of the userspace allocated memory */ }; +struct kvm_userspace_memory_region_ext { +struct kvm_userspace_memory_region region; +__u64 restricted_offset; +__u32 restricted_fd; +__u32 pad1; +__u64 pad2[14 ]; +}; + +#ifdef __KERNEL__ +/* +* kvm_user_mem_region is a kernel-only alias of kvm_userspace_memory_region_ext +* that "unpacks" kvm_userspace_memory_region so that KVM can directly access +* all fields from the top-level "extended" region. +*/ +struct kvm_user_mem_region { +__u32 slot; +__u32 flags; +__u64 guest_phys_addr; +__u64 memory_size; +__u64 userspace_addr; +__u64 restricted_offset; +__u32 restricted_fd; +__u32 pad1; +__u64 pad2[14 ]; +}; +#endif +/* * The bit 0 ~ bit 15 of kvm_memory_region::flags are visible for userspace, * other bits are reserved for kvm internal use which are defined in @@ -110,6 +137,7 @@ struct kvm_userspace_memory_region {*/ #define KVM_MEM_LOG_DIRTY_PAGES (1UL << 0)#define KVM_MEM_READONLY (1UL << 1) +#define KVM_MEM_PRIVATE (1UL << 2)/* for KVM_IRQ_LINE */ struct kvm_irq_level {virt/kvm/Kconfig +3
-0@@ -89,3 +89,6 @@ config KVM_XFER_TO_GUEST_WORK config HAVE_KVM_PM_NOTIFIER bool + +config HAVE_KVM_RESTRICTED_MEM + boolvirt/kvm/kvm_main.c +41
-9@@ -1532,7 +1532,7 @@ static void kvm_replace_memslot(struct kvm *kvm, } } -static int check_memory_region_flags (const struct kvm_userspace_memory_region *mem) +static int check_memory_region_flags (const struct kvm_user_mem_region *mem) {u32 valid_flags =KVM_MEM_LOG_DIRTY_PAGES ;@@ -1934,7 +1934,7 @@ static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,* Must be called holding kvm->slots_lock for write. */ int __kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem) +const struct kvm_user_mem_region *mem) {struct kvm_memory_slot *old, *new;struct kvm_memslots *slots;@@ -2038,7 +2038,7 @@ int __kvm_set_memory_region(struct kvm *kvm,EXPORT_SYMBOL_GPL (__kvm_set_memory_region);int kvm_set_memory_region (struct kvm *kvm, -const struct kvm_userspace_memory_region *mem) +const struct kvm_user_mem_region *mem) {int r;@@ -2050,7 +2050,7 @@ int kvm_set_memory_region(struct kvm *kvm,EXPORT_SYMBOL_GPL (kvm_set_memory_region);static int kvm_vm_ioctl_set_memory_region (struct kvm *kvm, -struct kvm_userspace_memory_region *mem) +struct kvm_user_mem_region *mem) {if ((u16 )mem->slot >=KVM_USER_MEM_SLOTS )return -EINVAL ;@@ -4698,6 +4698,33 @@ static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)return fd; } +#define SANITY_CHECK_MEM_REGION_FIELD (field) \ +do { \ + BUILD_BUG_ON(offsetof(struct kvm_user_mem_region, field) != \ + offsetof(struct kvm_userspace_memory_region, field)); \ + BUILD_BUG_ON(sizeof_field(struct kvm_user_mem_region, field) != \ + sizeof_field(struct kvm_userspace_memory_region, field)); \ +} while (0) + +#define SANITY_CHECK_MEM_REGION_EXT_FIELD (field) \ +do { \ + BUILD_BUG_ON(offsetof(struct kvm_user_mem_region, field) != \ + offsetof(struct kvm_userspace_memory_region_ext, field)); \ + BUILD_BUG_ON(sizeof_field(struct kvm_user_mem_region, field) != \ + sizeof_field(struct kvm_userspace_memory_region_ext, field)); \ +} while (0) + +static void kvm_sanity_check_user_mem_region_alias (void ) +{ +SANITY_CHECK_MEM_REGION_FIELD (slot); +SANITY_CHECK_MEM_REGION_FIELD (flags); +SANITY_CHECK_MEM_REGION_FIELD (guest_phys_addr); +SANITY_CHECK_MEM_REGION_FIELD (memory_size); +SANITY_CHECK_MEM_REGION_FIELD (userspace_addr); +SANITY_CHECK_MEM_REGION_EXT_FIELD (restricted_offset); +SANITY_CHECK_MEM_REGION_EXT_FIELD (restricted_fd); +} +static long kvm_vm_ioctl (struct file *filp,unsigned int ioctl,unsigned long arg) {@@ -4721,14 +4748,20 @@ static long kvm_vm_ioctl(struct file *filp,break ; }case KVM_SET_USER_MEMORY_REGION : { -struct kvm_userspace_memory_region kvm_userspace_mem; +struct kvm_user_mem_region mem; +unsigned long size =sizeof (struct kvm_userspace_memory_region ); + +kvm_sanity_check_user_mem_region_alias (); r = -EFAULT ; -if (copy_from_user (&kvm_userspace_mem, argp, -sizeof (kvm_userspace_mem))) +if (copy_from_user (&mem, argp, size)) + goto out; + + r = -EINVAL ; +if (mem.flags &KVM_MEM_PRIVATE ) goto out; - r =kvm_vm_ioctl_set_memory_region (kvm, &kvm_userspace_mem); + r =kvm_vm_ioctl_set_memory_region (kvm, &mem);break ; }case KVM_GET_DIRTY_LOG : { --2.25.1
Re: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
In reply to Chao PengOn 12/2/2022 2:13 PM, Chao Peng wrote:
..
Quoted 3 lines
Together with the change, a new config
HAVE_KVM_RESTRICTED_MEMis added and right now it is selected onX86_64only.
From the patch implementation, I have no idea why HAVE_KVM_RESTRICTED_MEM is needed.
Re: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Quoted 10 lines · Xiaoyao Li
On 12/2/2022 2:13 PM, Chao Peng wrote:
..
Quoted 3 lines
Together with the change, a new config
HAVE_KVM_RESTRICTED_MEMis added and right now it is selected onX86_64only.From the patch implementation, I have no idea why
HAVE_KVM_RESTRICTED_MEMis needed.
The reason is we want KVM further controls the feature enabling. An opt-in CONFIG_RESTRICTEDMEM can cause problem if user sets that for unsupported architectures.
Here is the original discussion:
https://lore.kernel.org/all/[email protected]/
Thanks,
Chao
Re: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Quoted 9 lines · Chao Peng
Quoted 8 lines · Xiaoyao Li
On 12/2/2022 2:13 PM, Chao Peng wrote:
..
Quoted 3 lines
Together with the change, a new config
HAVE_KVM_RESTRICTED_MEMis added and right now it is selected onX86_64only.
Quoted 6 lines
Quoted 2 lines
From the patch implementation, I have no idea why
HAVE_KVM_RESTRICTED_MEMis
needed.The reason is we want KVM further controls the feature enabling. An opt-in
CONFIG_RESTRICTEDMEMcan cause problem if user sets that for unsupported architectures.
HAVE_KVM_RESTRICTED_MEM is not used in this patch. It's better to introduce it in the patch that actually uses it.
Quoted 5 lines
Here is the original discussion:
https://lore.kernel.org/all/[email protected]/Thanks,
Chao
Re: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Quoted 13 lines · Xiaoyao Li
Quoted 12 lines · Chao Peng
Quoted 10 lines · Xiaoyao Li
On 12/2/2022 2:13 PM, Chao Peng wrote:
..
Quoted 3 lines
Together with the change, a new config
HAVE_KVM_RESTRICTED_MEMis added and right now it is selected onX86_64only.From the patch implementation, I have no idea why
HAVE_KVM_RESTRICTED_MEMis
needed.
Quoted 6 lines
Quoted 3 lines
The reason is we want KVM further controls the feature enabling. An opt-in
CONFIG_RESTRICTEDMEMcan cause problem if user sets that for unsupported architectures.
HAVE_KVM_RESTRICTED_MEMis not used in this patch. It's better to introduce it in the patch that actually uses it.
It's being 'used' in this patch by reverse selecting RESTRICTEDMEM in arch/x86/kvm/Kconfig, this gives people a sense where restrictedmem_notifier comes from. Introducing the config with other private/restricted memslot stuff together can also help future supporting architectures better identify what they need do. But those are trivial and moving to patch 08 sounds also good to me.
Thanks,
Chao
Quoted 6 lines
Quoted 6 lines
Here is the original discussion:
https://lore.kernel.org/all/[email protected]/Thanks,
Chao
Borislav Petkov
maintainerRe: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
In reply to Chao PengQuoted 3 lines · Chao Peng
In memory encryption usage, guest memory may be encrypted with special key and can be accessed only by the guest itself. We call such memory private memory. It's valueless and sometimes can cause problem to allow
valueless?
I can't parse that.
Quoted 4 lines
userspace to access guest private memory. This new KVM memslot extension allows guest private memory being provided through a restrictedmem backed file descriptor(fd) and userspace is restricted to access the bookmarked memory in the fd.
bookmarked?
Quoted 7 lines
This new extension, indicated by the new flag
KVM_MEM_PRIVATE, adds two additional KVM memslot fields restricted_fd/restricted_offset to allow userspace to instruct KVM to provide guest memory throughrestricted_fd. 'guest_phys_addr' is mapped at therestricted_offsetofrestricted_fdand the size is 'memory_size'.The extended memslot can still have the
userspace_addr(hva). When use, a
"When un use, ..."
...
arch/x86/kvm/Kconfig config KVM · line 54
Quoted 10 lines
arch/x86/kvm/Kconfig +2
-0@@ -50,6 +50,8 @@ config KVM select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM select HAVE_KVM_MEMORY_ATTRIBUTES + select HAVE_KVM_RESTRICTED_MEM if X86_64 + select RESTRICTEDMEM if HAVE_KVM_RESTRICTED_MEM
Those deps here look weird.
RESTRICTEDMEM should be selected by TDX_GUEST as it can't live without it.
Then you don't have to select HAVE_KVM_RESTRICTED_MEM simply because of X86_64 - you need that functionality when the respective guest support is enabled in KVM.
Then, looking forward into your patchset, I'm not sure you even need HAVE_KVM_RESTRICTED_MEM - you could make it all depend on CONFIG_RESTRICTEDMEM. But that's KVM folks call - I'd always aim for less Kconfig items because we have waay too many.
Thx.
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteRe: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Quoted 8 lines · Borislav Petkov
Quoted 3 lines · Chao Peng
In memory encryption usage, guest memory may be encrypted with special key and can be accessed only by the guest itself. We call such memory private memory. It's valueless and sometimes can cause problem to allow
valueless?
I can't parse that.
It's unnecessary and ...
Quoted 7 lines
Quoted 5 lines
userspace to access guest private memory. This new KVM memslot extension allows guest private memory being provided through a restrictedmem backed file descriptor(fd) and userspace is restricted to access the bookmarked memory in the fd.
bookmarked?
userspace is restricted to access the memory content in the fd.
Quoted 10 lines
Quoted 8 lines
This new extension, indicated by the new flag
KVM_MEM_PRIVATE, adds two additional KVM memslot fields restricted_fd/restricted_offset to allow userspace to instruct KVM to provide guest memory throughrestricted_fd. 'guest_phys_addr' is mapped at therestricted_offsetofrestricted_fdand the size is 'memory_size'.The extended memslot can still have the
userspace_addr(hva). When use, a"When un use, ..."
When both userspace_addr and restricted_fd/offset were used, ...
Quoted 16 lines
...
arch/x86/kvm/Kconfig config KVM · line 54
Quoted 10 lines
arch/x86/kvm/Kconfig +2
-0@@ -50,6 +50,8 @@ config KVM select INTERVAL_TREE select HAVE_KVM_PM_NOTIFIER if PM select HAVE_KVM_MEMORY_ATTRIBUTES + select HAVE_KVM_RESTRICTED_MEM if X86_64 + select RESTRICTEDMEM if HAVE_KVM_RESTRICTED_MEMThose deps here look weird.
Quoted 2 lines
RESTRICTEDMEM should be selected by
TDX_GUESTas it can't live without it.
RESTRICTEDMEM is needed by TDX_HOST, not TDX_GUEST.
Quoted 4 lines
Then you don't have to select
HAVE_KVM_RESTRICTED_MEMsimply because ofX86_64- you need that functionality when the respective guest support is enabled in KVM.
Letting the actual feature(e.g. TDX or pKVM) select it or add dependency sounds a viable and clearer solution. Sean, let me know your opinion.
Quoted 5 lines
Then, looking forward into your patchset, I'm not sure you even need
HAVE_KVM_RESTRICTED_MEM- you could make it all depend onCONFIG_RESTRICTEDMEM. But that's KVM folks call - I'd always aim for lessKconfigitems because we have waay too many.
The only reason to add another HAVE_KVM_RESTRICTED_MEM is some code only works for 64bit[*] and CONFIG_RESTRICTEDMEM is not sufficient to enforce that.
[*] https://lore.kernel.org/all/[email protected]/
Thanks,
Chao
Quoted 8 lines
Thx.
Signature · 4 lines
Regards/Gruss, Boris. https://people.kernel.org/tglx/notes-about-netiquette
Borislav Petkov
maintainerRe: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Quoted 1 line · Chao Peng
RESTRICTEDMEM is needed by
TDX_HOST, notTDX_GUEST.
Which basically means that RESTRICTEDMEM should simply depend on KVM. Because you can't know upfront whether KVM will run a TDX guest or a SNP guest and so on.
Which then means that RESTRICTEDMEM will practically end up always enabled in KVM HV configs.
Quoted 3 lines
The only reason to add another
HAVE_KVM_RESTRICTED_MEMis some code only works for 64bit[*] andCONFIG_RESTRICTEDMEMis not sufficient to enforce that.
This is what I mean with "we have too many Kconfig items". :-\
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteRe: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Quoted 9 lines · Borislav Petkov
Quoted 1 line · Chao Peng
RESTRICTEDMEM is needed by
TDX_HOST, notTDX_GUEST.Which basically means that RESTRICTEDMEM should simply depend on KVM. Because you can't know upfront whether KVM will run a TDX guest or a SNP guest and so on.
Which then means that RESTRICTEDMEM will practically end up always enabled in KVM HV configs.
That's right, CONFIG_RESTRICTEDMEM is always selected for supported KVM architectures (currently x86_64).
Quoted 6 lines
Quoted 4 lines
The only reason to add another
HAVE_KVM_RESTRICTED_MEMis some code only works for 64bit[*] andCONFIG_RESTRICTEDMEMis not sufficient to enforce that.This is what I mean with "we have too many
Kconfigitems". :-\
Yes I agree. One way to remove this is probably additionally checking CONFIG_64BIT instead.
Thanks,
Chao
Quoted 6 lines
Signature · 5 lines
-- Regards/Gruss, Boris. https://people.kernel.org/tglx/notes-about-netiquette
Re: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
In reply to Chao PengQuoted 23 lines · Chao Peng
In memory encryption usage, guest memory may be encrypted with special key and can be accessed only by the guest itself. We call such memory private memory. It's valueless and sometimes can cause problem to allow userspace to access guest private memory. This new KVM memslot extension allows guest private memory being provided through a restrictedmem backed file descriptor(fd) and userspace is restricted to access the bookmarked memory in the fd.
This new extension, indicated by the new flag
KVM_MEM_PRIVATE, adds two additional KVM memslot fields restricted_fd/restricted_offset to allow userspace to instruct KVM to provide guest memory throughrestricted_fd. 'guest_phys_addr' is mapped at therestricted_offsetofrestricted_fdand the size is 'memory_size'.The extended memslot can still have the
userspace_addr(hva). When use, a single memslot can maintain both private memory throughrestricted_fdand shared memory throughuserspace_addr. Whether the private or shared part is visible to guest is maintained by other KVM code.A
restrictedmem_notifierfield is also added to the memslot structure to allow the restricted_fd's backing store to notify KVM the memory change, KVM then can invalidate its page table entries or handle memory errors.
Quoted 6 lines
Together with the change, a new config
HAVE_KVM_RESTRICTED_MEMis added and right now it is selected onX86_64only.To make future maintenance easy, internally use a binary compatible alias struct
kvm_user_mem_regionto handle both the normal and the '_ext' variants.
Feels bit hacky IMHO, and more like a completely new feature than an extension.
Why not just add a new ioctl? The commit message does not address the most essential design here.
BR, Jarkko
Re: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Quoted 31 lines · Jarkko Sakkinen
Quoted 23 lines · Chao Peng
In memory encryption usage, guest memory may be encrypted with special key and can be accessed only by the guest itself. We call such memory private memory. It's valueless and sometimes can cause problem to allow userspace to access guest private memory. This new KVM memslot extension allows guest private memory being provided through a restrictedmem backed file descriptor(fd) and userspace is restricted to access the bookmarked memory in the fd.
This new extension, indicated by the new flag
KVM_MEM_PRIVATE, adds two additional KVM memslot fields restricted_fd/restricted_offset to allow userspace to instruct KVM to provide guest memory throughrestricted_fd. 'guest_phys_addr' is mapped at therestricted_offsetofrestricted_fdand the size is 'memory_size'.The extended memslot can still have the
userspace_addr(hva). When use, a single memslot can maintain both private memory throughrestricted_fdand shared memory throughuserspace_addr. Whether the private or shared part is visible to guest is maintained by other KVM code.A
restrictedmem_notifierfield is also added to the memslot structure to allow the restricted_fd's backing store to notify KVM the memory change, KVM then can invalidate its page table entries or handle memory errors.Quoted 6 lines
Together with the change, a new config
HAVE_KVM_RESTRICTED_MEMis added and right now it is selected onX86_64only.To make future maintenance easy, internally use a binary compatible alias struct
kvm_user_mem_regionto handle both the normal and the '_ext' variants.
Quoted 5 lines
Feels bit hacky IMHO, and more like a completely new feature than an extension.
Why not just add a new ioctl? The commit message does not address the most essential design here.
Yes, people can always choose to add a new ioctl for this kind of change and the balance point here is we want to also avoid 'too many ioctls' if the functionalities are similar. The '_ext' variant reuses all the existing fields in the 'normal' variant and most importantly KVM internally can reuse most of the code. I certainly can add some words in the commit message to explain this design choice.
Thanks,
Chao
Quoted 2 lines
BR, Jarkko
Sean Christopherson
maintainerRe: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Quoted 12 lines · Chao Peng
Quoted 10 lines · Jarkko Sakkinen
Quoted 3 lines · Chao Peng
To make future maintenance easy, internally use a binary compatible alias struct
kvm_user_mem_regionto handle both the normal and the '_ext' variants.Feels bit hacky IMHO, and more like a completely new feature than an extension.
Why not just add a new ioctl? The commit message does not address the most essential design here.
Quoted 6 lines
Yes, people can always choose to add a new ioctl for this kind of change and the balance point here is we want to also avoid 'too many ioctls' if the functionalities are similar. The '
_ext' variant reuses all the existing fields in the 'normal' variant and most importantly KVM internally can reuse most of the code. I certainly can add some words in the commit message to explain this design choice.
After seeing the userspace side of this, I agree with Jarkko; overloading KVM_SET_USER_MEMORY_REGION is a hack. E.g. the size validation ends up being bogus, and userspace ends up abusing unions or implementing kvm_user_mem_region itself.
It feels absolutely ridiculous, but I think the best option is to do:
#define KVM_SET_USER_MEMORY_REGION2 _IOW(KVMIO, 0x49, \
struct kvm_userspace_memory_region2)
/* for KVM_SET_USER_MEMORY_REGION2 */
struct kvm_user_mem_region2 {
__u32 slot;
__u32 flags;
__u64 guest_phys_addr;
__u64 memory_size;
__u64 userspace_addr;
__u64 restricted_offset;
__u32 restricted_fd;
__u32 pad1;
__u64 pad2[14];
}And it's consistent with other KVM ioctls(), e.g. KVM_SET_CPUID2.
Regarding the userspace side of things, please include Vishal's selftests in v11, it's impossible to properly review the uAPI changes without seeing the userspace side of things. I'm in the process of reviewing Vishal's v2[*], I'll try to massage it into a set of patches that you can incorporate into your series.
Re: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Quoted 20 lines · Sean Christopherson
Quoted 12 lines · Chao Peng
Quoted 10 lines · Jarkko Sakkinen
Quoted 3 lines · Chao Peng
To make future maintenance easy, internally use a binary compatible alias struct
kvm_user_mem_regionto handle both the normal and the '_ext' variants.Feels bit hacky IMHO, and more like a completely new feature than an extension.
Why not just add a new ioctl? The commit message does not address the most essential design here.
Quoted 6 lines
Yes, people can always choose to add a new ioctl for this kind of change and the balance point here is we want to also avoid 'too many ioctls' if the functionalities are similar. The '
_ext' variant reuses all the existing fields in the 'normal' variant and most importantly KVM internally can reuse most of the code. I certainly can add some words in the commit message to explain this design choice.
Quoted 4 lines
After seeing the userspace side of this, I agree with Jarkko; overloading
KVM_SET_USER_MEMORY_REGIONis a hack. E.g. the size validation ends up being bogus, and userspace ends up abusing unions or implementingkvm_user_mem_regionitself.
How is the size validation being bogus? I don't quite follow. Then we will use kvm_userspace_memory_region2 as the KVM internal alias, right? I see similar examples use different functions to handle different versions but it does look easier if we use alias for this function.
Quoted 5 lines
It feels absolutely ridiculous, but I think the best option is to do:
#define
KVM_SET_USER_MEMORY_REGION2_IOW(KVMIO,0x49, \
structkvm_userspace_memory_region2)
Just interesting, is 0x49 a safe number we can use?
Quoted 14 lines
/* for
KVM_SET_USER_MEMORY_REGION2*/struct kvm_user_mem_region2 { __u32 slot; __u32 flags; __u64 guest_phys_addr; __u64 memory_size; __u64 userspace_addr; __u64 restricted_offset; __u32 restricted_fd; __u32 pad1; __u64 pad2[14]; }
Quoted 1 line
And it's consistent with other KVM
ioctls(), e.g.KVM_SET_CPUID2.
Okay, agree from KVM userspace API perspective this is more consistent with similar existing examples. I see several of them.
I think we will also need a CAP_KVM_SET_USER_MEMORY_REGION2 for this new ioctl.
Quoted 5 lines
Regarding the userspace side of things, please include Vishal's selftests in v11, it's impossible to properly review the uAPI changes without seeing the userspace side of things. I'm in the process of reviewing Vishal's v2[*], I'll try to massage it into a set of patches that you can incorporate into your series.
Previously I included Vishal's selftests in the github repo, but not include them in this patch series. It's OK for me to incorporate them directly into this series and review together if Vishal is fine.
Chao
Quoted 2 lines
Re: [PATCH v10 3/9] KVM: Extend the memslot to support fd-based private memory
Quoted 10 lines · Chao Peng
Quoted 5 lines
Regarding the userspace side of things, please include Vishal's selftests in v11, it's impossible to properly review the uAPI changes without seeing the userspace side of things. I'm in the process of reviewing Vishal's v2[*], I'll try to massage it into a set of patches that you can incorporate into your series.
Previously I included Vishal's selftests in the github repo, but not include them in this patch series. It's OK for me to incorporate them directly into this series and review together if Vishal is fine.
Yeah, I am ok with incorporating selftest patches into this series and reviewing them together.
Regards,
Vishal
Quoted 3 lines
Chao
Quoted 2 lines