Skip to contentSkip to conversation

KVM: Add host swap event notifications for PV guest

PATCH Superseded Gleb Natapov 5 participants 88 messages Oct 4, 2010 – Oct 10, 2010

Subsystems (10)

v6 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

v6 cover KVM: Add host swap event notifications for PV guest

KVM virtualizes guest memory by means of shadow pages or HW assistance like NPT/EPT. Not all memory used by a guest is mapped into the guest address space or even present in a host memory at any given time. When vcpu tries to access memory page that is not mapped into the guest address space KVM is notified about it. KVM maps the page into the guest address space and resumes vcpu execution. If the page is swapped out from the host memory vcpu execution is suspended till the page is swapped into the memory again. This is inefficient since vcpu can do other work (run other task or serve interrupts) while page gets swapped in.

The patch series tries to mitigate this problem by introducing two mechanisms. The first one is used with non-PV guest and it works like
this: when vcpu tries to access swapped out page it is halted and requested page is swapped in by another thread. That way vcpu can still process interrupts while io is happening in parallel and, with any luck, interrupt will cause the guest to schedule another task on the vcpu, so it will have work to do instead of waiting for the page to be swapped in.

The second mechanism introduces PV notification about swapped page state to a guest (asynchronous page fault). Instead of halting vcpu upon access to swapped out page and hoping that some interrupt will cause reschedule we immediately inject asynchronous page fault to the vcpu. PV aware guest knows that upon receiving such exception it should schedule another task to run on the vcpu. Current task is put to sleep until another kind of asynchronous page fault is received that notifies the guest that page is now in the host memory, so task that waits for it can run again.

To measure performance benefits I use a simple benchmark program (below) that starts number of threads. Some of them do work (increment counter), others access huge array in random location trying to generate host page faults. The size of the array is smaller then guest memory bug bigger then host memory so we are guarantied that host will swap out part of the array.

I ran the benchmark on three setups: with current kvm.git (master), with my patch series + non-pv guest (nonpv) and with my patch series + pv guest (pv).

Each guest had 4 cpus and 2G memory and was launched inside 512M memory container. The command line was "./bm -f 4 -w 4 -t 60" (run 4 faulting threads and 4 working threads for a minute).

Below is the total amount of "work" each guest managed to do (average of 10 runs):
total work std error

master: 122789420615 (3818565029)
nonpv:  138455939001 (773774299)
pv:     234351846135 (10461117116)

Changes:
v1->v2
Use MSR instead of hypercall.
Move most of the code into arch independent place.
halt inside a guest instead of doing "wait for page" hypercall if
preemption is disabled.
v2->v3
Use MSR from range 0x4b564dxx.
Add slot version tracking.
Support migration by restarting all guest processes after migration. Drop patch that tract preemptability for non-preemptable kernels
due to performance concerns. Send async PF to non-preemptable guests only when vcpu is executing userspace code.
v3->v4
Provide alternative page fault handler in PV guest instead of adding hook to
standard page fault handler and patch it out on non-PV guests.
Allow only limited number of outstanding async page fault per vcpu. Unify gfn_to_pfn and gfn_to_pfn_async code.
Cancel outstanding slow work on reset.
v4->v5
Move async pv cpu initialization into cpu hotplug notifier.
Use GFP_NOWAIT instead of GFP_ATOMIC for allocation that shouldn't sleep Process KVM_REQ_MMU_SYNC even in page_fault_other_cr3() before changing
cr3 back
v5->v6
To many. Will list only major changes here.
Replace slow work with work queues.
Halt vcpu for non-pv guests.
Handle async PF in nested SVM mode.
Do not prefault swapped in page for non tdp case.

Gleb Natapov (12):
Add get_user_pages() variant that fails if major fault is required. Halt vcpu if page it tries to access is swapped out.
Retry fault before vmentry
Add memory slot versioning and use it to provide fast guest write interface Move kvm_smp_prepare_boot_cpu() from kvmclock.c to kvm.c.
Add PV MSR to enable asynchronous page faults delivery.
Add async PF initialization to PV guest.
Handle async PF in a guest.
Inject asynchronous page fault into a PV guest if page is swapped out. Handle async PF in non preemptable context
Let host know whether the guest can handle async PF in non-userspace context. Send async PF when guest is not in userspace too.

 Documentation/kernel-parameters.txt |    3 +
 Documentation/kvm/cpuid.txt         |    3 +
 Documentation/kvm/msr.txt           |   14 ++-
 arch/x86/include/asm/kvm_host.h     |   27 +++-
 arch/x86/include/asm/kvm_para.h     |   23 +++
 arch/x86/include/asm/traps.h        |    1 +
 arch/x86/kernel/entry_32.S          |   10 +
 arch/x86/kernel/entry_64.S          |    3 +
 arch/x86/kernel/kvm.c               |  316 +++++++++++++++++++++++++++++++++++
 arch/x86/kernel/kvmclock.c          |   13 +--
 arch/x86/kvm/Kconfig                |    1 +
 arch/x86/kvm/Makefile               |    1 +
 arch/x86/kvm/mmu.c                  |   60 ++++++-
 arch/x86/kvm/paging_tmpl.h          |    8 +-
 arch/x86/kvm/svm.c                  |   43 ++++-
 arch/x86/kvm/x86.c                  |  189 ++++++++++++++++++++-
 fs/ncpfs/mmap.c                     |    2 +
 include/linux/kvm.h                 |    1 +
 include/linux/kvm_host.h            |   38 ++++
 include/linux/kvm_types.h           |    7 +
 include/linux/mm.h                  |    5 +
 include/trace/events/kvm.h          |   93 ++++++++++
 mm/filemap.c                        |    3 +
 mm/memory.c                         |   31 +++-
 mm/shmem.c                          |    8 +-
 virt/kvm/Kconfig                    |    3 +
 virt/kvm/async_pf.c                 |  223 ++++++++++++++++++++++++
 virt/kvm/async_pf.h                 |   36 ++++
 virt/kvm/kvm_main.c                 |  114 +++++++++++--
 29 files changed, 1225 insertions(+), 54 deletions(-)
 create mode 100644 virt/kvm/async_pf.c
 create mode 100644 virt/kvm/async_pf.h

=== benchmark.c ===

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

#define FAULTING_THREADS 1
#define WORKING_THREADS 1
#define TIMEOUT 5
#define MEMORY 1024*1024*1024

pthread_barrier_t barrier;
volatile int stop;
size_t pages;

void *fault_thread(void* p)

{
	char *mem = p;

	pthread_barrier_wait(&barrier);

	while (!stop)
		mem[(random() % pages) << 12] = 10;

	pthread_barrier_wait(&barrier);

	return NULL;
}

void *work_thread(void* p)

{
	unsigned long *i = p;

	pthread_barrier_wait(&barrier);

	while (!stop)
		(*i)++;

	pthread_barrier_wait(&barrier);

	return NULL;
}

int main(int argc, char **argv)

{
	int ft = FAULTING_THREADS, wt = WORKING_THREADS;
	unsigned int timeout = TIMEOUT;
	size_t mem = MEMORY;
	void *buf;
	int i, opt, verbose = 0;
	pthread_t t;
	pthread_attr_t pattr;
	unsigned long *res, sum = 0;

	while((opt = getopt(argc, argv, "f:w:m:t:v")) != -1) {
		switch (opt) {
		case 'f':
			ft = atoi(optarg);
			break;
		case 'w':
			wt = atoi(optarg);
			break;
		case 'm':
			mem = atoi(optarg);
			break;
		case 't':
			timeout = atoi(optarg);
			break;
		case 'v':
			verbose++;
			break;
		default:
			fprintf(stderr, "Usage %s [-f num] [-w num] [-m byte] [-t secs]\n", argv[0]);
			exit(1);
		}
	}

	if (verbose)
		printf("fault=%d work=%d mem=%lu timeout=%d\n", ft, wt, mem, timeout);

	pages = mem >> 12;
	posix_memalign(&buf, 4096, pages << 12);
	res = malloc(sizeof (unsigned long) * wt);
	memset(res, 0, sizeof (unsigned long) * wt);

	pthread_attr_init(&pattr);
	pthread_barrier_init(&barrier, NULL, ft + wt + 1);

	for (i = 0; i < ft; i++) {
		pthread_create(&t, &pattr, fault_thread, buf);
		pthread_detach(t);
	}

	for (i = 0; i < wt; i++) {
		pthread_create(&t, &pattr, work_thread, &res[i]);
		pthread_detach(t);
	}

	/* prefault memory */
	memset(buf, 0, pages << 12);
	printf("start\n");

	pthread_barrier_wait(&barrier);

	pthread_barrier_destroy(&barrier);
	pthread_barrier_init(&barrier, NULL, ft + wt + 1);

	sleep(timeout);
	stop = 1;

	pthread_barrier_wait(&barrier);

	for (i = 0; i < wt; i++) {
		sum += res[i];
		printf("worker %d: %lu\n", i, res[i]);
	}
	printf("total: %lu\n", sum);

	return 0;
}

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#1 lore raw

PATCH v6 1/12 Add get_user_pages() variant that fails if major fault is required.

This patch add get_user_pages() variant that only succeeds if getting a reference to a page doesn't require major fault.

---
 fs/ncpfs/mmap.c    |    2 ++
 include/linux/mm.h |    5 +++++
 mm/filemap.c       |    3 +++
 mm/memory.c        |   31 ++++++++++++++++++++++++++++---
 mm/shmem.c         |    8 +++++++-
 5 files changed, 45 insertions(+), 4 deletions(-)
fs/ncpfs/mmap.c +2 -0
index 56f5b3a..b9c4f36 100644
@@ -39,6 +39,8 @@ static int ncp_file_mmap_fault(struct vm_area_struct *area,
 	int bufsize;
 	int pos; /* XXX: loff_t ? */
 
+	if (vmf->flags & FAULT_FLAG_MINOR)
+		return VM_FAULT_MAJOR | VM_FAULT_ERROR;
 	/*
 	 * ncpfs has nothing against high pages as long
 	 * as recvmsg and memset works on it
include/linux/mm.h +5 -0
index 74949fb..da32900 100644
@@ -144,6 +144,7 @@ extern pgprot_t protection_map[16];
 #define FAULT_FLAG_WRITE	0x01	/* Fault was a write access */
 #define FAULT_FLAG_NONLINEAR	0x02	/* Fault was via a nonlinear mapping */
 #define FAULT_FLAG_MKWRITE	0x04	/* Fault was mkwrite of existing pte */
+#define FAULT_FLAG_MINOR	0x08	/* Do only minor fault */
 
 /*
  * This interface is used by x86 PAT code to identify a pfn mapping that is
@@ -848,6 +849,9 @@ extern int access_process_vm(struct task_struct *tsk, unsigned long addr, void *
 int get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
 			unsigned long start, int nr_pages, int write, int force,
 			struct page **pages, struct vm_area_struct **vmas);
+int get_user_pages_noio(struct task_struct *tsk, struct mm_struct *mm,
+			unsigned long start, int nr_pages, int write, int force,
+			struct page **pages, struct vm_area_struct **vmas);
 int get_user_pages_fast(unsigned long start, int nr_pages, int write,
 			struct page **pages);
 struct page *get_dump_page(unsigned long addr);
@@ -1394,6 +1398,7 @@ struct page *follow_page(struct vm_area_struct *, unsigned long address,
 #define FOLL_GET	0x04	/* do get_page on page */
 #define FOLL_DUMP	0x08	/* give error on hole if it would be zero */
 #define FOLL_FORCE	0x10	/* get_user_pages read/write w/o permission */
+#define FOLL_MINOR	0x20	/* do only minor page faults */
 
 typedef int (*pte_fn_t)(pte_t *pte, pgtable_t token, unsigned long addr,
 			void *data);
mm/filemap.c +3 -0
index 3d4df44..ef28b6d 100644
@@ -1548,6 +1548,9 @@ int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
 			goto no_cached_page;
 		}
 	} else {
+		if (vmf->flags & FAULT_FLAG_MINOR)
+			return VM_FAULT_MAJOR | VM_FAULT_ERROR;
+
 		/* No page in the page cache at all */
 		do_sync_mmap_readahead(vma, ra, file, offset);
 		count_vm_event(PGMAJFAULT);
mm/memory.c +28 -3
index 0e18b4d..b221458 100644
@@ -1441,10 +1441,13 @@ int __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
 			cond_resched();
 			while (!(page = follow_page(vma, start, foll_flags))) {
 				int ret;
+				unsigned int fault_fl =
+					((foll_flags & FOLL_WRITE) ?
+					FAULT_FLAG_WRITE : 0) |
+					((foll_flags & FOLL_MINOR) ?
+					FAULT_FLAG_MINOR : 0);
 
-				ret = handle_mm_fault(mm, vma, start,
-					(foll_flags & FOLL_WRITE) ?
-					FAULT_FLAG_WRITE : 0);
+				ret = handle_mm_fault(mm, vma, start, fault_fl);
 
 				if (ret & VM_FAULT_ERROR) {
 					if (ret & VM_FAULT_OOM)
@@ -1452,6 +1455,8 @@ int __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
 					if (ret &
 					    (VM_FAULT_HWPOISON|VM_FAULT_SIGBUS))
 						return i ? i : -EFAULT;
+					else if (ret & VM_FAULT_MAJOR)
+						return i ? i : -EFAULT;
 					BUG();
 				}
 				if (ret & VM_FAULT_MAJOR)
@@ -1562,6 +1567,23 @@ int get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
 }
 EXPORT_SYMBOL(get_user_pages);
 
+int get_user_pages_noio(struct task_struct *tsk, struct mm_struct *mm,
+		unsigned long start, int nr_pages, int write, int force,
+		struct page **pages, struct vm_area_struct **vmas)
+{
+	int flags = FOLL_TOUCH | FOLL_MINOR;
+
+	if (pages)
+		flags |= FOLL_GET;
+	if (write)
+		flags |= FOLL_WRITE;
+	if (force)
+		flags |= FOLL_FORCE;
+
+	return __get_user_pages(tsk, mm, start, nr_pages, flags, pages, vmas);
+}
+EXPORT_SYMBOL(get_user_pages_noio);
+
 /**
  * get_dump_page() - pin user page in memory while writing it to core dump
  * @addr: user address
@@ -2648,6 +2670,9 @@ static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma,
 	delayacct_set_flag(DELAYACCT_PF_SWAPIN);
 	page = lookup_swap_cache(entry);
 	if (!page) {
+		if (flags & FAULT_FLAG_MINOR)
+			return VM_FAULT_MAJOR | VM_FAULT_ERROR;
+
 		grab_swap_token(mm); /* Contend for token _before_ read-in */
 		page = swapin_readahead(entry,
 					GFP_HIGHUSER_MOVABLE, vma, address);
mm/shmem.c +7 -1
index 080b09a..470d8a7 100644
@@ -1228,6 +1228,7 @@ static int shmem_getpage(struct inode *inode, unsigned long idx,
 	swp_entry_t swap;
 	gfp_t gfp;
 	int error;
+	int flags = type ? *type : 0;
 
 	if (idx >= SHMEM_MAX_INDEX)
 		return -EFBIG;
@@ -1287,6 +1288,11 @@ repeat:
 		swappage = lookup_swap_cache(swap);
 		if (!swappage) {
 			shmem_swp_unmap(entry);
+			if (flags & FAULT_FLAG_MINOR) {
+				spin_unlock(&info->lock);
+				*type = VM_FAULT_MAJOR | VM_FAULT_ERROR;
+				goto failed;
+			}
 			/* here we actually do the io */
 			if (type && !(*type & VM_FAULT_MAJOR)) {
 				__count_vm_event(PGMAJFAULT);
@@ -1510,7 +1516,7 @@ static int shmem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
 {
 	struct inode *inode = vma->vm_file->f_path.dentry->d_inode;
 	int error;
-	int ret;
+	int ret = (int)vmf->flags;
 
 	if (((loff_t)vmf->pgoff << PAGE_CACHE_SHIFT) >= i_size_read(inode))
 		return VM_FAULT_SIGBUS;
Signature · 7 lines
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#2 lore raw

PATCH v6 2/12 Halt vcpu if page it tries to access is swapped out.

In reply to Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

---
 arch/x86/include/asm/kvm_host.h |   17 +++
 arch/x86/kvm/Kconfig            |    1 +
 arch/x86/kvm/Makefile           |    1 +
 arch/x86/kvm/mmu.c              |   51 +++++++++-
 arch/x86/kvm/paging_tmpl.h      |    4 +-
 arch/x86/kvm/x86.c              |  109 +++++++++++++++++++-
 include/linux/kvm_host.h        |   31 ++++++
 include/trace/events/kvm.h      |   88 ++++++++++++++++
 virt/kvm/Kconfig                |    3 +
 virt/kvm/async_pf.c             |  220 +++++++++++++++++++++++++++++++++++++++
 virt/kvm/async_pf.h             |   36 +++++++
 virt/kvm/kvm_main.c             |   57 ++++++++--
 12 files changed, 603 insertions(+), 15 deletions(-)
 create mode 100644 virt/kvm/async_pf.c
 create mode 100644 virt/kvm/async_pf.h
arch/x86/include/asm/kvm_host.h +17 -0
index e209078..5f154d3 100644
@@ -83,6 +83,8 @@
 #define KVM_NR_FIXED_MTRR_REGION 88
 #define KVM_NR_VAR_MTRR 8
 
+#define ASYNC_PF_PER_VCPU 64
+
 extern spinlock_t kvm_lock;
 extern struct list_head vm_list;
 
@@ -412,6 +414,10 @@ struct kvm_vcpu_arch {
 	u64 hv_vapic;
 
 	cpumask_var_t wbinvd_dirty_mask;
+
+	struct {
+		gfn_t gfns[roundup_pow_of_two(ASYNC_PF_PER_VCPU)];
+	} apf;
 };
 
 struct kvm_arch {
@@ -585,7 +591,12 @@ struct kvm_x86_ops {
 	const struct trace_print_flags *exit_reasons_str;
 };
 
+struct kvm_arch_async_pf {
+	gfn_t gfn;
+};
+
 extern struct kvm_x86_ops *kvm_x86_ops;
+extern struct kvm_async_pf *kvm_double_apf;
 
 int kvm_mmu_module_init(void);
 void kvm_mmu_module_exit(void);
@@ -823,4 +834,10 @@ void kvm_set_shared_msr(unsigned index, u64 val, u64 mask);
 
 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip);
 
+void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
+				     struct kvm_async_pf *work);
+void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
+				 struct kvm_async_pf *work);
+extern bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn);
+
 #endif /* _ASM_X86_KVM_HOST_H */
arch/x86/kvm/Kconfig +1 -0
index ddc131f..50f6364 100644
@@ -28,6 +28,7 @@ config KVM
 	select HAVE_KVM_IRQCHIP
 	select HAVE_KVM_EVENTFD
 	select KVM_APIC_ARCHITECTURE
+	select KVM_ASYNC_PF
 	select USER_RETURN_NOTIFIER
 	select KVM_MMIO
 	---help---
arch/x86/kvm/Makefile +1 -0
index 31a7035..c53bf19 100644
@@ -9,6 +9,7 @@ kvm-y			+= $(addprefix ../../../virt/kvm/, kvm_main.o ioapic.o \
 				coalesced_mmio.o irq_comm.o eventfd.o \
 				assigned-dev.o)
 kvm-$(CONFIG_IOMMU_API)	+= $(addprefix ../../../virt/kvm/, iommu.o)
+kvm-$(CONFIG_KVM_ASYNC_PF)	+= $(addprefix ../../../virt/kvm/, async_pf.o)
 
 kvm-y			+= x86.o mmu.o emulate.o i8259.o irq.o lapic.o \
 			   i8254.o timer.o
arch/x86/kvm/mmu.c +50 -1

72 lines not on this page · raw message

arch/x86/kvm/paging_tmpl.h +3 -1
index 2bdd843..8154353 100644
@@ -573,7 +573,9 @@ static int FNAME(page_fault)(struct kvm_vcpu *vcpu, gva_t addr,
 
 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
 	smp_rmb();
-	pfn = gfn_to_pfn(vcpu->kvm, walker.gfn);
+
+	if (try_async_pf(vcpu, walker.gfn, addr, &pfn))
+		return 0;
 
 	/* mmio */
 	if (is_error_pfn(pfn))
arch/x86/kvm/x86.c +108 -1

176 lines not on this page · raw message

include/linux/kvm_host.h +31 -0
index 0b89d00..a08614e 100644
@@ -74,6 +74,26 @@ int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx,
 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
 			      struct kvm_io_device *dev);
 
+#ifdef CONFIG_KVM_ASYNC_PF
+struct kvm_async_pf {
+	struct work_struct work;
+	struct list_head link;
+	struct list_head queue;
+	struct kvm_vcpu *vcpu;
+	struct mm_struct *mm;
+	gva_t gva;
+	unsigned long addr;
+	struct kvm_arch_async_pf arch;
+	struct page *page;
+};
+
+void kvm_clear_async_pf_completion_queue(struct kvm_vcpu *vcpu);
+void kvm_check_async_pf_completion(struct kvm_vcpu *vcpu);
+int kvm_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
+		       struct kvm_arch_async_pf *arch);
+int kvm_async_pf_wakeup_all(struct kvm_vcpu *vcpu);
+#endif
+
 struct kvm_vcpu {
 	struct kvm *kvm;
 #ifdef CONFIG_PREEMPT_NOTIFIERS
@@ -104,6 +124,16 @@ struct kvm_vcpu {
 	gpa_t mmio_phys_addr;
 #endif
 
+#ifdef CONFIG_KVM_ASYNC_PF
+	struct {
+		u32 queued;
+		struct list_head queue;
+		struct list_head done;
+		spinlock_t lock;
+		struct kvm_async_pf *work;
+	} async_pf;
+#endif
+
 	struct kvm_vcpu_arch arch;
 };
 
@@ -302,6 +332,7 @@ void kvm_set_page_accessed(struct page *page);
 
 pfn_t hva_to_pfn_atomic(struct kvm *kvm, unsigned long addr);
 pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn);
+pfn_t gfn_to_pfn_async(struct kvm *kvm, gfn_t gfn, bool *async);
 pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn);
 pfn_t gfn_to_pfn_memslot(struct kvm *kvm,
 			 struct kvm_memory_slot *slot, gfn_t gfn);
include/trace/events/kvm.h +88 -0

94 lines not on this page · raw message

virt/kvm/Kconfig +3 -0
index 7f1178f..f63ccb0 100644
@@ -15,3 +15,6 @@ config KVM_APIC_ARCHITECTURE
 
 config KVM_MMIO
        bool
+
+config KVM_ASYNC_PF
+       bool
virt/kvm/async_pf.c new file +220 -0

220 lines not on this page · raw message

virt/kvm/async_pf.h new file +36 -0
new file mode 100644
index 0000000..fa15074
@@ -0,0 +1,36 @@
+/*
+ * kvm asynchromous fault support
+ *
+ * Copyright 2010 Red Hat, Inc.
+ *
+ * Author:
+ *      Gleb Natapov <[email protected]>
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of version 2 of the GNU General Public License
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef __KVM_ASYNC_PF_H__
+#define __KVM_ASYNC_PF_H__
+
+#ifdef CONFIG_KVM_ASYNC_PF
+int kvm_async_pf_init(void);
+void kvm_async_pf_deinit(void);
+void kvm_async_pf_vcpu_init(struct kvm_vcpu *vcpu);
+#else
+#define kvm_async_pf_init() (0)
+#define kvm_async_pf_deinit() do{}while(0)
+#define kvm_async_pf_vcpu_init(C) do{}while(0)
+#endif
+
+#endif
virt/kvm/kvm_main.c +45 -12

144 lines not on this page · raw message

Signature · 7 lines
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#23 lore raw

PATCH v6 3/12 Retry fault before vmentry

In reply to Gleb Natapov

When page is swapped in it is mapped into guest memory only after guest tries to access it again and generate another fault. To save this fault we can map it immediately since we know that guest is going to access the page. Do it only when tdp is enabled for now. Shadow paging case is more complicated. CR[034] and EFER registers should be switched before doing mapping and then switched back.

---
 arch/x86/include/asm/kvm_host.h |    4 +++-
 arch/x86/kvm/mmu.c              |   16 ++++++++--------
 arch/x86/kvm/paging_tmpl.h      |    6 +++---
 arch/x86/kvm/x86.c              |    7 +++++++
 virt/kvm/async_pf.c             |    2 ++
 5 files changed, 23 insertions(+), 12 deletions(-)
arch/x86/include/asm/kvm_host.h +3 -1
index 5f154d3..b9f263e 100644
@@ -240,7 +240,7 @@ struct kvm_mmu {
 	void (*new_cr3)(struct kvm_vcpu *vcpu);
 	void (*set_cr3)(struct kvm_vcpu *vcpu, unsigned long root);
 	unsigned long (*get_cr3)(struct kvm_vcpu *vcpu);
-	int (*page_fault)(struct kvm_vcpu *vcpu, gva_t gva, u32 err);
+	int (*page_fault)(struct kvm_vcpu *vcpu, gva_t gva, u32 err, bool no_apf);
 	void (*inject_page_fault)(struct kvm_vcpu *vcpu);
 	void (*free)(struct kvm_vcpu *vcpu);
 	gpa_t (*gva_to_gpa)(struct kvm_vcpu *vcpu, gva_t gva, u32 access,
@@ -838,6 +838,8 @@ void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
 				     struct kvm_async_pf *work);
 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
 				 struct kvm_async_pf *work);
+void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu,
+			       struct kvm_async_pf *work);
 extern bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn);
 
 #endif /* _ASM_X86_KVM_HOST_H */
arch/x86/kvm/mmu.c +8 -8
index 4d49b5e..d85fda8 100644
@@ -2558,7 +2558,7 @@ static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
 }
 
 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
-				u32 error_code)
+				u32 error_code, bool no_apf)
 {
 	gfn_t gfn;
 	int r;
@@ -2594,8 +2594,8 @@ static bool can_do_async_pf(struct kvm_vcpu *vcpu)
 	return kvm_x86_ops->interrupt_allowed(vcpu);
 }
 
-static bool try_async_pf(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
-			 pfn_t *pfn)
+static bool try_async_pf(struct kvm_vcpu *vcpu, bool no_apf, gfn_t gfn,
+			 gva_t gva, pfn_t *pfn)
 {
 	bool async;
 
@@ -2606,7 +2606,7 @@ static bool try_async_pf(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
 
 	put_page(pfn_to_page(*pfn));
 
-	if (can_do_async_pf(vcpu)) {
+	if (!no_apf && can_do_async_pf(vcpu)) {
 		trace_kvm_try_async_get_page(async, *pfn);
 		if (kvm_find_async_pf_gfn(vcpu, gfn)) {
 			vcpu->async_pf.work = kvm_double_apf;
@@ -2620,8 +2620,8 @@ static bool try_async_pf(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
 	return false;
 }
 
-static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa,
-				u32 error_code)
+static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
+			  bool no_apf)
 {
 	pfn_t pfn;
 	int r;
@@ -2643,7 +2643,7 @@ static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa,
 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
 	smp_rmb();
 
-	if (try_async_pf(vcpu, gfn, gpa, &pfn))
+	if (try_async_pf(vcpu, no_apf, gfn, gpa, &pfn))
 		return 0;
 
 	/* mmio */
@@ -3306,7 +3306,7 @@ int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code)
 	int r;
 	enum emulation_result er;
 
-	r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code);
+	r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code, false);
 	if (r < 0)
 		goto out;
 
arch/x86/kvm/paging_tmpl.h +3 -3
index 8154353..9ad90f8 100644
@@ -530,8 +530,8 @@ out_gpte_changed:
  *  Returns: 1 if we need to emulate the instruction, 0 otherwise, or
  *           a negative value on error.
  */
-static int FNAME(page_fault)(struct kvm_vcpu *vcpu, gva_t addr,
-			       u32 error_code)
+static int FNAME(page_fault)(struct kvm_vcpu *vcpu, gva_t addr, u32 error_code,
+			     bool no_apf)
 {
 	int write_fault = error_code & PFERR_WRITE_MASK;
 	int user_fault = error_code & PFERR_USER_MASK;
@@ -574,7 +574,7 @@ static int FNAME(page_fault)(struct kvm_vcpu *vcpu, gva_t addr,
 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
 	smp_rmb();
 
-	if (try_async_pf(vcpu, walker.gfn, addr, &pfn))
+	if (try_async_pf(vcpu, no_apf, walker.gfn, addr, &pfn))
 		return 0;
 
 	/* mmio */
arch/x86/kvm/x86.c +7 -0
index 8dd9ac2..48fd59d 100644
@@ -6123,6 +6123,13 @@ void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
 }
 EXPORT_SYMBOL_GPL(kvm_set_rflags);
 
+void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
+{
+	if (!tdp_enabled || is_error_page(work->page))
+		return;
+	vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
+}
+
 static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
 {
 	return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
virt/kvm/async_pf.c +2 -0
index f5109eb..44f4005 100644
@@ -133,6 +133,7 @@ void kvm_check_async_pf_completion(struct kvm_vcpu *vcpu)
 			spin_lock(&vcpu->async_pf.lock);
 			list_del(&work->link);
 			spin_unlock(&vcpu->async_pf.lock);
+			kvm_arch_async_page_ready(vcpu, work);
 			goto free;
 		}
 	}
@@ -145,6 +146,7 @@ void kvm_check_async_pf_completion(struct kvm_vcpu *vcpu)
 	list_del(&work->link);
 	spin_unlock(&vcpu->async_pf.lock);
 
+	kvm_arch_async_page_ready(vcpu, work);
 	kvm_arch_async_page_present(vcpu, work);
 
 free:
Signature · 7 lines
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#33 lore raw

PATCH v6 4/12 Add memory slot versioning and use it to provide fast guest write interface

In reply to Gleb Natapov

Keep track of memslots changes by keeping generation number in memslots structure. Provide kvm_write_guest_cached() function that skips gfn_to_hva() translation if memslots was not changed since previous invocation.

---
 include/linux/kvm_host.h  |    7 +++++
 include/linux/kvm_types.h |    7 +++++
 virt/kvm/kvm_main.c       |   57 +++++++++++++++++++++++++++++++++++++++++---
 3 files changed, 67 insertions(+), 4 deletions(-)
include/linux/kvm_host.h +7 -0
index a08614e..4dff9a1 100644
@@ -199,6 +199,7 @@ struct kvm_irq_routing_table {};
 
 struct kvm_memslots {
 	int nmemslots;
+	u32 generation;
 	struct kvm_memory_slot memslots[KVM_MEMORY_SLOTS +
 					KVM_PRIVATE_MEM_SLOTS];
 };
@@ -352,12 +353,18 @@ int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
 			 int offset, int len);
 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
 		    unsigned long len);
+int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
+			   void *data, unsigned long len);
+int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
+			      gpa_t gpa);
 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len);
 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len);
 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn);
 int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn);
 unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn);
 void mark_page_dirty(struct kvm *kvm, gfn_t gfn);
+void mark_page_dirty_in_slot(struct kvm *kvm, struct kvm_memory_slot *memslot,
+			     gfn_t gfn);
 
 void kvm_vcpu_block(struct kvm_vcpu *vcpu);
 void kvm_vcpu_on_spin(struct kvm_vcpu *vcpu);
include/linux/kvm_types.h +7 -0
index 7ac0d4e..ee6eb71 100644
@@ -67,4 +67,11 @@ struct kvm_lapic_irq {
 	u32 dest_id;
 };
 
+struct gfn_to_hva_cache {
+	u32 generation;
+	gpa_t gpa;
+	unsigned long hva;
+	struct kvm_memory_slot *memslot;
+};
+
 #endif /* __KVM_TYPES_H__ */
virt/kvm/kvm_main.c +53 -4

88 lines not on this page · raw message

Signature · 7 lines
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#46 lore raw

PATCH v6 5/12 Move kvm_smp_prepare_boot_cpu() from kvmclock.c to kvm.c.

In reply to Gleb Natapov

Async PF also needs to hook into smp_prepare_boot_cpu so move the hook into generic code.

---
 arch/x86/include/asm/kvm_para.h |    1 +
 arch/x86/kernel/kvm.c           |   11 +++++++++++
 arch/x86/kernel/kvmclock.c      |   13 +------------
 3 files changed, 13 insertions(+), 12 deletions(-)
arch/x86/include/asm/kvm_para.h +1 -0
index 7b562b6..e3faaaf 100644
@@ -65,6 +65,7 @@ struct kvm_mmu_op_release_pt {
 #include <asm/processor.h>
 
 extern void kvmclock_init(void);
+extern int kvm_register_clock(char *txt);
 
 
 /* This instruction is vmcall.  On non-VT architectures, it will generate a
arch/x86/kernel/kvm.c +11 -0
index 63b0ec8..e6db179 100644
@@ -231,10 +231,21 @@ static void __init paravirt_ops_setup(void)
 #endif
 }
 
+#ifdef CONFIG_SMP
+static void __init kvm_smp_prepare_boot_cpu(void)
+{
+	WARN_ON(kvm_register_clock("primary cpu clock"));
+	native_smp_prepare_boot_cpu();
+}
+#endif
+
 void __init kvm_guest_init(void)
 {
 	if (!kvm_para_available())
 		return;
 
 	paravirt_ops_setup();
+#ifdef CONFIG_SMP
+	smp_ops.smp_prepare_boot_cpu = kvm_smp_prepare_boot_cpu;
+#endif
 }
arch/x86/kernel/kvmclock.c +1 -12
index ca43ce3..f98d3ea 100644
@@ -125,7 +125,7 @@ static struct clocksource kvm_clock = {
 	.flags = CLOCK_SOURCE_IS_CONTINUOUS,
 };
 
-static int kvm_register_clock(char *txt)
+int kvm_register_clock(char *txt)
 {
 	int cpu = smp_processor_id();
 	int low, high, ret;
@@ -152,14 +152,6 @@ static void __cpuinit kvm_setup_secondary_clock(void)
 }
 #endif
 
-#ifdef CONFIG_SMP
-static void __init kvm_smp_prepare_boot_cpu(void)
-{
-	WARN_ON(kvm_register_clock("primary cpu clock"));
-	native_smp_prepare_boot_cpu();
-}
-#endif
-
 /*
  * After the clock is registered, the host will keep writing to the
  * registered memory location. If the guest happens to shutdown, this memory
@@ -206,9 +198,6 @@ void __init kvmclock_init(void)
 	x86_cpuinit.setup_percpu_clockev =
 		kvm_setup_secondary_clock;
 #endif
-#ifdef CONFIG_SMP
-	smp_ops.smp_prepare_boot_cpu = kvm_smp_prepare_boot_cpu;
-#endif
 	machine_ops.shutdown  = kvm_shutdown;
 #ifdef CONFIG_KEXEC
 	machine_ops.crash_shutdown  = kvm_crash_shutdown;
Signature · 7 lines
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#47 lore raw

PATCH v6 6/12 Add PV MSR to enable asynchronous page faults delivery.

In reply to Gleb Natapov

Guest enables async PF vcpu functionality using this MSR.

---
 Documentation/kvm/cpuid.txt     |    3 +++
 Documentation/kvm/msr.txt       |   13 ++++++++++++-
 arch/x86/include/asm/kvm_host.h |    2 ++
 arch/x86/include/asm/kvm_para.h |    4 ++++
 arch/x86/kvm/x86.c              |   38 ++++++++++++++++++++++++++++++++++++--
 include/linux/kvm.h             |    1 +
 6 files changed, 58 insertions(+), 3 deletions(-)
Documentation/kvm/cpuid.txt +3 -0
index 14a12ea..8820685 100644
@@ -36,6 +36,9 @@ KVM_FEATURE_MMU_OP                 ||     2 || deprecated.
 KVM_FEATURE_CLOCKSOURCE2           ||     3 || kvmclock available at msrs
                                    ||       || 0x4b564d00 and 0x4b564d01
 ------------------------------------------------------------------------------
+KVM_FEATURE_ASYNC_PF               ||     4 || async pf can be enabled by
+                                   ||       || writing to msr 0x4b564d02
+------------------------------------------------------------------------------
 KVM_FEATURE_CLOCKSOURCE_STABLE_BIT ||    24 || host will warn if no guest-side
                                    ||       || per-cpu warps are expected in
                                    ||       || kvmclock.
Documentation/kvm/msr.txt +12 -1
index 8ddcfe8..d64e723 100644
@@ -3,7 +3,6 @@ Glauber Costa <[email protected]>, Red Hat Inc, 2010
 =====================================================
 
 KVM makes use of some custom MSRs to service some requests.
-At present, this facility is only used by kvmclock.
 
 Custom MSRs have a range reserved for them, that goes from
 0x4b564d00 to 0x4b564dff. There are MSRs outside this area,
@@ -151,3 +150,15 @@ MSR_KVM_SYSTEM_TIME: 0x12
 			return PRESENT;
 		} else
 			return NON_PRESENT;
+
+MSR_KVM_ASYNC_PF_EN: 0x4b564d02
+	data: Bits 63-6 hold 64-byte aligned physical address of a 32bit memory
+	area which must be in guest RAM. Bits 5-1 are reserved and should be
+	zero. Bit 0 is 1 when asynchronous page faults are enabled on the vcpu
+	0 when disabled.
+
+	Physical address points to 32 bit memory location that will be written
+	to by the hypervisor at the time of asynchronous page fault injection to
+	indicate type of asynchronous page fault. Value of 1 means that the page
+	referred to by the page fault is not present. Value 2 means that the
+	page is now available.
arch/x86/include/asm/kvm_host.h +2 -0
index b9f263e..de31551 100644
@@ -417,6 +417,8 @@ struct kvm_vcpu_arch {
 
 	struct {
 		gfn_t gfns[roundup_pow_of_two(ASYNC_PF_PER_VCPU)];
+		struct gfn_to_hva_cache data;
+		u64 msr_val;
 	} apf;
 };
 
arch/x86/include/asm/kvm_para.h +4 -0
index e3faaaf..8662ae0 100644
@@ -20,6 +20,7 @@
  * are available. The use of 0x11 and 0x12 is deprecated
  */
 #define KVM_FEATURE_CLOCKSOURCE2        3
+#define KVM_FEATURE_ASYNC_PF		4
 
 /* The last 8 bits are used to indicate how to interpret the flags field
  * in pvclock structure. If no bits are set, all flags are ignored.
@@ -32,9 +33,12 @@
 /* Custom MSRs falls in the range 0x4b564d00-0x4b564dff */
 #define MSR_KVM_WALL_CLOCK_NEW  0x4b564d00
 #define MSR_KVM_SYSTEM_TIME_NEW 0x4b564d01
+#define MSR_KVM_ASYNC_PF_EN 0x4b564d02
 
 #define KVM_MAX_MMU_OP_BATCH           32
 
+#define KVM_ASYNC_PF_ENABLED			(1 << 0)
+
 /* Operations for KVM_HC_MMU_OP */
 #define KVM_MMU_OP_WRITE_PTE            1
 #define KVM_MMU_OP_FLUSH_TLB	        2
arch/x86/kvm/x86.c +36 -2
index 48fd59d..3e123ab 100644
@@ -782,12 +782,12 @@ EXPORT_SYMBOL_GPL(kvm_get_dr);
  * kvm-specific. Those are put in the beginning of the list.
  */
 
-#define KVM_SAVE_MSRS_BEGIN	7
+#define KVM_SAVE_MSRS_BEGIN	8
 static u32 msrs_to_save[] = {
 	MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
 	MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
 	HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
-	HV_X64_MSR_APIC_ASSIST_PAGE,
+	HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN,
 	MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
 	MSR_STAR,
 #ifdef CONFIG_X86_64
@@ -1425,6 +1425,29 @@ static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
 	return 0;
 }
 
+static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
+{
+	gpa_t gpa = data & ~0x3f;
+
+	/* Bits 1:5 are resrved, Should be zero */
+	if (data & 0x3e)
+		return 1;
+
+	vcpu->arch.apf.msr_val = data;
+
+	if (!(data & KVM_ASYNC_PF_ENABLED)) {
+		kvm_clear_async_pf_completion_queue(vcpu);
+		memset(vcpu->arch.apf.gfns, 0xff, sizeof vcpu->arch.apf.gfns);
+		return 0;
+	}
+
+	if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa))
+		return 1;
+
+	kvm_async_pf_wakeup_all(vcpu);
+	return 0;
+}
+
 int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
 {
 	switch (msr) {
@@ -1506,6 +1529,10 @@ int kvm_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data)
 		}
 		break;
 	}
+	case MSR_KVM_ASYNC_PF_EN:
+		if (kvm_pv_enable_async_pf(vcpu, data))
+			return 1;
+		break;
 	case MSR_IA32_MCG_CTL:
 	case MSR_IA32_MCG_STATUS:
 	case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
@@ -1782,6 +1809,9 @@ int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
 	case MSR_KVM_SYSTEM_TIME_NEW:
 		data = vcpu->arch.time;
 		break;
+	case MSR_KVM_ASYNC_PF_EN:
+		data = vcpu->arch.apf.msr_val;
+		break;
 	case MSR_IA32_P5_MC_ADDR:
 	case MSR_IA32_P5_MC_TYPE:
 	case MSR_IA32_MCG_CAP:
@@ -1929,6 +1959,7 @@ int kvm_dev_ioctl_check_extension(long ext)
 	case KVM_CAP_DEBUGREGS:
 	case KVM_CAP_X86_ROBUST_SINGLESTEP:
 	case KVM_CAP_XSAVE:
+	case KVM_CAP_ASYNC_PF:
 		r = 1;
 		break;
 	case KVM_CAP_COALESCED_MMIO:
@@ -5778,6 +5809,8 @@ free_vcpu:
 
 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
 {
+	vcpu->arch.apf.msr_val = 0;
+
 	vcpu_load(vcpu);
 	kvm_mmu_unload(vcpu);
 	vcpu_put(vcpu);
@@ -5797,6 +5830,7 @@ int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
 	vcpu->arch.dr7 = DR7_FIXED_1;
 
 	kvm_make_request(KVM_REQ_EVENT, vcpu);
+	vcpu->arch.apf.msr_val = 0;
 
 	kvm_clear_async_pf_completion_queue(vcpu);
 	memset(vcpu->arch.apf.gfns, 0xff, sizeof vcpu->arch.apf.gfns);
include/linux/kvm.h +1 -0
index 919ae53..ea2dc1a 100644
@@ -540,6 +540,7 @@ struct kvm_ppc_pvinfo {
 #endif
 #define KVM_CAP_PPC_GET_PVINFO 57
 #define KVM_CAP_PPC_IRQ_LEVEL 58
+#define KVM_CAP_ASYNC_PF 59
 
 #ifdef KVM_CAP_IRQ_ROUTING
 
Signature · 7 lines
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#55 lore raw

PATCH v6 7/12 Add async PF initialization to PV guest.

In reply to Gleb Natapov

Enable async PF in a guest if async PF capability is discovered.

---
 Documentation/kernel-parameters.txt |    3 +
 arch/x86/include/asm/kvm_para.h     |    5 ++
 arch/x86/kernel/kvm.c               |   92 +++++++++++++++++++++++++++++++++++
 3 files changed, 100 insertions(+), 0 deletions(-)
Documentation/kernel-parameters.txt +3 -0
index 8dc2548..0bd2203 100644
@@ -1699,6 +1699,9 @@ and is between 256 and 4096 characters. It is defined in the file
 
 	no-kvmclock	[X86,KVM] Disable paravirtualized KVM clock driver
 
+	no-kvmapf	[X86,KVM] Disable paravirtualized asynchronous page
+			fault handling.
+
 	nolapic		[X86-32,APIC] Do not enable or use the local APIC.
 
 	nolapic_timer	[X86-32,APIC] Do not use the local APIC timer.
arch/x86/include/asm/kvm_para.h +5 -0
index 8662ae0..e193c4f 100644
@@ -65,6 +65,11 @@ struct kvm_mmu_op_release_pt {
 	__u64 pt_phys;
 };
 
+struct kvm_vcpu_pv_apf_data {
+	__u32 reason;
+	__u32 enabled;
+};
+
 #ifdef __KERNEL__
 #include <asm/processor.h>
 
arch/x86/kernel/kvm.c +92 -0

127 lines not on this page · raw message

Signature · 7 lines
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#64 lore raw

PATCH v6 8/12 Handle async PF in a guest.

In reply to Gleb Natapov

When async PF capability is detected hook up special page fault handler that will handle async page fault events and bypass other page faults to regular page fault handler. Also add async PF handling to nested SVM emulation. Async PF always generates exit to L1 where vcpu thread will be scheduled out until page is available.

---
 arch/x86/include/asm/kvm_para.h |   12 +++
 arch/x86/include/asm/traps.h    |    1 +
 arch/x86/kernel/entry_32.S      |   10 ++
 arch/x86/kernel/entry_64.S      |    3 +
 arch/x86/kernel/kvm.c           |  184 ++++++++++++++++++++++++++++++++++++++-
 arch/x86/kvm/svm.c              |   43 +++++++--
 6 files changed, 243 insertions(+), 10 deletions(-)
arch/x86/include/asm/kvm_para.h +12 -0
index e193c4f..bcc5022 100644
@@ -65,6 +65,9 @@ struct kvm_mmu_op_release_pt {
 	__u64 pt_phys;
 };
 
+#define KVM_PV_REASON_PAGE_NOT_PRESENT 1
+#define KVM_PV_REASON_PAGE_READY 2
+
 struct kvm_vcpu_pv_apf_data {
 	__u32 reason;
 	__u32 enabled;
@@ -170,8 +173,17 @@ static inline unsigned int kvm_arch_para_features(void)
 
 #ifdef CONFIG_KVM_GUEST
 void __init kvm_guest_init(void);
+void kvm_async_pf_task_wait(u32 token);
+void kvm_async_pf_task_wake(u32 token);
+u32 kvm_read_and_reset_pf_reason(void);
 #else
 #define kvm_guest_init() do { } while (0)
+#define kvm_async_pf_task_wait(T) do {} while(0)
+#define kvm_async_pf_task_wake(T) do {} while(0)
+static u32 kvm_read_and_reset_pf_reason(void)
+{
+	return 0;
+}
 #endif
 
 #endif /* __KERNEL__ */
arch/x86/include/asm/traps.h +1 -0
index f66cda5..0310da6 100644
@@ -30,6 +30,7 @@ asmlinkage void segment_not_present(void);
 asmlinkage void stack_segment(void);
 asmlinkage void general_protection(void);
 asmlinkage void page_fault(void);
+asmlinkage void async_page_fault(void);
 asmlinkage void spurious_interrupt_bug(void);
 asmlinkage void coprocessor_error(void);
 asmlinkage void alignment_check(void);
arch/x86/kernel/entry_32.S +10 -0
index 227d009..e6e7273 100644
@@ -1496,6 +1496,16 @@ ENTRY(general_protection)
 	CFI_ENDPROC
 END(general_protection)
 
+#ifdef CONFIG_KVM_GUEST
+ENTRY(async_page_fault)
+	RING0_EC_FRAME
+	pushl $do_async_page_fault
+	CFI_ADJUST_CFA_OFFSET 4
+	jmp error_code
+	CFI_ENDPROC
+END(apf_page_fault)
+#endif
+
 /*
  * End of kprobes section
  */
arch/x86/kernel/entry_64.S +3 -0
index 17be5ec..def98c3 100644
@@ -1349,6 +1349,9 @@ errorentry xen_stack_segment do_stack_segment
 #endif
 errorentry general_protection do_general_protection
 errorentry page_fault do_page_fault
+#ifdef CONFIG_KVM_GUEST
+errorentry async_page_fault do_async_page_fault
+#endif
 #ifdef CONFIG_X86_MCE
 paranoidzeroentry machine_check *machine_check_vector(%rip)
 #endif
arch/x86/kernel/kvm.c +183 -1

218 lines not on this page · raw message

arch/x86/kvm/svm.c +34 -9

82 lines not on this page · raw message

Signature · 7 lines
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#76 lore raw

PATCH v6 9/12 Inject asynchronous page fault into a PV guest if page is swapped out.

In reply to Gleb Natapov

Send async page fault to a PV guest if it accesses swapped out memory. Guest will choose another task to run upon receiving the fault.

Allow async page fault injection only when guest is in user mode since otherwise guest may be in non-sleepable context and will not be able to reschedule.

Vcpu will be halted if guest will fault on the same page again or if vcpu executes kernel code.

---
 arch/x86/include/asm/kvm_host.h |    3 ++
 arch/x86/kvm/mmu.c              |    1 +
 arch/x86/kvm/x86.c              |   49 ++++++++++++++++++++++++++++++++------
 include/trace/events/kvm.h      |   17 ++++++++----
 virt/kvm/async_pf.c             |    3 +-
 5 files changed, 58 insertions(+), 15 deletions(-)
arch/x86/include/asm/kvm_host.h +3 -0
index de31551..2f6fc87 100644
@@ -419,6 +419,7 @@ struct kvm_vcpu_arch {
 		gfn_t gfns[roundup_pow_of_two(ASYNC_PF_PER_VCPU)];
 		struct gfn_to_hva_cache data;
 		u64 msr_val;
+		u32 id;
 	} apf;
 };
 
@@ -594,6 +595,7 @@ struct kvm_x86_ops {
 };
 
 struct kvm_arch_async_pf {
+	u32 token;
 	gfn_t gfn;
 };
 
@@ -842,6 +844,7 @@ void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
 				 struct kvm_async_pf *work);
 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu,
 			       struct kvm_async_pf *work);
+bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu);
 extern bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn);
 
 #endif /* _ASM_X86_KVM_HOST_H */
arch/x86/kvm/mmu.c +1 -0
index d85fda8..de53cab 100644
@@ -2580,6 +2580,7 @@ static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
 int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
 {
 	struct kvm_arch_async_pf arch;
+	arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
 	arch.gfn = gfn;
 
 	return kvm_setup_async_pf(vcpu, gva, gfn, &arch);
arch/x86/kvm/x86.c +41 -8

66 lines not on this page · raw message

include/trace/events/kvm.h +11 -6
index bcc69b2..dd44aa3 100644
@@ -204,34 +204,39 @@ TRACE_EVENT(
 
 TRACE_EVENT(
 	kvm_async_pf_not_present,
-	TP_PROTO(u64 gva),
-	TP_ARGS(gva),
+	TP_PROTO(u64 token, u64 gva),
+	TP_ARGS(token, gva),
 
 	TP_STRUCT__entry(
+		__field(__u64, token)
 		__field(__u64, gva)
 		),
 
 	TP_fast_assign(
+		__entry->token = token;
 		__entry->gva = gva;
 		),
 
-	TP_printk("gva %#llx not present", __entry->gva)
+	TP_printk("token %#llx gva %#llx not present", __entry->token,
+		  __entry->gva)
 );
 
 TRACE_EVENT(
 	kvm_async_pf_ready,
-	TP_PROTO(u64 gva),
-	TP_ARGS(gva),
+	TP_PROTO(u64 token, u64 gva),
+	TP_ARGS(token, gva),
 
 	TP_STRUCT__entry(
+		__field(__u64, token)
 		__field(__u64, gva)
 		),
 
 	TP_fast_assign(
+		__entry->token = token;
 		__entry->gva = gva;
 		),
 
-	TP_printk("gva %#llx ready", __entry->gva)
+	TP_printk("token %#llx gva %#llx ready", __entry->token, __entry->gva)
 );
 
 TRACE_EVENT(
virt/kvm/async_pf.c +2 -1
index 44f4005..d1cd495 100644
@@ -138,7 +138,8 @@ void kvm_check_async_pf_completion(struct kvm_vcpu *vcpu)
 		}
 	}
 
-	if (list_empty_careful(&vcpu->async_pf.done))
+	if (list_empty_careful(&vcpu->async_pf.done) ||
+	    !kvm_arch_can_inject_async_page_present(vcpu))
 		return;
 
 	spin_lock(&vcpu->async_pf.lock);
Signature · 7 lines
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#80 lore raw

PATCH v6 10/12 Handle async PF in non preemptable context

In reply to Gleb Natapov

If async page fault is received by idle task or when preemp_count is not zero guest cannot reschedule, so do sti; hlt and wait for page to be ready. vcpu can still process interrupts while it waits for the page to be ready.

---
 arch/x86/kernel/kvm.c |   40 ++++++++++++++++++++++++++++++++++------
 1 files changed, 34 insertions(+), 6 deletions(-)
arch/x86/kernel/kvm.c +34 -6
index 36fb3e4..f73946f 100644
@@ -37,6 +37,7 @@
 #include <asm/cpu.h>
 #include <asm/traps.h>
 #include <asm/desc.h>
+#include <asm/tlbflush.h>
 
 #define MMU_QUEUE_SIZE 1024
 
@@ -78,6 +79,8 @@ struct kvm_task_sleep_node {
 	wait_queue_head_t wq;
 	u32 token;
 	int cpu;
+	bool halted;
+	struct mm_struct *mm;
 };
 
 static struct kvm_task_sleep_head {
@@ -106,6 +109,11 @@ void kvm_async_pf_task_wait(u32 token)
 	struct kvm_task_sleep_head *b = &async_pf_sleepers[key];
 	struct kvm_task_sleep_node n, *e;
 	DEFINE_WAIT(wait);
+	int cpu, idle;
+
+	cpu = get_cpu();
+	idle = idle_cpu(cpu);
+	put_cpu();
 
 	spin_lock(&b->lock);
 	e = _find_apf_task(b, token);
@@ -119,19 +127,33 @@ void kvm_async_pf_task_wait(u32 token)
 
 	n.token = token;
 	n.cpu = smp_processor_id();
+	n.mm = current->active_mm;
+	n.halted = idle || preempt_count() > 1;
+	atomic_inc(&n.mm->mm_count);
 	init_waitqueue_head(&n.wq);
 	hlist_add_head(&n.link, &b->list);
 	spin_unlock(&b->lock);
 
 	for (;;) {
-		prepare_to_wait(&n.wq, &wait, TASK_UNINTERRUPTIBLE);
+		if (!n.halted)
+			prepare_to_wait(&n.wq, &wait, TASK_UNINTERRUPTIBLE);
 		if (hlist_unhashed(&n.link))
 			break;
-		local_irq_enable();
-		schedule();
-		local_irq_disable();
+
+		if (!n.halted) {
+			local_irq_enable();
+			schedule();
+			local_irq_disable();
+		} else {
+			/*
+			 * We cannot reschedule. So halt.
+			 */
+			native_safe_halt();
+			local_irq_disable();
+		}
 	}
-	finish_wait(&n.wq, &wait);
+	if (!n.halted)
+		finish_wait(&n.wq, &wait);
 
 	return;
 }
@@ -140,7 +162,12 @@ EXPORT_SYMBOL_GPL(kvm_async_pf_task_wait);
 static void apf_task_wake_one(struct kvm_task_sleep_node *n)
 {
 	hlist_del_init(&n->link);
-	if (waitqueue_active(&n->wq))
+	if (!n->mm)
+		return;
+	mmdrop(n->mm);
+	if (n->halted)
+		smp_send_reschedule(n->cpu);
+	else if (waitqueue_active(&n->wq))
 		wake_up(&n->wq);
 }
 
@@ -193,6 +220,7 @@ again:
 		}
 		n->token = token;
 		n->cpu = smp_processor_id();
+		n->mm = NULL;
 		init_waitqueue_head(&n->wq);
 		hlist_add_head(&n->link, &b->list);
 	} else
Signature · 7 lines
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#84 lore raw

PATCH v6 11/12 Let host know whether the guest can handle async PF in non-userspace context.

In reply to Gleb Natapov

If guest can detect that it runs in non-preemptable context it can handle async PFs at any time, so let host know that it can send async PF even if guest cpu is not in userspace.

---
 Documentation/kvm/msr.txt       |    5 +++--
 arch/x86/include/asm/kvm_host.h |    1 +
 arch/x86/include/asm/kvm_para.h |    1 +
 arch/x86/kernel/kvm.c           |    3 +++
 arch/x86/kvm/x86.c              |    5 +++--
 5 files changed, 11 insertions(+), 4 deletions(-)
Documentation/kvm/msr.txt +3 -2
index d64e723..918f9ad 100644
@@ -153,9 +153,10 @@ MSR_KVM_SYSTEM_TIME: 0x12
 
 MSR_KVM_ASYNC_PF_EN: 0x4b564d02
 	data: Bits 63-6 hold 64-byte aligned physical address of a 32bit memory
-	area which must be in guest RAM. Bits 5-1 are reserved and should be
+	area which must be in guest RAM. Bits 5-2 are reserved and should be
 	zero. Bit 0 is 1 when asynchronous page faults are enabled on the vcpu
-	0 when disabled.
+	0 when disabled. Bit 2 is 1 if asynchronous page faults can be injected
+	when vcpu is in kernel mode.
 
 	Physical address points to 32 bit memory location that will be written
 	to by the hypervisor at the time of asynchronous page fault injection to
arch/x86/include/asm/kvm_host.h +1 -0
index 2f6fc87..81c1a4f 100644
@@ -420,6 +420,7 @@ struct kvm_vcpu_arch {
 		struct gfn_to_hva_cache data;
 		u64 msr_val;
 		u32 id;
+		bool send_user_only;
 	} apf;
 };
 
arch/x86/include/asm/kvm_para.h +1 -0
index bcc5022..bf3dab3 100644
@@ -38,6 +38,7 @@
 #define KVM_MAX_MMU_OP_BATCH           32
 
 #define KVM_ASYNC_PF_ENABLED			(1 << 0)
+#define KVM_ASYNC_PF_SEND_ALWAYS		(1 << 1)
 
 /* Operations for KVM_HC_MMU_OP */
 #define KVM_MMU_OP_WRITE_PTE            1
arch/x86/kernel/kvm.c +3 -0
index f73946f..d5877bf 100644
@@ -449,6 +449,9 @@ void __cpuinit kvm_guest_cpu_init(void)
 	if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF) && kvmapf) {
 		u64 pa = __pa(&__get_cpu_var(apf_reason));
 
+#ifdef CONFIG_PREEMPT
+		pa |= KVM_ASYNC_PF_SEND_ALWAYS;
+#endif
 		if (native_write_msr_safe(MSR_KVM_ASYNC_PF_EN,
 					  pa | KVM_ASYNC_PF_ENABLED, pa >> 32))
 			return;
arch/x86/kvm/x86.c +3 -2
index 0e69d37..cad4412 100644
@@ -1429,8 +1429,8 @@ static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
 {
 	gpa_t gpa = data & ~0x3f;
 
-	/* Bits 1:5 are resrved, Should be zero */
-	if (data & 0x3e)
+	/* Bits 2:5 are resrved, Should be zero */
+	if (data & 0x3c)
 		return 1;
 
 	vcpu->arch.apf.msr_val = data;
@@ -1444,6 +1444,7 @@ static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
 	if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa))
 		return 1;
 
+	vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
 	kvm_async_pf_wakeup_all(vcpu);
 	return 0;
 }
Signature · 7 lines
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#86 lore raw

PATCH v6 12/12 Send async PF when guest is not in userspace too.

In reply to Gleb Natapov

If guest indicates that it can handle async pf in kernel mode too send it, but only if interrupts are enabled.

---
 arch/x86/kvm/x86.c |    3 ++-
 1 files changed, 2 insertions(+), 1 deletions(-)
arch/x86/kvm/x86.c +2 -1
index cad4412..30b1cd1 100644
@@ -6244,7 +6244,8 @@ void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
 		kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
 
 		if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
-		    kvm_x86_ops->get_cpl(vcpu) == 0)
+		    (vcpu->arch.apf.send_user_only &&
+		     kvm_x86_ops->get_cpl(vcpu) == 0))
 			vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
 		else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
 			vcpu->arch.fault.error_code = 0;
Signature · 7 lines
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Acked-by on v6 2/12
#3 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Gleb Natapov
Quoted 8 lines · Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

This seems quite different from the last version, but it looks fine to me.

Signature · 7 lines
All rights reversed

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Acked-by on v6 4/12
#34 lore raw

Re: [PATCH v6 04/12] Add memory slot versioning and use it to provide fast guest write interface

In reply to Gleb Natapov
Quoted 6 lines · Gleb Natapov

Keep track of memslots changes by keeping generation number in memslots structure. Provide kvm_write_guest_cached() function that skips gfn_to_hva() translation if memslots was not changed since previous invocation.

Signature · 7 lines
All rights reversed

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Acked-by on v6 9/12
#77 lore raw

Re: [PATCH v6 09/12] Inject asynchronous page fault into a PV guest if page is swapped out.

In reply to Gleb Natapov
Quoted 11 lines · Gleb Natapov

Send async page fault to a PV guest if it accesses swapped out memory. Guest will choose another task to run upon receiving the fault.

Allow async page fault injection only when guest is in user mode since otherwise guest may be in non-sleepable context and will not be able to reschedule.

Vcpu will be halted if guest will fault on the same page again or if vcpu executes kernel code.

Signature · 7 lines
All rights reversed

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Acked-by on v6 12/12
#87 lore raw

Re: [PATCH v6 12/12] Send async PF when guest is not in userspace too.

In reply to Gleb Natapov
Quoted 4 lines · Gleb Natapov

If guest indicates that it can handle async pf in kernel mode too send it, but only if interrupts are enabled.

Signature · 7 lines
All rights reversed

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#4 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Gleb Natapov
Quoted 48 lines · Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

---
 arch/x86/include/asm/kvm_host.h |   17 +++
 arch/x86/kvm/Kconfig            |    1 +
 arch/x86/kvm/Makefile           |    1 +
 arch/x86/kvm/mmu.c              |   51 +++++++++-
 arch/x86/kvm/paging_tmpl.h      |    4 +-
 arch/x86/kvm/x86.c              |  109 +++++++++++++++++++-
 include/linux/kvm_host.h        |   31 ++++++
 include/trace/events/kvm.h      |   88 ++++++++++++++++
 virt/kvm/Kconfig                |    3 +
 virt/kvm/async_pf.c             |  220 +++++++++++++++++++++++++++++++++++++++
 virt/kvm/async_pf.h             |   36 +++++++
 virt/kvm/kvm_main.c             |   57 ++++++++--
 12 files changed, 603 insertions(+), 15 deletions(-)
 create mode 100644 virt/kvm/async_pf.c
 create mode 100644 virt/kvm/async_pf.h
virt/kvm/async_pf.c new file +22 -0
+	async_pf_cache = NULL;
+}
+
+void kvm_async_pf_vcpu_init(struct kvm_vcpu *vcpu)
+{
+	INIT_LIST_HEAD(&vcpu->async_pf.done);
+	INIT_LIST_HEAD(&vcpu->async_pf.queue);
+	spin_lock_init(&vcpu->async_pf.lock);
+}
+
+static void async_pf_execute(struct work_struct *work)
+{
+	struct page *page;
+	struct kvm_async_pf *apf =
+		container_of(work, struct kvm_async_pf, work);
+	struct mm_struct *mm = apf->mm;
+	struct kvm_vcpu *vcpu = apf->vcpu;
+	unsigned long addr = apf->addr;
+	gva_t gva = apf->gva;
+
+	might_sleep();
+

virt/kvm/async_pf.c line 78

Quoted 10 lines
virt/kvm/async_pf.c new file +10 -0
+	use_mm(mm);
+	down_read(&mm->mmap_sem);
+	get_user_pages(current, mm, addr, 1, 1, 0, &page, NULL);
+	up_read(&mm->mmap_sem);
+	unuse_mm(mm);
+
+	spin_lock(&vcpu->async_pf.lock);
+	list_add_tail(&apf->link, &vcpu->async_pf.done);
+	apf->page = page;
+	spin_unlock(&vcpu->async_pf.lock);

This can fail, and apf->page become NULL.

Quoted 6 lines
virt/kvm/async_pf.c new file +6 -0
+	if (list_empty_careful(&vcpu->async_pf.done))
+		return;
+
+	spin_lock(&vcpu->async_pf.lock);
+	work = list_first_entry(&vcpu->async_pf.done, typeof(*work), link);
+	list_del(&work->link);

virt/kvm/async_pf.c line 155

Quoted 10 lines
virt/kvm/async_pf.c new file +10 -0
+	spin_unlock(&vcpu->async_pf.lock);
+
+	kvm_arch_async_page_present(vcpu, work);
+
+free:
+	list_del(&work->queue);
+	vcpu->async_pf.queued--;
+	put_page(work->page);
+	kmem_cache_free(async_pf_cache, work);
+}

Better handle it here (and other sites).

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#24 lore raw

Re: [PATCH v6 03/12] Retry fault before vmentry

In reply to Gleb Natapov
Quoted 130 lines · Gleb Natapov

When page is swapped in it is mapped into guest memory only after guest tries to access it again and generate another fault. To save this fault we can map it immediately since we know that guest is going to access the page. Do it only when tdp is enabled for now. Shadow paging case is more complicated. CR[034] and EFER registers should be switched before doing mapping and then switched back.

---
 arch/x86/include/asm/kvm_host.h |    4 +++-
 arch/x86/kvm/mmu.c              |   16 ++++++++--------
 arch/x86/kvm/paging_tmpl.h      |    6 +++---
 arch/x86/kvm/x86.c              |    7 +++++++
 virt/kvm/async_pf.c             |    2 ++
 5 files changed, 23 insertions(+), 12 deletions(-)
arch/x86/include/asm/kvm_host.h +3 -1
index 5f154d3..b9f263e 100644
@@ -240,7 +240,7 @@ struct kvm_mmu {
 	void (*new_cr3)(struct kvm_vcpu *vcpu);
 	void (*set_cr3)(struct kvm_vcpu *vcpu, unsigned long root);
 	unsigned long (*get_cr3)(struct kvm_vcpu *vcpu);
-	int (*page_fault)(struct kvm_vcpu *vcpu, gva_t gva, u32 err);
+	int (*page_fault)(struct kvm_vcpu *vcpu, gva_t gva, u32 err, bool no_apf);
 	void (*inject_page_fault)(struct kvm_vcpu *vcpu);
 	void (*free)(struct kvm_vcpu *vcpu);
 	gpa_t (*gva_to_gpa)(struct kvm_vcpu *vcpu, gva_t gva, u32 access,
@@ -838,6 +838,8 @@ void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
 				     struct kvm_async_pf *work);
 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
 				 struct kvm_async_pf *work);
+void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu,
+			       struct kvm_async_pf *work);
 extern bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn);
 
 #endif /* _ASM_X86_KVM_HOST_H */
arch/x86/kvm/mmu.c +8 -8
index 4d49b5e..d85fda8 100644
@@ -2558,7 +2558,7 @@ static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
 }
 
 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
-				u32 error_code)
+				u32 error_code, bool no_apf)
 {
 	gfn_t gfn;
 	int r;
@@ -2594,8 +2594,8 @@ static bool can_do_async_pf(struct kvm_vcpu *vcpu)
 	return kvm_x86_ops->interrupt_allowed(vcpu);
 }
 
-static bool try_async_pf(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
-			 pfn_t *pfn)
+static bool try_async_pf(struct kvm_vcpu *vcpu, bool no_apf, gfn_t gfn,
+			 gva_t gva, pfn_t *pfn)
 {
 	bool async;
 
@@ -2606,7 +2606,7 @@ static bool try_async_pf(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
 
 	put_page(pfn_to_page(*pfn));
 
-	if (can_do_async_pf(vcpu)) {
+	if (!no_apf && can_do_async_pf(vcpu)) {
 		trace_kvm_try_async_get_page(async, *pfn);
 		if (kvm_find_async_pf_gfn(vcpu, gfn)) {
 			vcpu->async_pf.work = kvm_double_apf;
@@ -2620,8 +2620,8 @@ static bool try_async_pf(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
 	return false;
 }
 
-static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa,
-				u32 error_code)
+static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
+			  bool no_apf)
 {
 	pfn_t pfn;
 	int r;
@@ -2643,7 +2643,7 @@ static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa,
 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
 	smp_rmb();
 
-	if (try_async_pf(vcpu, gfn, gpa, &pfn))
+	if (try_async_pf(vcpu, no_apf, gfn, gpa, &pfn))
 		return 0;
 
 	/* mmio */
@@ -3306,7 +3306,7 @@ int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code)
 	int r;
 	enum emulation_result er;
 
-	r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code);
+	r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code, false);
 	if (r < 0)
 		goto out;
 
arch/x86/kvm/paging_tmpl.h +3 -3
index 8154353..9ad90f8 100644
@@ -530,8 +530,8 @@ out_gpte_changed:
  *  Returns: 1 if we need to emulate the instruction, 0 otherwise, or
  *           a negative value on error.
  */
-static int FNAME(page_fault)(struct kvm_vcpu *vcpu, gva_t addr,
-			       u32 error_code)
+static int FNAME(page_fault)(struct kvm_vcpu *vcpu, gva_t addr, u32 error_code,
+			     bool no_apf)
 {
 	int write_fault = error_code & PFERR_WRITE_MASK;
 	int user_fault = error_code & PFERR_USER_MASK;
@@ -574,7 +574,7 @@ static int FNAME(page_fault)(struct kvm_vcpu *vcpu, gva_t addr,
 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
 	smp_rmb();
 
-	if (try_async_pf(vcpu, walker.gfn, addr, &pfn))
+	if (try_async_pf(vcpu, no_apf, walker.gfn, addr, &pfn))
 		return 0;
 
 	/* mmio */
arch/x86/kvm/x86.c +0 -0
index 8dd9ac2..48fd59d 100644

arch/x86/kvm/x86.c void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags) · line 6132

Quoted 10 lines
arch/x86/kvm/x86.c +7 -0
@@ -6123,6 +6123,13 @@ void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
 }
 EXPORT_SYMBOL_GPL(kvm_set_rflags);
 
+void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
+{
+	if (!tdp_enabled || is_error_page(work->page))
+		return;
+	vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
+}
+

Can't you set a bit in vcpu->requests instead, and handle it in "out:" at the end of vcpu_enter_guest?

To have a single entry point for pagefaults, after vmexit handling.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#35 lore raw

Re: [PATCH v6 04/12] Add memory slot versioning and use it to provide fast guest write interface

In reply to Gleb Natapov
Quoted 91 lines · Gleb Natapov

Keep track of memslots changes by keeping generation number in memslots structure. Provide kvm_write_guest_cached() function that skips gfn_to_hva() translation if memslots was not changed since previous invocation.

---
 include/linux/kvm_host.h  |    7 +++++
 include/linux/kvm_types.h |    7 +++++
 virt/kvm/kvm_main.c       |   57 +++++++++++++++++++++++++++++++++++++++++---
 3 files changed, 67 insertions(+), 4 deletions(-)
include/linux/kvm_host.h +7 -0
index a08614e..4dff9a1 100644
@@ -199,6 +199,7 @@ struct kvm_irq_routing_table {};
 
 struct kvm_memslots {
 	int nmemslots;
+	u32 generation;
 	struct kvm_memory_slot memslots[KVM_MEMORY_SLOTS +
 					KVM_PRIVATE_MEM_SLOTS];
 };
@@ -352,12 +353,18 @@ int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
 			 int offset, int len);
 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
 		    unsigned long len);
+int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
+			   void *data, unsigned long len);
+int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
+			      gpa_t gpa);
 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len);
 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len);
 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn);
 int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn);
 unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn);
 void mark_page_dirty(struct kvm *kvm, gfn_t gfn);
+void mark_page_dirty_in_slot(struct kvm *kvm, struct kvm_memory_slot *memslot,
+			     gfn_t gfn);
 
 void kvm_vcpu_block(struct kvm_vcpu *vcpu);
 void kvm_vcpu_on_spin(struct kvm_vcpu *vcpu);
include/linux/kvm_types.h +7 -0
index 7ac0d4e..ee6eb71 100644
@@ -67,4 +67,11 @@ struct kvm_lapic_irq {
 	u32 dest_id;
 };
 
+struct gfn_to_hva_cache {
+	u32 generation;
+	gpa_t gpa;
+	unsigned long hva;
+	struct kvm_memory_slot *memslot;
+};
+
 #endif /* __KVM_TYPES_H__ */
virt/kvm/kvm_main.c +10 -0
index db58a1b..45ef50c 100644
@@ -687,6 +687,7 @@ skip_lpage:
 		memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
 		if (mem->slot >= slots->nmemslots)
 			slots->nmemslots = mem->slot + 1;
+		slots->generation++;
 		slots->memslots[mem->slot].flags |= KVM_MEMSLOT_INVALID;
 
 		old_memslots = kvm->memslots;
@@ -723,6 +724,7 @@ skip_lpage:
 	memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
 	if (mem->slot >= slots->nmemslots)
 		slots->nmemslots = mem->slot + 1;
+	slots->generation++;
 
 	/* actual memory is freed via old in kvm_free_physmem_slot below */
 	if (!npages) {
@@ -1247,6 +1249,47 @@ int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
 	return 0;
 }
 
+int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
+			      gpa_t gpa)
+{
+	struct kvm_memslots *slots = kvm_memslots(kvm);
+	int offset = offset_in_page(gpa);
+	gfn_t gfn = gpa >> PAGE_SHIFT;
+
+	ghc->gpa = gpa;

virt/kvm/kvm_main.c int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data, · line 1269

Quoted 10 lines
virt/kvm/kvm_main.c +10 -0
+	ghc->generation = slots->generation;
+	ghc->memslot = gfn_to_memslot(kvm, gfn);
+	ghc->hva = gfn_to_hva(kvm, gfn);
+	if (!kvm_is_error_hva(ghc->hva))
+		ghc->hva += offset;
+	else
+		return -EFAULT;
+
+	return 0;
+}

Should use a unique kvm_memslots structure for the cache entry, since it can change in between (use gfn_to_hva_memslot, etc on "slots" pointer).

Also should zap any cached entries on overflow, otherwise malicious userspace could make use of stale slots:

Quoted 13 lines
virt/kvm/kvm_main.c +8 -0
+void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
+{
+	struct kvm_memory_slot *memslot;
+
+	memslot = gfn_to_memslot(kvm, gfn);
+	mark_page_dirty_in_slot(kvm, memslot, gfn);
+}
+
 /*
  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
  */
Signature · 1 line
1.7.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#57 lore raw

Re: [PATCH v6 07/12] Add async PF initialization to PV guest.

In reply to Gleb Natapov
Quoted 10 lines · Gleb Natapov

Enable async PF in a guest if async PF capability is discovered.

---
 Documentation/kernel-parameters.txt |    3 +
 arch/x86/include/asm/kvm_para.h     |    5 ++
 arch/x86/kernel/kvm.c               |   92 +++++++++++++++++++++++++++++++++++
 3 files changed, 100 insertions(+), 0 deletions(-)

arch/x86/kernel/kvm.c static void __init paravirt_ops_setup(void) · line 313

Quoted 9 lines
arch/x86/kernel/kvm.c +9 -0
+static int __cpuinit kvm_cpu_notify(struct notifier_block *self,
+				    unsigned long action, void *hcpu)
+{
+	int cpu = (unsigned long)hcpu;
+	switch (action) {
+	case CPU_ONLINE:
+	case CPU_DOWN_FAILED:
+	case CPU_ONLINE_FROZEN:
+		smp_call_function_single(cpu, kvm_guest_cpu_notify, NULL, 0);

wait parameter should probably be 1.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#78 lore raw

Re: [PATCH v6 09/12] Inject asynchronous page fault into a PV guest if page is swapped out.

In reply to Gleb Natapov
Quoted 88 lines · Gleb Natapov

Send async page fault to a PV guest if it accesses swapped out memory. Guest will choose another task to run upon receiving the fault.

Allow async page fault injection only when guest is in user mode since otherwise guest may be in non-sleepable context and will not be able to reschedule.

Vcpu will be halted if guest will fault on the same page again or if vcpu executes kernel code.

---
 arch/x86/include/asm/kvm_host.h |    3 ++
 arch/x86/kvm/mmu.c              |    1 +
 arch/x86/kvm/x86.c              |   49 ++++++++++++++++++++++++++++++++------
 include/trace/events/kvm.h      |   17 ++++++++----
 virt/kvm/async_pf.c             |    3 +-
 5 files changed, 58 insertions(+), 15 deletions(-)
arch/x86/include/asm/kvm_host.h +3 -0
index de31551..2f6fc87 100644
@@ -419,6 +419,7 @@ struct kvm_vcpu_arch {
 		gfn_t gfns[roundup_pow_of_two(ASYNC_PF_PER_VCPU)];
 		struct gfn_to_hva_cache data;
 		u64 msr_val;
+		u32 id;
 	} apf;
 };
 
@@ -594,6 +595,7 @@ struct kvm_x86_ops {
 };
 
 struct kvm_arch_async_pf {
+	u32 token;
 	gfn_t gfn;
 };
 
@@ -842,6 +844,7 @@ void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
 				 struct kvm_async_pf *work);
 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu,
 			       struct kvm_async_pf *work);
+bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu);
 extern bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn);
 
 #endif /* _ASM_X86_KVM_HOST_H */
arch/x86/kvm/mmu.c +1 -0
index d85fda8..de53cab 100644
@@ -2580,6 +2580,7 @@ static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
 int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
 {
 	struct kvm_arch_async_pf arch;
+	arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
 	arch.gfn = gfn;
 
 	return kvm_setup_async_pf(vcpu, gva, gfn, &arch);
arch/x86/kvm/x86.c +11 -6
index 3e123ab..0e69d37 100644
@@ -6225,25 +6225,58 @@ static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
 	}
 }
 
+static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
+{
+
+	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
+				      sizeof(val));
+}
+
 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
 				     struct kvm_async_pf *work)
 {
-	vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
-
-	if (work == kvm_double_apf)
+	if (work == kvm_double_apf) {
 		trace_kvm_async_pf_doublefault(kvm_rip_read(vcpu));
-	else {
-		trace_kvm_async_pf_not_present(work->gva);
-
+		vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
+	} else {
+		trace_kvm_async_pf_not_present(work->arch.token, work->gva);

arch/x86/kvm/x86.c static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn) · line 6252

Quoted 10 lines
arch/x86/kvm/x86.c +9 -0
 		kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
+
+		if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
+		    kvm_x86_ops->get_cpl(vcpu) == 0)
+			vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
+		else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
+			vcpu->arch.fault.error_code = 0;
+			vcpu->arch.fault.address = work->arch.token;
+			kvm_inject_page_fault(vcpu);
+		}

Missed !kvm_event_needs_reinjection(vcpu) ?

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#81 lore raw

Re: [PATCH v6 10/12] Handle async PF in non preemptable context

In reply to Gleb Natapov
Quoted 45 lines · Gleb Natapov

If async page fault is received by idle task or when preemp_count is not zero guest cannot reschedule, so do sti; hlt and wait for page to be ready. vcpu can still process interrupts while it waits for the page to be ready.

---
 arch/x86/kernel/kvm.c |   40 ++++++++++++++++++++++++++++++++++------
 1 files changed, 34 insertions(+), 6 deletions(-)
arch/x86/kernel/kvm.c +8 -0
index 36fb3e4..f73946f 100644
@@ -37,6 +37,7 @@
 #include <asm/cpu.h>
 #include <asm/traps.h>
 #include <asm/desc.h>
+#include <asm/tlbflush.h>
 
 #define MMU_QUEUE_SIZE 1024
 
@@ -78,6 +79,8 @@ struct kvm_task_sleep_node {
 	wait_queue_head_t wq;
 	u32 token;
 	int cpu;
+	bool halted;
+	struct mm_struct *mm;
 };
 
 static struct kvm_task_sleep_head {
@@ -106,6 +109,11 @@ void kvm_async_pf_task_wait(u32 token)
 	struct kvm_task_sleep_head *b = &async_pf_sleepers[key];
 	struct kvm_task_sleep_node n, *e;
 	DEFINE_WAIT(wait);
+	int cpu, idle;
+
+	cpu = get_cpu();
+	idle = idle_cpu(cpu);
+	put_cpu();
 
 	spin_lock(&b->lock);
 	e = _find_apf_task(b, token);

arch/x86/kernel/kvm.c void kvm_async_pf_task_wait(u32 token) · line 132

Quoted 6 lines
arch/x86/kernel/kvm.c +3 -0
@@ -119,19 +127,33 @@ void kvm_async_pf_task_wait(u32 token)
 
 	n.token = token;
 	n.cpu = smp_processor_id();
+	n.mm = current->active_mm;
+	n.halted = idle || preempt_count() > 1;
+	atomic_inc(&n.mm->mm_count);

Can't see why this reference is needed.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#82 lore raw

Re: [PATCH v6 10/12] Handle async PF in non preemptable context

Quoted 47 lines · Marcelo Tosatti
Quoted 46 lines · Gleb Natapov

If async page fault is received by idle task or when preemp_count is not zero guest cannot reschedule, so do sti; hlt and wait for page to be ready. vcpu can still process interrupts while it waits for the page to be ready.

---
 arch/x86/kernel/kvm.c |   40 ++++++++++++++++++++++++++++++++++------
 1 files changed, 34 insertions(+), 6 deletions(-)
arch/x86/kernel/kvm.c +8 -0
index 36fb3e4..f73946f 100644
@@ -37,6 +37,7 @@
 #include <asm/cpu.h>
 #include <asm/traps.h>
 #include <asm/desc.h>
+#include <asm/tlbflush.h>
 
 #define MMU_QUEUE_SIZE 1024
 
@@ -78,6 +79,8 @@ struct kvm_task_sleep_node {
 	wait_queue_head_t wq;
 	u32 token;
 	int cpu;
+	bool halted;
+	struct mm_struct *mm;
 };
 
 static struct kvm_task_sleep_head {
@@ -106,6 +109,11 @@ void kvm_async_pf_task_wait(u32 token)
 	struct kvm_task_sleep_head *b = &async_pf_sleepers[key];
 	struct kvm_task_sleep_node n, *e;
 	DEFINE_WAIT(wait);
+	int cpu, idle;
+
+	cpu = get_cpu();
+	idle = idle_cpu(cpu);
+	put_cpu();
 
 	spin_lock(&b->lock);
 	e = _find_apf_task(b, token);
@@ -119,19 +127,33 @@ void kvm_async_pf_task_wait(u32 token)
 
Quoted 7 lines

arch/x86/kernel/kvm.c void kvm_async_pf_task_wait(u32 token) · line 132

Quoted 5 lines
arch/x86/kernel/kvm.c +3 -0
 	n.token = token;
 	n.cpu = smp_processor_id();
+	n.mm = current->active_mm;
+	n.halted = idle || preempt_count() > 1;
+	atomic_inc(&n.mm->mm_count);

Can't see why this reference is needed.

I thought that if kernel thread does fault on behalf of some process mm can go away while kernel thread is sleeping. But it looks like kernel thread increase reference to mm it runs with by himself, so may be this is redundant (but not harmful).

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#79 lore raw

Re: [PATCH v6 09/12] Inject asynchronous page fault into a PV guest if page is swapped out.

In reply to Marcelo Tosatti
Quoted 93 lines · Marcelo Tosatti
Quoted 92 lines · Gleb Natapov

Send async page fault to a PV guest if it accesses swapped out memory. Guest will choose another task to run upon receiving the fault.

Allow async page fault injection only when guest is in user mode since otherwise guest may be in non-sleepable context and will not be able to reschedule.

Vcpu will be halted if guest will fault on the same page again or if vcpu executes kernel code.

---
 arch/x86/include/asm/kvm_host.h |    3 ++
 arch/x86/kvm/mmu.c              |    1 +
 arch/x86/kvm/x86.c              |   49 ++++++++++++++++++++++++++++++++------
 include/trace/events/kvm.h      |   17 ++++++++----
 virt/kvm/async_pf.c             |    3 +-
 5 files changed, 58 insertions(+), 15 deletions(-)
arch/x86/include/asm/kvm_host.h +3 -0
index de31551..2f6fc87 100644
@@ -419,6 +419,7 @@ struct kvm_vcpu_arch {
 		gfn_t gfns[roundup_pow_of_two(ASYNC_PF_PER_VCPU)];
 		struct gfn_to_hva_cache data;
 		u64 msr_val;
+		u32 id;
 	} apf;
 };
 
@@ -594,6 +595,7 @@ struct kvm_x86_ops {
 };
 
 struct kvm_arch_async_pf {
+	u32 token;
 	gfn_t gfn;
 };
 
@@ -842,6 +844,7 @@ void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
 				 struct kvm_async_pf *work);
 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu,
 			       struct kvm_async_pf *work);
+bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu);
 extern bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn);
 
 #endif /* _ASM_X86_KVM_HOST_H */
arch/x86/kvm/mmu.c +1 -0
index d85fda8..de53cab 100644
@@ -2580,6 +2580,7 @@ static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
 int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
 {
 	struct kvm_arch_async_pf arch;
+	arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
 	arch.gfn = gfn;
 
 	return kvm_setup_async_pf(vcpu, gva, gfn, &arch);
arch/x86/kvm/x86.c +14 -6
index 3e123ab..0e69d37 100644
@@ -6225,25 +6225,58 @@ static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
 	}
 }
 
+static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
+{
+
+	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
+				      sizeof(val));
+}
+
 void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
 				     struct kvm_async_pf *work)
 {
-	vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
-
-	if (work == kvm_double_apf)
+	if (work == kvm_double_apf) {
 		trace_kvm_async_pf_doublefault(kvm_rip_read(vcpu));
-	else {
-		trace_kvm_async_pf_not_present(work->gva);
-
+		vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
+	} else {
+		trace_kvm_async_pf_not_present(work->arch.token, work->gva);
 		kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
+
+		if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
+		    kvm_x86_ops->get_cpl(vcpu) == 0)
Quoted 8 lines

arch/x86/kvm/x86.c static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn) · line 6252

Quoted 6 lines
arch/x86/kvm/x86.c +6 -0
+			vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
+		else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
+			vcpu->arch.fault.error_code = 0;
+			vcpu->arch.fault.address = work->arch.token;
+			kvm_inject_page_fault(vcpu);
+		}

Missed !kvm_event_needs_reinjection(vcpu) ?

This check is done in can_do_async_pf(). We will not get here if event is pending.

--
Gleb.

#5 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Marcelo Tosatti
Quoted 60 lines · Marcelo Tosatti
Quoted 50 lines · Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

---

  arch/x86/include/asm/kvm_host.h |   17 +++
  arch/x86/kvm/Kconfig            |    1 +
  arch/x86/kvm/Makefile           |    1 +
  arch/x86/kvm/mmu.c              |   51 +++++++++-
  arch/x86/kvm/paging_tmpl.h      |    4 +-
  arch/x86/kvm/x86.c              |  109 +++++++++++++++++++-
  include/linux/kvm_host.h        |   31 ++++++
  include/trace/events/kvm.h      |   88 ++++++++++++++++
  virt/kvm/Kconfig                |    3 +
  virt/kvm/async_pf.c             |  220 +++++++++++++++++++++++++++++++++++++++
  virt/kvm/async_pf.h             |   36 +++++++
  virt/kvm/kvm_main.c             |   57 ++++++++--
  12 files changed, 603 insertions(+), 15 deletions(-)

create mode 100644 virt/kvm/async_pf.c
create mode 100644 virt/kvm/async_pf.h

+ async_pf_cache = NULL;
+}
+
+void kvm_async_pf_vcpu_init(struct kvm_vcpu *vcpu) +{
+ INIT_LIST_HEAD(&vcpu->async_pf.done);
+ INIT_LIST_HEAD(&vcpu->async_pf.queue);
+ spin_lock_init(&vcpu->async_pf.lock);
+}
+
+static void async_pf_execute(struct work_struct *work) +{
+ struct page *page;
+ struct kvm_async_pf *apf =
+ container_of(work, struct kvm_async_pf, work);
+ struct mm_struct *mm = apf->mm;
+ struct kvm_vcpu *vcpu = apf->vcpu;
+ unsigned long addr = apf->addr;
+ gva_t gva = apf->gva;
+
+ might_sleep();
+
+ use_mm(mm);
+ down_read(&mm->mmap_sem);

Quoted 8 lines

+ get_user_pages(current, mm, addr, 1, 1, 0,&page, NULL);
+ up_read(&mm->mmap_sem);
+ unuse_mm(mm);
+
+ spin_lock(&vcpu->async_pf.lock);
+ list_add_tail(&apf->link,&vcpu->async_pf.done);
+ apf->page = page;
+ spin_unlock(&vcpu->async_pf.lock);

Quoted 1 line

This can fail, and apf->page become NULL.

Does it even become NULL? On error, get_user_pages() won't update the pages argument, so page becomes garbage here.

Signature · 7 lines
error compiling committee.c: too many arguments to function

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#6 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

Quoted 61 lines · Avi Kivity
Quoted 60 lines · Marcelo Tosatti
Quoted 58 lines · Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

---

  arch/x86/include/asm/kvm_host.h |   17 +++
  arch/x86/kvm/Kconfig            |    1 +
  arch/x86/kvm/Makefile           |    1 +
  arch/x86/kvm/mmu.c              |   51 +++++++++-
  arch/x86/kvm/paging_tmpl.h      |    4 +-
  arch/x86/kvm/x86.c              |  109 +++++++++++++++++++-
  include/linux/kvm_host.h        |   31 ++++++
  include/trace/events/kvm.h      |   88 ++++++++++++++++
  virt/kvm/Kconfig                |    3 +
  virt/kvm/async_pf.c             |  220 +++++++++++++++++++++++++++++++++++++++
  virt/kvm/async_pf.h             |   36 +++++++
  virt/kvm/kvm_main.c             |   57 ++++++++--
  12 files changed, 603 insertions(+), 15 deletions(-)

create mode 100644 virt/kvm/async_pf.c
create mode 100644 virt/kvm/async_pf.h

+ async_pf_cache = NULL;
+}
+
+void kvm_async_pf_vcpu_init(struct kvm_vcpu *vcpu) +{
+ INIT_LIST_HEAD(&vcpu->async_pf.done);
+ INIT_LIST_HEAD(&vcpu->async_pf.queue);
+ spin_lock_init(&vcpu->async_pf.lock);
+}
+
+static void async_pf_execute(struct work_struct *work) +{
+ struct page *page;
+ struct kvm_async_pf *apf =
+ container_of(work, struct kvm_async_pf, work);
+ struct mm_struct *mm = apf->mm;
+ struct kvm_vcpu *vcpu = apf->vcpu;
+ unsigned long addr = apf->addr;
+ gva_t gva = apf->gva;
+
+ might_sleep();
+
+ use_mm(mm);
+ down_read(&mm->mmap_sem);
+ get_user_pages(current, mm, addr, 1, 1, 0,&page, NULL);
+ up_read(&mm->mmap_sem);
+ unuse_mm(mm);
+
+ spin_lock(&vcpu->async_pf.lock);
+ list_add_tail(&apf->link,&vcpu->async_pf.done);
+ apf->page = page;
+ spin_unlock(&vcpu->async_pf.lock);

Quoted 5 lines
Quoted 1 line

This can fail, and apf->page become NULL.

Does it even become NULL? On error, get_user_pages() won't update the pages argument, so page becomes garbage here.

apf is allocated with kmem_cache_zalloc() and ->page is set to NULL in kvm_setup_async_pf() to be extra sure.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#58 lore raw

Re: [PATCH v6 07/12] Add async PF initialization to PV guest.

In reply to Marcelo Tosatti
Quoted 11 lines · Marcelo Tosatti
Quoted 9 lines · Gleb Natapov

Enable async PF in a guest if async PF capability is discovered.

---
 Documentation/kernel-parameters.txt |    3 +
 arch/x86/include/asm/kvm_para.h     |    5 ++
 arch/x86/kernel/kvm.c               |   92 +++++++++++++++++++++++++++++++++++
 3 files changed, 100 insertions(+), 0 deletions(-)
Quoted 11 lines

arch/x86/kernel/kvm.c static void __init paravirt_ops_setup(void) · line 313

Quoted 9 lines
arch/x86/kernel/kvm.c +9 -0
+static int __cpuinit kvm_cpu_notify(struct notifier_block *self,
+				    unsigned long action, void *hcpu)
+{
+	int cpu = (unsigned long)hcpu;
+	switch (action) {
+	case CPU_ONLINE:
+	case CPU_DOWN_FAILED:
+	case CPU_ONLINE_FROZEN:
+		smp_call_function_single(cpu, kvm_guest_cpu_notify, NULL, 0);

wait parameter should probably be 1.

Why should we wait for it? FWIW I copied this from somewhere (May be arch/x86/pci/amd_bus.c).

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#25 lore raw

Re: [PATCH v6 03/12] Retry fault before vmentry

In reply to Marcelo Tosatti
Quoted 145 lines · Marcelo Tosatti
Quoted 130 lines · Gleb Natapov

When page is swapped in it is mapped into guest memory only after guest tries to access it again and generate another fault. To save this fault we can map it immediately since we know that guest is going to access the page. Do it only when tdp is enabled for now. Shadow paging case is more complicated. CR[034] and EFER registers should be switched before doing mapping and then switched back.

---
 arch/x86/include/asm/kvm_host.h |    4 +++-
 arch/x86/kvm/mmu.c              |   16 ++++++++--------
 arch/x86/kvm/paging_tmpl.h      |    6 +++---
 arch/x86/kvm/x86.c              |    7 +++++++
 virt/kvm/async_pf.c             |    2 ++
 5 files changed, 23 insertions(+), 12 deletions(-)
arch/x86/include/asm/kvm_host.h +3 -1
index 5f154d3..b9f263e 100644
@@ -240,7 +240,7 @@ struct kvm_mmu {
 	void (*new_cr3)(struct kvm_vcpu *vcpu);
 	void (*set_cr3)(struct kvm_vcpu *vcpu, unsigned long root);
 	unsigned long (*get_cr3)(struct kvm_vcpu *vcpu);
-	int (*page_fault)(struct kvm_vcpu *vcpu, gva_t gva, u32 err);
+	int (*page_fault)(struct kvm_vcpu *vcpu, gva_t gva, u32 err, bool no_apf);
 	void (*inject_page_fault)(struct kvm_vcpu *vcpu);
 	void (*free)(struct kvm_vcpu *vcpu);
 	gpa_t (*gva_to_gpa)(struct kvm_vcpu *vcpu, gva_t gva, u32 access,
@@ -838,6 +838,8 @@ void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
 				     struct kvm_async_pf *work);
 void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
 				 struct kvm_async_pf *work);
+void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu,
+			       struct kvm_async_pf *work);
 extern bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn);
 
 #endif /* _ASM_X86_KVM_HOST_H */
arch/x86/kvm/mmu.c +8 -8
index 4d49b5e..d85fda8 100644
@@ -2558,7 +2558,7 @@ static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
 }
 
 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
-				u32 error_code)
+				u32 error_code, bool no_apf)
 {
 	gfn_t gfn;
 	int r;
@@ -2594,8 +2594,8 @@ static bool can_do_async_pf(struct kvm_vcpu *vcpu)
 	return kvm_x86_ops->interrupt_allowed(vcpu);
 }
 
-static bool try_async_pf(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
-			 pfn_t *pfn)
+static bool try_async_pf(struct kvm_vcpu *vcpu, bool no_apf, gfn_t gfn,
+			 gva_t gva, pfn_t *pfn)
 {
 	bool async;
 
@@ -2606,7 +2606,7 @@ static bool try_async_pf(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
 
 	put_page(pfn_to_page(*pfn));
 
-	if (can_do_async_pf(vcpu)) {
+	if (!no_apf && can_do_async_pf(vcpu)) {
 		trace_kvm_try_async_get_page(async, *pfn);
 		if (kvm_find_async_pf_gfn(vcpu, gfn)) {
 			vcpu->async_pf.work = kvm_double_apf;
@@ -2620,8 +2620,8 @@ static bool try_async_pf(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
 	return false;
 }
 
-static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa,
-				u32 error_code)
+static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
+			  bool no_apf)
 {
 	pfn_t pfn;
 	int r;
@@ -2643,7 +2643,7 @@ static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa,
 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
 	smp_rmb();
 
-	if (try_async_pf(vcpu, gfn, gpa, &pfn))
+	if (try_async_pf(vcpu, no_apf, gfn, gpa, &pfn))
 		return 0;
 
 	/* mmio */
@@ -3306,7 +3306,7 @@ int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code)
 	int r;
 	enum emulation_result er;
 
-	r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code);
+	r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code, false);
 	if (r < 0)
 		goto out;
 
arch/x86/kvm/paging_tmpl.h +3 -3
index 8154353..9ad90f8 100644
@@ -530,8 +530,8 @@ out_gpte_changed:
  *  Returns: 1 if we need to emulate the instruction, 0 otherwise, or
  *           a negative value on error.
  */
-static int FNAME(page_fault)(struct kvm_vcpu *vcpu, gva_t addr,
-			       u32 error_code)
+static int FNAME(page_fault)(struct kvm_vcpu *vcpu, gva_t addr, u32 error_code,
+			     bool no_apf)
 {
 	int write_fault = error_code & PFERR_WRITE_MASK;
 	int user_fault = error_code & PFERR_USER_MASK;
@@ -574,7 +574,7 @@ static int FNAME(page_fault)(struct kvm_vcpu *vcpu, gva_t addr,
 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
 	smp_rmb();
 
-	if (try_async_pf(vcpu, walker.gfn, addr, &pfn))
+	if (try_async_pf(vcpu, no_apf, walker.gfn, addr, &pfn))
 		return 0;
 
 	/* mmio */
arch/x86/kvm/x86.c +0 -0
index 8dd9ac2..48fd59d 100644

arch/x86/kvm/x86.c void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags) · line 6132

Quoted 10 lines
arch/x86/kvm/x86.c +7 -0
@@ -6123,6 +6123,13 @@ void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
 }
 EXPORT_SYMBOL_GPL(kvm_set_rflags);
 
+void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
+{
+	if (!tdp_enabled || is_error_page(work->page))
+		return;
+	vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
+}
+

Can't you set a bit in vcpu->requests instead, and handle it in "out:" at the end of vcpu_enter_guest?

Quoted 1 line

To have a single entry point for pagefaults, after vmexit handling.

Jumping to "out:" will skip vmexit handling anyway, so we will not reuse same call site anyway. I don't see yet why the way you propose will have an advantage.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#36 lore raw

Re: [PATCH v6 04/12] Add memory slot versioning and use it to provide fast guest write interface

In reply to Marcelo Tosatti
Quoted 97 lines · Marcelo Tosatti
Quoted 96 lines · Gleb Natapov

Keep track of memslots changes by keeping generation number in memslots structure. Provide kvm_write_guest_cached() function that skips gfn_to_hva() translation if memslots was not changed since previous invocation.

---
 include/linux/kvm_host.h  |    7 +++++
 include/linux/kvm_types.h |    7 +++++
 virt/kvm/kvm_main.c       |   57 +++++++++++++++++++++++++++++++++++++++++---
 3 files changed, 67 insertions(+), 4 deletions(-)
include/linux/kvm_host.h +7 -0
index a08614e..4dff9a1 100644
@@ -199,6 +199,7 @@ struct kvm_irq_routing_table {};
 
 struct kvm_memslots {
 	int nmemslots;
+	u32 generation;
 	struct kvm_memory_slot memslots[KVM_MEMORY_SLOTS +
 					KVM_PRIVATE_MEM_SLOTS];
 };
@@ -352,12 +353,18 @@ int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
 			 int offset, int len);
 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
 		    unsigned long len);
+int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
+			   void *data, unsigned long len);
+int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
+			      gpa_t gpa);
 int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len);
 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len);
 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn);
 int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn);
 unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn);
 void mark_page_dirty(struct kvm *kvm, gfn_t gfn);
+void mark_page_dirty_in_slot(struct kvm *kvm, struct kvm_memory_slot *memslot,
+			     gfn_t gfn);
 
 void kvm_vcpu_block(struct kvm_vcpu *vcpu);
 void kvm_vcpu_on_spin(struct kvm_vcpu *vcpu);
include/linux/kvm_types.h +7 -0
index 7ac0d4e..ee6eb71 100644
@@ -67,4 +67,11 @@ struct kvm_lapic_irq {
 	u32 dest_id;
 };
 
+struct gfn_to_hva_cache {
+	u32 generation;
+	gpa_t gpa;
+	unsigned long hva;
+	struct kvm_memory_slot *memslot;
+};
+
 #endif /* __KVM_TYPES_H__ */
virt/kvm/kvm_main.c +15 -0
index db58a1b..45ef50c 100644
@@ -687,6 +687,7 @@ skip_lpage:
 		memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
 		if (mem->slot >= slots->nmemslots)
 			slots->nmemslots = mem->slot + 1;
+		slots->generation++;
 		slots->memslots[mem->slot].flags |= KVM_MEMSLOT_INVALID;
 
 		old_memslots = kvm->memslots;
@@ -723,6 +724,7 @@ skip_lpage:
 	memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
 	if (mem->slot >= slots->nmemslots)
 		slots->nmemslots = mem->slot + 1;
+	slots->generation++;
 
 	/* actual memory is freed via old in kvm_free_physmem_slot below */
 	if (!npages) {
@@ -1247,6 +1249,47 @@ int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
 	return 0;
 }
 
+int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
+			      gpa_t gpa)
+{
+	struct kvm_memslots *slots = kvm_memslots(kvm);
+	int offset = offset_in_page(gpa);
+	gfn_t gfn = gpa >> PAGE_SHIFT;
+
+	ghc->gpa = gpa;
+	ghc->generation = slots->generation;
+	ghc->memslot = gfn_to_memslot(kvm, gfn);
+	ghc->hva = gfn_to_hva(kvm, gfn);
+	if (!kvm_is_error_hva(ghc->hva))
+		ghc->hva += offset;
Quoted 9 lines

virt/kvm/kvm_main.c int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data, · line 1269

Quoted 5 lines
virt/kvm/kvm_main.c +5 -0
+	else
+		return -EFAULT;
+
+	return 0;
+}

Should use a unique kvm_memslots structure for the cache entry, since it can change in between (use gfn_to_hva_memslot, etc on "slots" pointer).

I do not understand what do you mean here. kvm_memslots structure itself is not cached only various translation that use it are cached. Translation result are never used if kvm_memslots was changed.

Quoted 3 lines

Also should zap any cached entries on overflow, otherwise malicious userspace could make use of stale slots:

There is only one cached entry at each given time. User who wants to write into guest memory often defines gfn_to_hva_cache variable somewhere. Init it with kvm_gfn_to_hva_cache_init() and then calls kvm_write_guest_cached() on it. If there was no slot changes in between cached translation are used. Otherwise cache is recalculated.

Quoted 5 lines
Quoted 5 lines
virt/kvm/kvm_main.c +5 -0
+void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
+{
+	struct kvm_memory_slot *memslot;
+
+	memslot = gfn_to_memslot(kvm, gfn);
Quoted 8 lines
Quoted 8 lines
virt/kvm/kvm_main.c +3 -0
+	mark_page_dirty_in_slot(kvm, memslot, gfn);
+}
+
 /*
  * The vCPU has executed a HLT instruction with in-kernel mode enabled.
  */
Signature · 1 line
1.7.1

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#9 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Marcelo Tosatti
Quoted 72 lines · Marcelo Tosatti
Quoted 48 lines · Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

---
 arch/x86/include/asm/kvm_host.h |   17 +++
 arch/x86/kvm/Kconfig            |    1 +
 arch/x86/kvm/Makefile           |    1 +
 arch/x86/kvm/mmu.c              |   51 +++++++++-
 arch/x86/kvm/paging_tmpl.h      |    4 +-
 arch/x86/kvm/x86.c              |  109 +++++++++++++++++++-
 include/linux/kvm_host.h        |   31 ++++++
 include/trace/events/kvm.h      |   88 ++++++++++++++++
 virt/kvm/Kconfig                |    3 +
 virt/kvm/async_pf.c             |  220 +++++++++++++++++++++++++++++++++++++++
 virt/kvm/async_pf.h             |   36 +++++++
 virt/kvm/kvm_main.c             |   57 ++++++++--
 12 files changed, 603 insertions(+), 15 deletions(-)
 create mode 100644 virt/kvm/async_pf.c
 create mode 100644 virt/kvm/async_pf.h
virt/kvm/async_pf.c new file +22 -0
+	async_pf_cache = NULL;
+}
+
+void kvm_async_pf_vcpu_init(struct kvm_vcpu *vcpu)
+{
+	INIT_LIST_HEAD(&vcpu->async_pf.done);
+	INIT_LIST_HEAD(&vcpu->async_pf.queue);
+	spin_lock_init(&vcpu->async_pf.lock);
+}
+
+static void async_pf_execute(struct work_struct *work)
+{
+	struct page *page;
+	struct kvm_async_pf *apf =
+		container_of(work, struct kvm_async_pf, work);
+	struct mm_struct *mm = apf->mm;
+	struct kvm_vcpu *vcpu = apf->vcpu;
+	unsigned long addr = apf->addr;
+	gva_t gva = apf->gva;
+
+	might_sleep();
+

virt/kvm/async_pf.c line 78

Quoted 10 lines
virt/kvm/async_pf.c new file +10 -0
+	use_mm(mm);
+	down_read(&mm->mmap_sem);
+	get_user_pages(current, mm, addr, 1, 1, 0, &page, NULL);
+	up_read(&mm->mmap_sem);
+	unuse_mm(mm);
+
+	spin_lock(&vcpu->async_pf.lock);
+	list_add_tail(&apf->link, &vcpu->async_pf.done);
+	apf->page = page;
+	spin_unlock(&vcpu->async_pf.lock);

This can fail, and apf->page become NULL.

Quoted 10 lines
virt/kvm/async_pf.c new file +10 -0
+	if (list_empty_careful(&vcpu->async_pf.done))
+		return;
+
+	spin_lock(&vcpu->async_pf.lock);
+	work = list_first_entry(&vcpu->async_pf.done, typeof(*work), link);
+	list_del(&work->link);
+	spin_unlock(&vcpu->async_pf.lock);
+
+	kvm_arch_async_page_present(vcpu, work);
+
Quoted 8 lines

virt/kvm/async_pf.c line 155

Quoted 6 lines
virt/kvm/async_pf.c new file +6 -0
+free:
+	list_del(&work->queue);
+	vcpu->async_pf.queued--;
+	put_page(work->page);
+	kmem_cache_free(async_pf_cache, work);
+}

Better handle it here (and other sites).

Yeah. We should just reenter gust and let usual code path handle error on next guest access.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#26 lore raw

Re: [PATCH v6 03/12] Retry fault before vmentry

In reply to Gleb Natapov
Quoted 7 lines · Gleb Natapov
Quoted 4 lines

Can't you set a bit in vcpu->requests instead, and handle it in "out:" at the end of vcpu_enter_guest?

To have a single entry point for pagefaults, after vmexit handling.

Jumping to "out:" will skip vmexit handling anyway, so we will not reuse same call site anyway. I don't see yet why the way you propose will have an advantage.

What i meant was to call pagefault handler after vmexit handling.

Because the way it is in your patch now, with pre pagefault on entry, one has to make an effort to verify ordering wrt other events on entry processing.

With pre pagefault after vmexit, its more natural.

Does that make sense?

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#37 lore raw

Re: [PATCH v6 04/12] Add memory slot versioning and use it to provide fast guest write interface

In reply to Gleb Natapov
Quoted 9 lines · Gleb Natapov
Quoted 9 lines

virt/kvm/kvm_main.c int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data, · line 1260

Quoted 9 lines
virt/kvm/kvm_main.c +9 -0
+int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
+			      gpa_t gpa)
+{
+	struct kvm_memslots *slots = kvm_memslots(kvm);
+	int offset = offset_in_page(gpa);
+	gfn_t gfn = gpa >> PAGE_SHIFT;
+
+	ghc->gpa = gpa;
+	ghc->generation = slots->generation;

kvm->memslots can change here.

Quoted 2 lines
Quoted 2 lines

virt/kvm/kvm_main.c int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data, · line 1262

Quoted 2 lines
virt/kvm/kvm_main.c +2 -0
+	ghc->memslot = gfn_to_memslot(kvm, gfn);
+	ghc->hva = gfn_to_hva(kvm, gfn);

And if so, gfn_to_memslot / gfn_to_hva will use new memslots pointer.

Should dereference all values from one copy of kvm->memslots pointer.

Quoted 15 lines
Quoted 11 lines

virt/kvm/kvm_main.c int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data, · line 1269

Quoted 7 lines
virt/kvm/kvm_main.c +7 -0
+	if (!kvm_is_error_hva(ghc->hva))
+		ghc->hva += offset;
+	else
+		return -EFAULT;
+
+	return 0;
+}

Should use a unique kvm_memslots structure for the cache entry, since it can change in between (use gfn_to_hva_memslot, etc on "slots" pointer).

I do not understand what do you mean here. kvm_memslots structure itself is not cached only various translation that use it are cached. Translation result are never used if kvm_memslots was changed.

Quoted 8 lines
Quoted 3 lines

Also should zap any cached entries on overflow, otherwise malicious userspace could make use of stale slots:

There is only one cached entry at each given time. User who wants to write into guest memory often defines gfn_to_hva_cache variable somewhere. Init it with kvm_gfn_to_hva_cache_init() and then calls kvm_write_guest_cached() on it. If there was no slot changes in between cached translation are used. Otherwise cache is recalculated.

Malicious userspace can cause entry to be cached, ioctl SET_USER_MEMORY_REGION 2^32 times, generation number will match, mark_page_dirty_in_slot will be called with pointer to freed memory.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#59 lore raw

Re: [PATCH v6 07/12] Add async PF initialization to PV guest.

In reply to Gleb Natapov
Quoted 23 lines · Gleb Natapov
Quoted 11 lines · Marcelo Tosatti
Quoted 9 lines · Gleb Natapov

Enable async PF in a guest if async PF capability is discovered.

---
 Documentation/kernel-parameters.txt |    3 +
 arch/x86/include/asm/kvm_para.h     |    5 ++
 arch/x86/kernel/kvm.c               |   92 +++++++++++++++++++++++++++++++++++
 3 files changed, 100 insertions(+), 0 deletions(-)
Quoted 11 lines

arch/x86/kernel/kvm.c static void __init paravirt_ops_setup(void) · line 313

Quoted 9 lines
arch/x86/kernel/kvm.c +9 -0
+static int __cpuinit kvm_cpu_notify(struct notifier_block *self,
+				    unsigned long action, void *hcpu)
+{
+	int cpu = (unsigned long)hcpu;
+	switch (action) {
+	case CPU_ONLINE:
+	case CPU_DOWN_FAILED:
+	case CPU_ONLINE_FROZEN:
+		smp_call_function_single(cpu, kvm_guest_cpu_notify, NULL, 0);

wait parameter should probably be 1.

Quoted 2 lines

Why should we wait for it? FWIW I copied this from somewhere (May be arch/x86/pci/amd_bus.c).

So that you know its executed in a defined point in cpu bringup.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#60 lore raw

Re: [PATCH v6 07/12] Add async PF initialization to PV guest.

Quoted 24 lines · Marcelo Tosatti
Quoted 23 lines · Gleb Natapov
Quoted 22 lines · Marcelo Tosatti
Quoted 10 lines · Gleb Natapov

Enable async PF in a guest if async PF capability is discovered.

---
 Documentation/kernel-parameters.txt |    3 +
 arch/x86/include/asm/kvm_para.h     |    5 ++
 arch/x86/kernel/kvm.c               |   92 +++++++++++++++++++++++++++++++++++
 3 files changed, 100 insertions(+), 0 deletions(-)

arch/x86/kernel/kvm.c static void __init paravirt_ops_setup(void) · line 313

Quoted 9 lines
arch/x86/kernel/kvm.c +9 -0
+static int __cpuinit kvm_cpu_notify(struct notifier_block *self,
+				    unsigned long action, void *hcpu)
+{
+	int cpu = (unsigned long)hcpu;
+	switch (action) {
+	case CPU_ONLINE:
+	case CPU_DOWN_FAILED:
+	case CPU_ONLINE_FROZEN:
+		smp_call_function_single(cpu, kvm_guest_cpu_notify, NULL, 0);

wait parameter should probably be 1.

Quoted 5 lines
Quoted 2 lines

Why should we wait for it? FWIW I copied this from somewhere (May be arch/x86/pci/amd_bus.c).

So that you know its executed in a defined point in cpu bringup.

If I read code correctly CPU we are notified about is already running when callback is called, so I do not see what waiting for IPI to be processed will accomplish here. With many cpus we will make boot a little bit slower. I don't care too much though, so if you still think that 1 is required here I'll make it so.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#38 lore raw

Re: [PATCH v6 04/12] Add memory slot versioning and use it to provide fast guest write interface

In reply to Marcelo Tosatti
Quoted 13 lines · Marcelo Tosatti
Quoted 9 lines · Gleb Natapov
Quoted 9 lines

virt/kvm/kvm_main.c int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data, · line 1260

Quoted 9 lines
virt/kvm/kvm_main.c +9 -0
+int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
+			      gpa_t gpa)
+{
+	struct kvm_memslots *slots = kvm_memslots(kvm);
+	int offset = offset_in_page(gpa);
+	gfn_t gfn = gpa >> PAGE_SHIFT;
+
+	ghc->gpa = gpa;
+	ghc->generation = slots->generation;

kvm->memslots can change here.

Quoted 7 lines
Quoted 2 lines
Quoted 2 lines

virt/kvm/kvm_main.c int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data, · line 1262

Quoted 2 lines
virt/kvm/kvm_main.c +2 -0
+	ghc->memslot = gfn_to_memslot(kvm, gfn);
+	ghc->hva = gfn_to_hva(kvm, gfn);

And if so, gfn_to_memslot / gfn_to_hva will use new memslots pointer.

Should dereference all values from one copy of kvm->memslots pointer.

Ah, I see now. Thanks! Will fix.

Quoted 24 lines
Quoted 15 lines
Quoted 11 lines

virt/kvm/kvm_main.c int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data, · line 1269

Quoted 7 lines
virt/kvm/kvm_main.c +7 -0
+	if (!kvm_is_error_hva(ghc->hva))
+		ghc->hva += offset;
+	else
+		return -EFAULT;
+
+	return 0;
+}

Should use a unique kvm_memslots structure for the cache entry, since it can change in between (use gfn_to_hva_memslot, etc on "slots" pointer).

I do not understand what do you mean here. kvm_memslots structure itself is not cached only various translation that use it are cached. Translation result are never used if kvm_memslots was changed.

Quoted 8 lines
Quoted 3 lines

Also should zap any cached entries on overflow, otherwise malicious userspace could make use of stale slots:

There is only one cached entry at each given time. User who wants to write into guest memory often defines gfn_to_hva_cache variable somewhere. Init it with kvm_gfn_to_hva_cache_init() and then calls kvm_write_guest_cached() on it. If there was no slot changes in between cached translation are used. Otherwise cache is recalculated.

Quoted 4 lines

Malicious userspace can cause entry to be cached, ioctl SET_USER_MEMORY_REGION 2^32 times, generation number will match, mark_page_dirty_in_slot will be called with pointer to freed memory.

Hmm. To zap all cached entires on overflow we need to track them. If we will track then we can zap them on each slot update and drop "generation" entirely.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#10 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Gleb Natapov
Quoted 8 lines · Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

arch/x86/kvm/mmu.c static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva, · line 2595

Quoted 9 lines
arch/x86/kvm/mmu.c +9 -0
+
+static bool can_do_async_pf(struct kvm_vcpu *vcpu)
+{
+	if (unlikely(!irqchip_in_kernel(vcpu->kvm) ||
+		     kvm_event_needs_reinjection(vcpu)))
+		return false;
+
+	return kvm_x86_ops->interrupt_allowed(vcpu);
+}

Strictly speaking, if the cpu can handle NMIs it can take an apf?

arch/x86/kvm/x86.c static int vcpu_enter_guest(struct kvm_vcpu *vcpu) · line 5131

Quoted 11 lines
arch/x86/kvm/x86.c +7 -0
@@ -5112,6 +5122,13 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  	if (unlikely(r))
  		goto out;
 
+	kvm_check_async_pf_completion(vcpu);
+	if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED) {
+		/* Page is swapped out. Do synthetic halt */
+		r = 1;
+		goto out;
+	}
+

Why do it here in the fast path? Can't you halt the cpu when starting the page fault?

I guess the apf threads can't touch mp_state, but they can have a KVM_REQ to trigger the check.

arch/x86/kvm/x86.c int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu) · line 5802

Quoted 9 lines
arch/x86/kvm/x86.c +2 -0
  	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
  		inject_pending_event(vcpu);
 
@@ -5781,6 +5798,9 @@ int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
 
  	kvm_make_request(KVM_REQ_EVENT, vcpu);
 
+	kvm_clear_async_pf_completion_queue(vcpu);
+	memset(vcpu->arch.apf.gfns, 0xff, sizeof vcpu->arch.apf.gfns);

An ordinary for loop is less tricky, even if it means one more line.

arch/x86/kvm/x86.c void kvm_arch_flush_shadow(struct kvm *kvm) · line 6070

Quoted 9 lines
arch/x86/kvm/x86.c +1 -0
@@ -6040,6 +6064,7 @@ void kvm_arch_flush_shadow(struct kvm *kvm)
  int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
  {
  	return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
+		|| !list_empty_careful(&vcpu->async_pf.done)
  		|| vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
  		|| vcpu->arch.nmi_pending ||
  		(kvm_arch_interrupt_allowed(vcpu)&&

Unrelated, shouldn't kvm_arch_vcpu_runnable() look at vcpu->requests? Specifically KVM_REQ_EVENT?

arch/x86/kvm/x86.c void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags) · line 6141

Quoted 6 lines
arch/x86/kvm/x86.c +6 -0
+static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
+{
+	u32 key = kvm_async_pf_hash_fn(gfn);
+
+	while (vcpu->arch.apf.gfns[key] != -1)
+		key = kvm_async_pf_next_probe(key);

Not sure what that -1 converts to on i386 where gfn_t is u64.

Quoted 4 lines
arch/x86/kvm/x86.c +4 -0
+
+void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
+				     struct kvm_async_pf *work)
+{

arch/x86/kvm/x86.c void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags) · line 6199

Quoted 10 lines
arch/x86/kvm/x86.c +10 -0
+	vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
+
+	if (work == kvm_double_apf)
+		trace_kvm_async_pf_doublefault(kvm_rip_read(vcpu));
+	else {
+		trace_kvm_async_pf_not_present(work->gva);
+
+		kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
+	}
+}

Just have vcpu as the argument for tracepoints to avoid unconditional kvm_rip_read (slow on Intel), and call kvm_rip_read() in tp_fast_assign(). Similarly you can pass work instead of work->gva, though that's not nearly as important.

include/trace/events/kvm.h TRACE_EVENT(kvm_age_page, · line 208

Quoted 5 lines
include/trace/events/kvm.h +5 -0
+
+TRACE_EVENT(
+	kvm_async_pf_not_present,
+	TP_PROTO(u64 gva),
+	TP_ARGS(gva),

Do you actually have a gva with tdp? With nested virtualization, how do you interpret this gva?

include/trace/events/kvm.h TRACE_EVENT(kvm_age_page, · line 240

Quoted 5 lines
include/trace/events/kvm.h +5 -0
+
+TRACE_EVENT(
+	kvm_async_pf_completed,
+	TP_PROTO(unsigned long address, struct page *page, u64 gva),
+	TP_ARGS(address, page, gva),

What does address mean? There's also gva?

include/trace/events/kvm.h TRACE_EVENT(kvm_age_page, · line 252

Quoted 12 lines
include/trace/events/kvm.h +12 -0
+
+	TP_STRUCT__entry(
+		__field(unsigned long, address)
+		__field(struct page*, page)
+		__field(u64, gva)
+		),
+
+	TP_fast_assign(
+		__entry->address = address;
+		__entry->page = page;
+		__entry->gva = gva;
+		),

Recording a struct page * in a tracepoint? Userspace can read this entry, better to the page_to_pfn() here.

virt/kvm/async_pf.c line 105

Quoted 12 lines
virt/kvm/async_pf.c new file +12 -0
+void kvm_clear_async_pf_completion_queue(struct kvm_vcpu *vcpu)
+{
+	/* cancel outstanding work queue item */
+	while (!list_empty(&vcpu->async_pf.queue)) {
+		struct kvm_async_pf *work =
+			list_entry(vcpu->async_pf.queue.next,
+				   typeof(*work), queue);
+		cancel_work_sync(&work->work);
+		list_del(&work->queue);
+		if (!work->page) /* work was canceled */
+			kmem_cache_free(async_pf_cache, work);
+	}

Are you holding any lock here?

If not, what protects vcpu->async_pf.queue?
If yes, cancel_work_sync() will need to aquire it too (in case work is running now and needs to take the lock, and cacncel_work_sync() needs to wait for it) -> deadlock.

virt/kvm/async_pf.c line 168

Quoted 3 lines
virt/kvm/async_pf.c new file +3 -0
+
+	/* do alloc nowait since if we are going to sleep anyway we
+	   may as well sleep faulting in page */

/*
* multi
* line
* comment
*/

(but a good one, this is subtle)

I missed where you halt the vcpu. Can you point me at the function?

Note this is a synthetic halt and must not be visible to live migration, or we risk live migrating a halted state which doesn't really exist.

Might be simplest to drain the apf queue on any of the save/restore ioctls.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#11 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

Quoted 2 lines · Avi Kivity

I missed where you halt the vcpu. Can you point me at the function?

Found it.

Multiplexing a guest state with a host state is a bad idea. Better have separate state.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#7 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Gleb Natapov
Quoted 62 lines · Gleb Natapov
Quoted 61 lines · Avi Kivity
Quoted 60 lines · Marcelo Tosatti
Quoted 58 lines · Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

---

   arch/x86/include/asm/kvm_host.h |   17 +++
   arch/x86/kvm/Kconfig            |    1 +
   arch/x86/kvm/Makefile           |    1 +
   arch/x86/kvm/mmu.c              |   51 +++++++++-
   arch/x86/kvm/paging_tmpl.h      |    4 +-
   arch/x86/kvm/x86.c              |  109 +++++++++++++++++++-
   include/linux/kvm_host.h        |   31 ++++++
   include/trace/events/kvm.h      |   88 ++++++++++++++++
   virt/kvm/Kconfig                |    3 +
   virt/kvm/async_pf.c             |  220 +++++++++++++++++++++++++++++++++++++++
   virt/kvm/async_pf.h             |   36 +++++++
   virt/kvm/kvm_main.c             |   57 ++++++++--
   12 files changed, 603 insertions(+), 15 deletions(-)

create mode 100644 virt/kvm/async_pf.c
create mode 100644 virt/kvm/async_pf.h

  +	async_pf_cache = NULL;
  +}
  +
  +void kvm_async_pf_vcpu_init(struct kvm_vcpu *vcpu)
  +{
  +	INIT_LIST_HEAD(&vcpu->async_pf.done);
  +	INIT_LIST_HEAD(&vcpu->async_pf.queue);
  +	spin_lock_init(&vcpu->async_pf.lock);
  +}
  +
  +static void async_pf_execute(struct work_struct *work)
  +{
  +	struct page *page;
  +	struct kvm_async_pf *apf =
  +		container_of(work, struct kvm_async_pf, work);
  +	struct mm_struct *mm = apf->mm;
  +	struct kvm_vcpu *vcpu = apf->vcpu;
  +	unsigned long addr = apf->addr;
  +	gva_t gva = apf->gva;
  +
  +	might_sleep();
  +
  +	use_mm(mm);
  +	down_read(&mm->mmap_sem);
  +	get_user_pages(current, mm, addr, 1, 1, 0,&page, NULL);
  +	up_read(&mm->mmap_sem);
  +	unuse_mm(mm);
  +
  +	spin_lock(&vcpu->async_pf.lock);
  +	list_add_tail(&apf->link,&vcpu->async_pf.done);
  +	apf->page = page;
  +	spin_unlock(&vcpu->async_pf.lock);
Quoted 8 lines
Quoted 5 lines
Quoted 1 line

This can fail, and apf->page become NULL.

Does it even become NULL? On error, get_user_pages() won't update the pages argument, so page becomes garbage here.

apf is allocated with kmem_cache_zalloc() and ->page is set to NULL in kvm_setup_async_pf() to be extra sure.

But you assign apf->page = page;, overriding it with garbage here.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#39 lore raw

Re: [PATCH v6 04/12] Add memory slot versioning and use it to provide fast guest write interface

In reply to Gleb Natapov
Quoted 7 lines · Gleb Natapov
Quoted 4 lines

Malicious userspace can cause entry to be cached, ioctl SET_USER_MEMORY_REGION 2^32 times, generation number will match, mark_page_dirty_in_slot will be called with pointer to freed memory.

Hmm. To zap all cached entires on overflow we need to track them. If we will track then we can zap them on each slot update and drop "generation" entirely.

To track them you need locking.

Isn't SET_USER_MEMORY_REGION so slow that calling it 2^32 times isn't really feasible?

In any case, can use u64 generation count.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#29 lore raw

Re: [PATCH v6 03/12] Retry fault before vmentry

In reply to Gleb Natapov
Quoted 6 lines · Gleb Natapov

When page is swapped in it is mapped into guest memory only after guest tries to access it again and generate another fault. To save this fault we can map it immediately since we know that guest is going to access the page. Do it only when tdp is enabled for now. Shadow paging case is more complicated. CR[034] and EFER registers should be switched before doing mapping and then switched back.

With non-pv apf, I don't think we can do shadow paging. The guest isn't aware of the apf, so as far as it is concerned it is allowed to kill the process and replace it with something else:

guest process x: apf
kvm: timer intr
guest kernel: context switch
very fast guest admin: pkill -9 x
guest kernel: destroy x's cr3
guest kernel: reuse x's cr3 for new process y
kvm: retry fault, instantiating x's page in y's page table

Even with tdp, we have the same case for nnpt (just s/kernel/hypervisor/ and s/process/guest/). What we really need is to only instantiate the page for direct maps, which are independent of the guest.

Could be done like this:

- at apf time, walk shadow mmu
- if !sp->role.direct, abort
- take reference to sp
- on apf completion, instantiate spte in sp

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#45 lore raw

Re: [PATCH v6 04/12] Add memory slot versioning and use it to provide fast guest write interface

In reply to Gleb Natapov
Quoted 4 lines · Gleb Natapov

Keep track of memslots changes by keeping generation number in memslots structure. Provide kvm_write_guest_cached() function that skips gfn_to_hva() translation if memslots was not changed since previous invocation.

btw, this patch (and patch 5, and perhaps more) can be applied independently. If you like, you can submit them before the patch set is complete to reduce your queue length.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#48 lore raw

Re: [PATCH v6 06/12] Add PV MSR to enable asynchronous page faults delivery.

In reply to Gleb Natapov

Documentation/kvm/msr.txt MSR_KVM_SYSTEM_TIME: 0x12 · line 155

Quoted 6 lines · Gleb Natapov

Guest enables async PF vcpu functionality using this MSR.

return NON_PRESENT;

Documentation/kvm/msr.txt +3 -0
+
+MSR_KVM_ASYNC_PF_EN: 0x4b564d02
+	data: Bits 63-6 hold 64-byte aligned physical address of a 32bit memory

Given that it must be aligned anyway, we can require it to be a 64-byte region and also require that the guest zero it before writing the MSR. That will give us a little more flexibility in the future.

Quoted 72 lines
Documentation/kvm/msr.txt +9 -0
+	area which must be in guest RAM. Bits 5-1 are reserved and should be
+	zero. Bit 0 is 1 when asynchronous page faults are enabled on the vcpu
+	0 when disabled.
+
+	Physical address points to 32 bit memory location that will be written
+	to by the hypervisor at the time of asynchronous page fault injection to
+	indicate type of asynchronous page fault. Value of 1 means that the page
+	referred to by the page fault is not present. Value 2 means that the
+	page is now available.
arch/x86/include/asm/kvm_host.h +2 -0
index b9f263e..de31551 100644
@@ -417,6 +417,8 @@ struct kvm_vcpu_arch {
 
  	struct {
  		gfn_t gfns[roundup_pow_of_two(ASYNC_PF_PER_VCPU)];
+		struct gfn_to_hva_cache data;
+		u64 msr_val;
  	} apf;
  };
 
arch/x86/include/asm/kvm_para.h +4 -0
index e3faaaf..8662ae0 100644
@@ -20,6 +20,7 @@
   * are available. The use of 0x11 and 0x12 is deprecated
   */
  #define KVM_FEATURE_CLOCKSOURCE2        3
+#define KVM_FEATURE_ASYNC_PF		4
 
  /* The last 8 bits are used to indicate how to interpret the flags field
   * in pvclock structure. If no bits are set, all flags are ignored.
@@ -32,9 +33,12 @@
  /* Custom MSRs falls in the range 0x4b564d00-0x4b564dff */
  #define MSR_KVM_WALL_CLOCK_NEW  0x4b564d00
  #define MSR_KVM_SYSTEM_TIME_NEW 0x4b564d01
+#define MSR_KVM_ASYNC_PF_EN 0x4b564d02
 
  #define KVM_MAX_MMU_OP_BATCH           32
 
+#define KVM_ASYNC_PF_ENABLED			(1<<  0)
+
  /* Operations for KVM_HC_MMU_OP */
  #define KVM_MMU_OP_WRITE_PTE            1
  #define KVM_MMU_OP_FLUSH_TLB	        2
arch/x86/kvm/x86.c +4 -2
index 48fd59d..3e123ab 100644
@@ -782,12 +782,12 @@ EXPORT_SYMBOL_GPL(kvm_get_dr);
   * kvm-specific. Those are put in the beginning of the list.
   */
 
-#define KVM_SAVE_MSRS_BEGIN	7
+#define KVM_SAVE_MSRS_BEGIN	8
  static u32 msrs_to_save[] = {
  	MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
  	MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
  	HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
-	HV_X64_MSR_APIC_ASSIST_PAGE,
+	HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN,
  	MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
  	MSR_STAR,
  #ifdef CONFIG_X86_64
@@ -1425,6 +1425,29 @@ static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
  	return 0;
  }
 
+static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
+{

arch/x86/kvm/x86.c static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data) · line 1439

Quoted 10 lines
arch/x86/kvm/x86.c +10 -0
+	gpa_t gpa = data&  ~0x3f;
+
+	/* Bits 1:5 are resrved, Should be zero */
+	if (data&  0x3e)
+		return 1;
+
+	vcpu->arch.apf.msr_val = data;
+
+	if (!(data&  KVM_ASYNC_PF_ENABLED)) {
+		kvm_clear_async_pf_completion_queue(vcpu);

May be a lengthy synchronous operation. I guess we don't care.

arch/x86/kvm/x86.c static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data) · line 1440

Quoted 1 line
arch/x86/kvm/x86.c +1 -0
+		memset(vcpu->arch.apf.gfns, 0xff, sizeof vcpu->arch.apf.gfns);

That memset again.

arch/x86/kvm/x86.c static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data) · line 1445

Quoted 5 lines
arch/x86/kvm/x86.c +5 -0
+		return 0;
+	}
+
+	if (kvm_gfn_to_hva_cache_init(vcpu->kvm,&vcpu->arch.apf.data, gpa))
+		return 1;

Note: we need to handle the memory being removed from underneath kvm_gfn_to_hve_cache(). Given that, we can just make kvm_gfn_to_hva_cache_init() return void. "success" means nothing when future changes can invalidate it.

arch/x86/kvm/x86.c static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data) · line 1447

Quoted 2 lines
arch/x86/kvm/x86.c +2 -0
+
+	kvm_async_pf_wakeup_all(vcpu);

Why is this needed? If all apfs are flushed at disable time, what do we need to wake up?

Need to list the MSR for save/restore/reset.

Signature · 2 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.
#61 lore raw

Re: [PATCH v6 07/12] Add async PF initialization to PV guest.

In reply to Gleb Natapov

arch/x86/kernel/kvm.c static void __init paravirt_ops_setup(void)

Quoted 13 lines · Gleb Natapov

Enable async PF in a guest if async PF capability is discovered.

arch/x86/kernel/kvm.c +10 -0
+void __cpuinit kvm_guest_cpu_init(void)
+{
+	if (!kvm_para_available())
+		return;
+
+	if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF)&&  kvmapf) {
+		u64 pa = __pa(&__get_cpu_var(apf_reason));
+
+		if (native_write_msr_safe(MSR_KVM_ASYNC_PF_EN,
+					  pa | KVM_ASYNC_PF_ENABLED, pa>>  32))

native_ versions of processor accessors shouldn't be used generally.

Also, the MSR isn't documented to fail on valid input, so you can use a normal wrmsrl() here.

Quoted 9 lines
arch/x86/kernel/kvm.c +8 -0
+			return;
+		__get_cpu_var(apf_reason).enabled = 1;
+		printk(KERN_INFO"KVM setup async PF for cpu %d\n",
+		       smp_processor_id());
+	}
+}
+
 
+static int kvm_pv_reboot_notify(struct notifier_block *nb,

arch/x86/kernel/kvm.c static void __init paravirt_ops_setup(void) · line 287

Quoted 10 lines
arch/x86/kernel/kvm.c +10 -0
+				unsigned long code, void *unused)
+{
+	if (code == SYS_RESTART)
+		on_each_cpu(kvm_pv_disable_apf, NULL, 1);
+	return NOTIFY_DONE;
+}
+
+static struct notifier_block kvm_pv_reboot_nb = {
+	.notifier_call = kvm_pv_reboot_notify,
+};

Does this handle kexec?

arch/x86/kernel/kvm.c static void __init paravirt_ops_setup(void) · line 303

Quoted 8 lines
arch/x86/kernel/kvm.c +8 -0
+
+static void kvm_guest_cpu_notify(void *dummy)
+{
+	if (!dummy)
+		kvm_guest_cpu_init();
+	else
+		kvm_pv_disable_apf(NULL);
+}

Why are you making decisions based on a dummy input?

The whole thing looks strange. Use two functions?

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#52 lore raw

Re: [PATCH v6 06/12] Add PV MSR to enable asynchronous page faults delivery.

In reply to Gleb Natapov

Documentation/kvm/msr.txt MSR_KVM_SYSTEM_TIME: 0x12 · line 164

Quoted 6 lines · Gleb Natapov
Documentation/kvm/msr.txt +6 -0
+
+	Physical address points to 32 bit memory location that will be written
+	to by the hypervisor at the time of asynchronous page fault injection to
+	indicate type of asynchronous page fault. Value of 1 means that the page
+	referred to by the page fault is not present. Value 2 means that the
+	page is now available.

"The must not enable interrupts before the reason is read, or it may be overwritten by another apf".

Document the fact that disabling interrupts disables APFs.

How does the guest distinguish betweem APFs and ordinary page faults?

What's the role of cr2?

When disabling APF, all pending APFs are flushed and may or may not get a completion.

Is a "page available" notification guaranteed to arrive on the same vcpu that took the "page not present" fault?

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#65 lore raw

Re: [PATCH v6 08/12] Handle async PF in a guest.

In reply to Gleb Natapov
Quoted 6 lines · Gleb Natapov

When async PF capability is detected hook up special page fault handler that will handle async page fault events and bypass other page faults to regular page fault handler. Also add async PF handling to nested SVM emulation. Async PF always generates exit to L1 where vcpu thread will be scheduled out until page is available.

Please separate guest and host changes.

Quoted 18 lines
arch/x86/kernel/kvm.c +18 -0
+void kvm_async_pf_task_wait(u32 token)
+{
+	u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS);
+	struct kvm_task_sleep_head *b =&async_pf_sleepers[key];
+	struct kvm_task_sleep_node n, *e;
+	DEFINE_WAIT(wait);
+
+	spin_lock(&b->lock);
+	e = _find_apf_task(b, token);
+	if (e) {
+		/* dummy entry exist ->  wake up was delivered ahead of PF */
+		hlist_del(&e->link);
+		kfree(e);
+		spin_unlock(&b->lock);
+		return;
+	}
+
+	n.token = token;

arch/x86/kernel/kvm.c static void kvm_io_delay(void) · line 130

Quoted 10 lines
arch/x86/kernel/kvm.c +10 -0
+	n.cpu = smp_processor_id();
+	init_waitqueue_head(&n.wq);
+	hlist_add_head(&n.link,&b->list);
+	spin_unlock(&b->lock);
+
+	for (;;) {
+		prepare_to_wait(&n.wq,&wait, TASK_UNINTERRUPTIBLE);
+		if (hlist_unhashed(&n.link))
+			break;
+		local_irq_enable();

Suppose we take another apf here. And another, and another (for different pages, while executing schedule()). What's to prevent kernel stack overflow?

arch/x86/kernel/kvm.c static void kvm_io_delay(void) · line 139

Quoted 9 lines
arch/x86/kernel/kvm.c +9 -0
+		schedule();
+		local_irq_disable();
+	}
+	finish_wait(&n.wq,&wait);
+
+	return;
+}
+EXPORT_SYMBOL_GPL(kvm_async_pf_task_wait);
+

I have a truly marvellous patch that fixes the bug which this signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#12 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Avi Kivity
Quoted 10 lines · Avi Kivity

arch/x86/kvm/mmu.c static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva, · line 2595

Quoted 8 lines
arch/x86/kvm/mmu.c +8 -0
+static bool can_do_async_pf(struct kvm_vcpu *vcpu)
+{
+ if (unlikely(!irqchip_in_kernel(vcpu->kvm) ||
+ kvm_event_needs_reinjection(vcpu)))
+ return false;
+
+ return kvm_x86_ops->interrupt_allowed(vcpu);
+}

Strictly speaking, if the cpu can handle NMIs it can take an apf?

Strictly speaking, yes.

However, it may not be able to DO anything with it, since it won't be able to reschedule the context it's running :)

Signature · 7 lines
All rights reversed

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#13 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

Quoted 13 lines · Rik van Riel
Quoted 10 lines · Avi Kivity

arch/x86/kvm/mmu.c static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva, · line 2595

Quoted 8 lines
arch/x86/kvm/mmu.c +8 -0
+static bool can_do_async_pf(struct kvm_vcpu *vcpu)
+{
+ if (unlikely(!irqchip_in_kernel(vcpu->kvm) ||
+ kvm_event_needs_reinjection(vcpu)))
+ return false;
+
+ return kvm_x86_ops->interrupt_allowed(vcpu);
+}

Strictly speaking, if the cpu can handle NMIs it can take an apf?

Quoted 5 lines

Strictly speaking, yes.

However, it may not be able to DO anything with it, since it won't be able to reschedule the context it's running :)

I was thinking about keeping the watchdog nmi handler responsive.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#85 lore raw

Re: [PATCH v6 11/12] Let host know whether the guest can handle async PF in non-userspace context.

In reply to Gleb Natapov
Quoted 8 lines · Gleb Natapov

If guest can detect that it runs in non-preemptable context it can handle async PFs at any time, so let host know that it can send async PF even if guest cpu is not in userspace.

MSR_KVM_ASYNC_PF_EN: 0x4b564d02
data: Bits 63-6 hold 64-byte aligned physical address of a 32bit memory

Documentation/kvm/msr.txt MSR_KVM_SYSTEM_TIME: 0x12 · line 159

Quoted 6 lines
Documentation/kvm/msr.txt +3 -2
-	area which must be in guest RAM. Bits 5-1 are reserved and should be
+	area which must be in guest RAM. Bits 5-2 are reserved and should be
  	zero. Bit 0 is 1 when asynchronous page faults are enabled on the vcpu
-	0 when disabled.
+	0 when disabled. Bit 2 is 1 if asynchronous page faults can be injected
+	when vcpu is in kernel mode.

Please use cpl instead of user mode and kernel mode. The original terms are ambiguous for cpl ==1 || cpl == 2.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#40 lore raw

Re: [PATCH v6 04/12] Add memory slot versioning and use it to provide fast guest write interface

In reply to Avi Kivity
Quoted 5 lines · Avi Kivity
Quoted 4 lines · Gleb Natapov
Quoted 4 lines

Malicious userspace can cause entry to be cached, ioctl SET_USER_MEMORY_REGION 2^32 times, generation number will match, mark_page_dirty_in_slot will be called with pointer to freed memory.

Quoted 8 lines
Quoted 3 lines

Hmm. To zap all cached entires on overflow we need to track them. If we will track then we can zap them on each slot update and drop "generation" entirely.

To track them you need locking.

Isn't SET_USER_MEMORY_REGION so slow that calling it 2^32 times isn't really feasible?

Assuming it takes 1ms, it would take 49 days.

Quoted 1 line

In any case, can use u64 generation count.

Agree.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#41 lore raw

Re: [PATCH v6 04/12] Add memory slot versioning and use it to provide fast guest write interface

Quoted 10 lines · Marcelo Tosatti
Quoted 9 lines · Avi Kivity
Quoted 7 lines · Gleb Natapov
Quoted 4 lines

Malicious userspace can cause entry to be cached, ioctl SET_USER_MEMORY_REGION 2^32 times, generation number will match, mark_page_dirty_in_slot will be called with pointer to freed memory.

Hmm. To zap all cached entires on overflow we need to track them. If we will track then we can zap them on each slot update and drop "generation" entirely.

Quoted 7 lines
Quoted 4 lines

To track them you need locking.

Isn't SET_USER_MEMORY_REGION so slow that calling it 2^32 times isn't really feasible?

Assuming it takes 1ms, it would take 49 days.

We may fail ioctl when max value is reached. The question is how much slot changes can we expect from real guest during its lifetime.

Quoted 3 lines
Quoted 1 line

In any case, can use u64 generation count.

Agree.

Yes, 64 bit ought to be enough for anybody.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#42 lore raw

Re: [PATCH v6 04/12] Add memory slot versioning and use it to provide fast guest write interface

Quoted 9 lines · Gleb Natapov
Quoted 6 lines
Quoted 3 lines

Isn't SET_USER_MEMORY_REGION so slow that calling it 2^32 times isn't really feasible?

Assuming it takes 1ms, it would take 49 days.

We may fail ioctl when max value is reached. The question is how much slot changes can we expect from real guest during its lifetime.

A normal guest has a 30 Hz timer for reading the vga framebuffer, multiple slots. Let's assume 100 Hz frequency, that gives 490 days until things stop working.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#66 lore raw

Re: [PATCH v6 08/12] Handle async PF in a guest.

In reply to Avi Kivity
Quoted 34 lines · Avi Kivity
Quoted 6 lines · Gleb Natapov

When async PF capability is detected hook up special page fault handler that will handle async page fault events and bypass other page faults to regular page fault handler. Also add async PF handling to nested SVM emulation. Async PF always generates exit to L1 where vcpu thread will be scheduled out until page is available.

Please separate guest and host changes.

Quoted 24 lines
arch/x86/kernel/kvm.c +24 -0
+void kvm_async_pf_task_wait(u32 token)
+{
+	u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS);
+	struct kvm_task_sleep_head *b =&async_pf_sleepers[key];
+	struct kvm_task_sleep_node n, *e;
+	DEFINE_WAIT(wait);
+
+	spin_lock(&b->lock);
+	e = _find_apf_task(b, token);
+	if (e) {
+		/* dummy entry exist ->  wake up was delivered ahead of PF */
+		hlist_del(&e->link);
+		kfree(e);
+		spin_unlock(&b->lock);
+		return;
+	}
+
+	n.token = token;
+	n.cpu = smp_processor_id();
+	init_waitqueue_head(&n.wq);
+	hlist_add_head(&n.link,&b->list);
+	spin_unlock(&b->lock);
+
+	for (;;) {
Quoted 9 lines

arch/x86/kernel/kvm.c static void kvm_io_delay(void) · line 130

Quoted 4 lines
arch/x86/kernel/kvm.c +4 -0
+		prepare_to_wait(&n.wq,&wait, TASK_UNINTERRUPTIBLE);
+		if (hlist_unhashed(&n.link))
+			break;
+		local_irq_enable();

Suppose we take another apf here. And another, and another (for different pages, while executing schedule()). What's to prevent kernel stack overflow?

Host side keeps track of outstanding apfs and will not send apf for the same phys address twice. It will halt vcpu instead.

Quoted 11 lines

arch/x86/kernel/kvm.c static void kvm_io_delay(void) · line 139

Quoted 9 lines
arch/x86/kernel/kvm.c +9 -0
+		schedule();
+		local_irq_disable();
+	}
+	finish_wait(&n.wq,&wait);
+
+	return;
+}
+EXPORT_SYMBOL_GPL(kvm_async_pf_task_wait);
+

I have a truly marvellous patch that fixes the bug which this signature is too narrow to contain.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#67 lore raw

Re: [PATCH v6 08/12] Handle async PF in a guest.

Quoted 40 lines · Gleb Natapov
Quoted 39 lines · Avi Kivity
Quoted 6 lines · Gleb Natapov

When async PF capability is detected hook up special page fault handler that will handle async page fault events and bypass other page faults to regular page fault handler. Also add async PF handling to nested SVM emulation. Async PF always generates exit to L1 where vcpu thread will be scheduled out until page is available.

Please separate guest and host changes.

Quoted 28 lines
arch/x86/kernel/kvm.c +28 -0
+void kvm_async_pf_task_wait(u32 token)
+{
+	u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS);
+	struct kvm_task_sleep_head *b =&async_pf_sleepers[key];
+	struct kvm_task_sleep_node n, *e;
+	DEFINE_WAIT(wait);
+
+	spin_lock(&b->lock);
+	e = _find_apf_task(b, token);
+	if (e) {
+		/* dummy entry exist ->   wake up was delivered ahead of PF */
+		hlist_del(&e->link);
+		kfree(e);
+		spin_unlock(&b->lock);
+		return;
+	}
+
+	n.token = token;
+	n.cpu = smp_processor_id();
+	init_waitqueue_head(&n.wq);
+	hlist_add_head(&n.link,&b->list);
+	spin_unlock(&b->lock);
+
+	for (;;) {
+		prepare_to_wait(&n.wq,&wait, TASK_UNINTERRUPTIBLE);
+		if (hlist_unhashed(&n.link))
+			break;
+		local_irq_enable();
Quoted 6 lines
Quoted 4 lines

Suppose we take another apf here. And another, and another (for different pages, while executing schedule()). What's to prevent kernel stack overflow?

Host side keeps track of outstanding apfs and will not send apf for the same phys address twice. It will halt vcpu instead.

What about different pages, running the scheduler code?

Oh, and we'll run the scheduler recursively.

Signature · 2 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.
#30 lore raw

Re: [PATCH v6 03/12] Retry fault before vmentry

In reply to Avi Kivity
Quoted 9 lines · Avi Kivity
Quoted 6 lines · Gleb Natapov

When page is swapped in it is mapped into guest memory only after guest tries to access it again and generate another fault. To save this fault we can map it immediately since we know that guest is going to access the page. Do it only when tdp is enabled for now. Shadow paging case is more complicated. CR[034] and EFER registers should be switched before doing mapping and then switched back.

With non-pv apf, I don't think we can do shadow paging. The guest

Yes, with non-pv this trick will not work without tdp. I haven't even considered it for that case.

Quoted 16 lines

isn't aware of the apf, so as far as it is concerned it is allowed to kill the process and replace it with something else:

guest process x: apf
kvm: timer intr
guest kernel: context switch
very fast guest admin: pkill -9 x
guest kernel: destroy x's cr3
guest kernel: reuse x's cr3 for new process y
kvm: retry fault, instantiating x's page in y's page table

Even with tdp, we have the same case for nnpt (just s/kernel/hypervisor/ and s/process/guest/). What we really need is to only instantiate the page for direct maps, which are independent of the guest.

Quoted 10 lines

Could be done like this:

- at apf time, walk shadow mmu
- if !sp->role.direct, abort
- take reference to sp
- on apf completion, instantiate spte in sp

Signature · 2 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#43 lore raw

Re: [PATCH v6 04/12] Add memory slot versioning and use it to provide fast guest write interface

In reply to Avi Kivity
Quoted 7 lines · Avi Kivity
Quoted 6 lines · Gleb Natapov
Quoted 6 lines
Quoted 3 lines

Isn't SET_USER_MEMORY_REGION so slow that calling it 2^32 times isn't really feasible?

Assuming it takes 1ms, it would take 49 days.

Quoted 8 lines
Quoted 3 lines

We may fail ioctl when max value is reached. The question is how much slot changes can we expect from real guest during its lifetime.

A normal guest has a 30 Hz timer for reading the vga framebuffer, multiple slots. Let's assume 100 Hz frequency, that gives 490 days until things stop working.

And reading vga framebuffer needs slots changes because of dirty map tracking?

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#14 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Avi Kivity
Quoted 9 lines · Avi Kivity
Quoted 8 lines · Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

Quoted 12 lines

arch/x86/kvm/mmu.c static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva, · line 2595

Quoted 9 lines
arch/x86/kvm/mmu.c +9 -0
+
+static bool can_do_async_pf(struct kvm_vcpu *vcpu)
+{
+	if (unlikely(!irqchip_in_kernel(vcpu->kvm) ||
+		     kvm_event_needs_reinjection(vcpu)))
+		return false;
+
+	return kvm_x86_ops->interrupt_allowed(vcpu);
+}

Strictly speaking, if the cpu can handle NMIs it can take an apf?

We can always do apf, but if vcpu can't do anything hwy bother. For NMI watchdog yes, may be it is worth to allow apf if nmi is allowed.

Quoted 4 lines
Quoted 4 lines
arch/x86/kvm/x86.c +0 -0
@@ -5112,6 +5122,13 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 	if (unlikely(r))
 		goto out;
 
Quoted 10 lines

arch/x86/kvm/x86.c static int vcpu_enter_guest(struct kvm_vcpu *vcpu) · line 5131

Quoted 7 lines
arch/x86/kvm/x86.c +7 -0
+	kvm_check_async_pf_completion(vcpu);
+	if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED) {
+		/* Page is swapped out. Do synthetic halt */
+		r = 1;
+		goto out;
+	}
+

Why do it here in the fast path? Can't you halt the cpu when starting the page fault?

Page fault may complete before guest re-entry. We do not want to halt vcpu in this case.

Quoted 3 lines

I guess the apf threads can't touch mp_state, but they can have a KVM_REQ to trigger the check.

This will require KVM_REQ check on fast path, so what's the difference performance wise.

Quoted 14 lines

arch/x86/kvm/x86.c int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu) · line 5802

Quoted 10 lines
arch/x86/kvm/x86.c +2 -0
 	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
 		inject_pending_event(vcpu);
 
@@ -5781,6 +5798,9 @@ int kvm_arch_vcpu_reset(struct kvm_vcpu *vcpu)
 
 	kvm_make_request(KVM_REQ_EVENT, vcpu);
 
+	kvm_clear_async_pf_completion_queue(vcpu);
+	memset(vcpu->arch.apf.gfns, 0xff, sizeof vcpu->arch.apf.gfns);

An ordinary for loop is less tricky, even if it means one more line.

Quoted 1 line
Quoted 11 lines

arch/x86/kvm/x86.c void kvm_arch_flush_shadow(struct kvm *kvm) · line 6070

Quoted 8 lines
arch/x86/kvm/x86.c +1 -0
@@ -6040,6 +6064,7 @@ void kvm_arch_flush_shadow(struct kvm *kvm)
 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
 {
 	return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
+		|| !list_empty_careful(&vcpu->async_pf.done)
 		|| vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
 		|| vcpu->arch.nmi_pending ||
 		(kvm_arch_interrupt_allowed(vcpu)&&

Unrelated, shouldn't kvm_arch_vcpu_runnable() look at vcpu->requests? Specifically KVM_REQ_EVENT?

I think KVM_REQ_EVENT is covered by checking nmi and interrupt queue here.

Quoted 9 lines

arch/x86/kvm/x86.c void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags) · line 6141

Quoted 7 lines
arch/x86/kvm/x86.c +6 -0
+static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
+{
+	u32 key = kvm_async_pf_hash_fn(gfn);
+
+	while (vcpu->arch.apf.gfns[key] != -1)
+		key = kvm_async_pf_next_probe(key);

Not sure what that -1 converts to on i386 where gfn_t is u64.

Will check.

Quoted 11 lines
Quoted 11 lines
arch/x86/kvm/x86.c +11 -0
+
+void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
+				     struct kvm_async_pf *work)
+{
+	vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
+
+	if (work == kvm_double_apf)
+		trace_kvm_async_pf_doublefault(kvm_rip_read(vcpu));
+	else {
+		trace_kvm_async_pf_not_present(work->gva);
+
Quoted 9 lines

arch/x86/kvm/x86.c void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags) · line 6199

Quoted 3 lines
arch/x86/kvm/x86.c +3 -0
+		kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
+	}
+}

Just have vcpu as the argument for tracepoints to avoid unconditional kvm_rip_read (slow on Intel), and call kvm_rip_read() in tp_fast_assign(). Similarly you can pass work instead of work->gva, though that's not nearly as important.

Will do.

Quoted 8 lines

include/trace/events/kvm.h TRACE_EVENT(kvm_age_page, · line 208

Quoted 5 lines
include/trace/events/kvm.h +5 -0
+
+TRACE_EVENT(
+	kvm_async_pf_not_present,
+	TP_PROTO(u64 gva),
+	TP_ARGS(gva),

Do you actually have a gva with tdp? With nested virtualization, how do you interpret this gva?

With tdp it is gpa just like tdp_page_fault gets gpa where shadow page version gets gva. Nested virtualization is too complex to interpret.

Quoted 8 lines

include/trace/events/kvm.h TRACE_EVENT(kvm_age_page, · line 240

Quoted 5 lines
include/trace/events/kvm.h +5 -0
+
+TRACE_EVENT(
+	kvm_async_pf_completed,
+	TP_PROTO(unsigned long address, struct page *page, u64 gva),
+	TP_ARGS(address, page, gva),

What does address mean? There's also gva?

hva.

Quoted 7 lines
Quoted 7 lines
include/trace/events/kvm.h +7 -0
+
+	TP_STRUCT__entry(
+		__field(unsigned long, address)
+		__field(struct page*, page)
+		__field(u64, gva)
+		),
+
Quoted 9 lines

include/trace/events/kvm.h TRACE_EVENT(kvm_age_page, · line 252

Quoted 5 lines
include/trace/events/kvm.h +5 -0
+	TP_fast_assign(
+		__entry->address = address;
+		__entry->page = page;
+		__entry->gva = gva;
+		),

Recording a struct page * in a tracepoint? Userspace can read this entry, better to the page_to_pfn() here.

OK.

Quoted 16 lines

virt/kvm/async_pf.c line 105

Quoted 13 lines
virt/kvm/async_pf.c new file +12 -0
+void kvm_clear_async_pf_completion_queue(struct kvm_vcpu *vcpu)
+{
+	/* cancel outstanding work queue item */
+	while (!list_empty(&vcpu->async_pf.queue)) {
+		struct kvm_async_pf *work =
+			list_entry(vcpu->async_pf.queue.next,
+				   typeof(*work), queue);
+		cancel_work_sync(&work->work);
+		list_del(&work->queue);
+		if (!work->page) /* work was canceled */
+			kmem_cache_free(async_pf_cache, work);
+	}

Are you holding any lock here?

Quoted 1 line

If not, what protects vcpu->async_pf.queue?

Nothing. It is accessed only from vcpu thread.

Quoted 4 lines

If yes, cancel_work_sync() will need to aquire it too (in case work is running now and needs to take the lock, and cacncel_work_sync() needs to wait for it) -> deadlock.

Work never touches this list.

Quoted 11 lines

virt/kvm/async_pf.c line 168

Quoted 3 lines
virt/kvm/async_pf.c new file +3 -0
+
+	/* do alloc nowait since if we are going to sleep anyway we
+	   may as well sleep faulting in page */

/*
* multi
* line
* comment
*/

(but a good one, this is subtle)

Quoted 8 lines

I missed where you halt the vcpu. Can you point me at the function?

Note this is a synthetic halt and must not be visible to live migration, or we risk live migrating a halted state which doesn't really exist.

Might be simplest to drain the apf queue on any of the save/restore ioctls.

So that "info cpu" will interfere with apf? Migration should work in regular way. apf state should not be migrated since it has no meaning on the destination. I'll make sure synthetic halt state will not interfere with migration.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#8 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Avi Kivity
Quoted 65 lines · Avi Kivity
Quoted 64 lines · Gleb Natapov
Quoted 63 lines · Avi Kivity
Quoted 61 lines · Marcelo Tosatti
Quoted 50 lines · Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

---

   arch/x86/include/asm/kvm_host.h |   17 +++
   arch/x86/kvm/Kconfig            |    1 +
   arch/x86/kvm/Makefile           |    1 +
   arch/x86/kvm/mmu.c              |   51 +++++++++-
   arch/x86/kvm/paging_tmpl.h      |    4 +-
   arch/x86/kvm/x86.c              |  109 +++++++++++++++++++-
   include/linux/kvm_host.h        |   31 ++++++
   include/trace/events/kvm.h      |   88 ++++++++++++++++
   virt/kvm/Kconfig                |    3 +
   virt/kvm/async_pf.c             |  220 +++++++++++++++++++++++++++++++++++++++
   virt/kvm/async_pf.h             |   36 +++++++
   virt/kvm/kvm_main.c             |   57 ++++++++--
   12 files changed, 603 insertions(+), 15 deletions(-)

create mode 100644 virt/kvm/async_pf.c
create mode 100644 virt/kvm/async_pf.h

  +	async_pf_cache = NULL;
  +}
  +
  +void kvm_async_pf_vcpu_init(struct kvm_vcpu *vcpu)
  +{
  +	INIT_LIST_HEAD(&vcpu->async_pf.done);
  +	INIT_LIST_HEAD(&vcpu->async_pf.queue);
  +	spin_lock_init(&vcpu->async_pf.lock);
  +}
  +
  +static void async_pf_execute(struct work_struct *work)
  +{
  +	struct page *page;
  +	struct kvm_async_pf *apf =
  +		container_of(work, struct kvm_async_pf, work);
  +	struct mm_struct *mm = apf->mm;
  +	struct kvm_vcpu *vcpu = apf->vcpu;
  +	unsigned long addr = apf->addr;
  +	gva_t gva = apf->gva;
  +
  +	might_sleep();
  +
  +	use_mm(mm);
  +	down_read(&mm->mmap_sem);
Quoted 8 lines
  +	get_user_pages(current, mm, addr, 1, 1, 0,&page, NULL);
  +	up_read(&mm->mmap_sem);
  +	unuse_mm(mm);
  +
  +	spin_lock(&vcpu->async_pf.lock);
  +	list_add_tail(&apf->link,&vcpu->async_pf.done);
  +	apf->page = page;
  +	spin_unlock(&vcpu->async_pf.lock);

This can fail, and apf->page become NULL.

Quoted 9 lines
Quoted 6 lines
Quoted 3 lines

Does it even become NULL? On error, get_user_pages() won't update the pages argument, so page becomes garbage here.

apf is allocated with kmem_cache_zalloc() and ->page is set to NULL in kvm_setup_async_pf() to be extra sure.

But you assign apf->page = page;, overriding it with garbage here.

Ah, right you are.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#68 lore raw

Re: [PATCH v6 08/12] Handle async PF in a guest.

In reply to Avi Kivity
Quoted 8 lines · Avi Kivity
Quoted 2 lines · Gleb Natapov

Host side keeps track of outstanding apfs and will not send apf for the same phys address twice. It will halt vcpu instead.

What about different pages, running the scheduler code?

Oh, and we'll run the scheduler recursively.

When preempt is disabled in the guest, it will not invoke the "reschedule for apf" code, but it will simply turn into a normal page fault.

Last I looked, the scheduler code disabled preempt (for obvious reasons).

Signature · 7 lines
All rights reversed

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#49 lore raw

Re: [PATCH v6 06/12] Add PV MSR to enable asynchronous page faults delivery.

In reply to Avi Kivity
Quoted 13 lines · Avi Kivity

Documentation/kvm/msr.txt MSR_KVM_SYSTEM_TIME: 0x12 · line 155

Quoted 6 lines · Gleb Natapov

Guest enables async PF vcpu functionality using this MSR.

Documentation/kvm/msr.txt +3 -0
 			return NON_PRESENT;
+
+MSR_KVM_ASYNC_PF_EN: 0x4b564d02
+	data: Bits 63-6 hold 64-byte aligned physical address of a 32bit memory

Given that it must be aligned anyway, we can require it to be a 64-byte region and also require that the guest zero it before writing the MSR. That will give us a little more flexibility in the future.

No code change needed, so OK.

Quoted 89 lines
Quoted 72 lines
Documentation/kvm/msr.txt +9 -0
+	area which must be in guest RAM. Bits 5-1 are reserved and should be
+	zero. Bit 0 is 1 when asynchronous page faults are enabled on the vcpu
+	0 when disabled.
+
+	Physical address points to 32 bit memory location that will be written
+	to by the hypervisor at the time of asynchronous page fault injection to
+	indicate type of asynchronous page fault. Value of 1 means that the page
+	referred to by the page fault is not present. Value 2 means that the
+	page is now available.
arch/x86/include/asm/kvm_host.h +2 -0
index b9f263e..de31551 100644
@@ -417,6 +417,8 @@ struct kvm_vcpu_arch {
 
 	struct {
 		gfn_t gfns[roundup_pow_of_two(ASYNC_PF_PER_VCPU)];
+		struct gfn_to_hva_cache data;
+		u64 msr_val;
 	} apf;
 };
 
arch/x86/include/asm/kvm_para.h +4 -0
index e3faaaf..8662ae0 100644
@@ -20,6 +20,7 @@
  * are available. The use of 0x11 and 0x12 is deprecated
  */
 #define KVM_FEATURE_CLOCKSOURCE2        3
+#define KVM_FEATURE_ASYNC_PF		4
 
 /* The last 8 bits are used to indicate how to interpret the flags field
  * in pvclock structure. If no bits are set, all flags are ignored.
@@ -32,9 +33,12 @@
 /* Custom MSRs falls in the range 0x4b564d00-0x4b564dff */
 #define MSR_KVM_WALL_CLOCK_NEW  0x4b564d00
 #define MSR_KVM_SYSTEM_TIME_NEW 0x4b564d01
+#define MSR_KVM_ASYNC_PF_EN 0x4b564d02
 
 #define KVM_MAX_MMU_OP_BATCH           32
 
+#define KVM_ASYNC_PF_ENABLED			(1<<  0)
+
 /* Operations for KVM_HC_MMU_OP */
 #define KVM_MMU_OP_WRITE_PTE            1
 #define KVM_MMU_OP_FLUSH_TLB	        2
arch/x86/kvm/x86.c +4 -2
index 48fd59d..3e123ab 100644
@@ -782,12 +782,12 @@ EXPORT_SYMBOL_GPL(kvm_get_dr);
  * kvm-specific. Those are put in the beginning of the list.
  */
 
-#define KVM_SAVE_MSRS_BEGIN	7
+#define KVM_SAVE_MSRS_BEGIN	8
 static u32 msrs_to_save[] = {
 	MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
 	MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
 	HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
-	HV_X64_MSR_APIC_ASSIST_PAGE,
+	HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN,
 	MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
 	MSR_STAR,
 #ifdef CONFIG_X86_64
@@ -1425,6 +1425,29 @@ static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
 	return 0;
 }
 
+static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
+{

arch/x86/kvm/x86.c static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data) · line 1439

Quoted 10 lines
arch/x86/kvm/x86.c +10 -0
+	gpa_t gpa = data&  ~0x3f;
+
+	/* Bits 1:5 are resrved, Should be zero */
+	if (data&  0x3e)
+		return 1;
+
+	vcpu->arch.apf.msr_val = data;
+
+	if (!(data&  KVM_ASYNC_PF_ENABLED)) {
+		kvm_clear_async_pf_completion_queue(vcpu);

May be a lengthy synchronous operation. I guess we don't care.

arch/x86/kvm/x86.c static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data) · line 1440

Quoted 1 line
arch/x86/kvm/x86.c +1 -0
+		memset(vcpu->arch.apf.gfns, 0xff, sizeof vcpu->arch.apf.gfns);

That memset again.

Quoted 11 lines

arch/x86/kvm/x86.c static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data) · line 1445

Quoted 5 lines
arch/x86/kvm/x86.c +5 -0
+		return 0;
+	}
+
+	if (kvm_gfn_to_hva_cache_init(vcpu->kvm,&vcpu->arch.apf.data, gpa))
+		return 1;

Note: we need to handle the memory being removed from underneath kvm_gfn_to_hve_cache(). Given that, we can just make kvm_gfn_to_hva_cache_init() return void. "success" means nothing when future changes can invalidate it.

I want to catch guest doing stupid things. If guest give us non-existent address I want wrmsr to #GP.

Quoted 5 lines

arch/x86/kvm/x86.c static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data) · line 1447

Quoted 2 lines
arch/x86/kvm/x86.c +2 -0
+
+	kvm_async_pf_wakeup_all(vcpu);

Why is this needed? If all apfs are flushed at disable time, what do we need to wake up?

For migration. Destination will rewrite msr and all processes will be waked up.

Quoted 4 lines

Need to list the MSR for save/restore/reset.

This patch adds it to msrs_to_save, no?

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#53 lore raw

Re: [PATCH v6 06/12] Add PV MSR to enable asynchronous page faults delivery.

In reply to Avi Kivity
Quoted 15 lines · Avi Kivity

Documentation/kvm/msr.txt MSR_KVM_SYSTEM_TIME: 0x12 · line 164

Quoted 6 lines · Gleb Natapov
Documentation/kvm/msr.txt +6 -0
+
+	Physical address points to 32 bit memory location that will be written
+	to by the hypervisor at the time of asynchronous page fault injection to
+	indicate type of asynchronous page fault. Value of 1 means that the page
+	referred to by the page fault is not present. Value 2 means that the
+	page is now available.

"The must not enable interrupts before the reason is read, or it may be overwritten by another apf".

Document the fact that disabling interrupts disables APFs.

How does the guest distinguish betweem APFs and ordinary page faults?

Quoted 8 lines

What's the role of cr2?

When disabling APF, all pending APFs are flushed and may or may not get a completion.

Is a "page available" notification guaranteed to arrive on the same vcpu that took the "page not present" fault?

You mean documentation is lacking? :)

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#69 lore raw

Re: [PATCH v6 08/12] Handle async PF in a guest.

In reply to Avi Kivity
Quoted 41 lines · Avi Kivity
Quoted 40 lines · Gleb Natapov
Quoted 39 lines · Avi Kivity
Quoted 6 lines · Gleb Natapov

When async PF capability is detected hook up special page fault handler that will handle async page fault events and bypass other page faults to regular page fault handler. Also add async PF handling to nested SVM emulation. Async PF always generates exit to L1 where vcpu thread will be scheduled out until page is available.

Please separate guest and host changes.

Quoted 28 lines
arch/x86/kernel/kvm.c +28 -0
+void kvm_async_pf_task_wait(u32 token)
+{
+	u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS);
+	struct kvm_task_sleep_head *b =&async_pf_sleepers[key];
+	struct kvm_task_sleep_node n, *e;
+	DEFINE_WAIT(wait);
+
+	spin_lock(&b->lock);
+	e = _find_apf_task(b, token);
+	if (e) {
+		/* dummy entry exist ->   wake up was delivered ahead of PF */
+		hlist_del(&e->link);
+		kfree(e);
+		spin_unlock(&b->lock);
+		return;
+	}
+
+	n.token = token;
+	n.cpu = smp_processor_id();
+	init_waitqueue_head(&n.wq);
+	hlist_add_head(&n.link,&b->list);
+	spin_unlock(&b->lock);
+
+	for (;;) {
+		prepare_to_wait(&n.wq,&wait, TASK_UNINTERRUPTIBLE);
+		if (hlist_unhashed(&n.link))
+			break;
+		local_irq_enable();
Quoted 9 lines
Quoted 6 lines
Quoted 4 lines

Suppose we take another apf here. And another, and another (for different pages, while executing schedule()). What's to prevent kernel stack overflow?

Host side keeps track of outstanding apfs and will not send apf for the same phys address twice. It will halt vcpu instead.

What about different pages, running the scheduler code?

We can get couple of nested apfs, just like we can get nested interrupts. Since scheduler disables preemption second apf will halt.

Quoted 2 lines

Oh, and we'll run the scheduler recursively.

As rick said scheduler disables preemption. And this is actually first thing it does. Otherwise any interrupt may cause recursive scheduler invocation.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#27 lore raw

Re: [PATCH v6 03/12] Retry fault before vmentry

In reply to Marcelo Tosatti
Quoted 9 lines · Marcelo Tosatti
Quoted 7 lines · Gleb Natapov
Quoted 4 lines

Can't you set a bit in vcpu->requests instead, and handle it in "out:" at the end of vcpu_enter_guest?

To have a single entry point for pagefaults, after vmexit handling.

Jumping to "out:" will skip vmexit handling anyway, so we will not reuse same call site anyway. I don't see yet why the way you propose will have an advantage.

Quoted 6 lines

What i meant was to call pagefault handler after vmexit handling.

Because the way it is in your patch now, with pre pagefault on entry, one has to make an effort to verify ordering wrt other events on entry processing.

What events do you have in mind?

Quoted 2 lines

With pre pagefault after vmexit, its more natural.

I do not see non-ugly way to pass information that is needed to perform the prefault to the place you want me to put it. We can skip guest entry in case prefault was done which will have the same effect as your proposal, but I want to have a good reason to do so since otherwise we will just do more work for nothing on guest entry.

Quoted 1 line

Does that make sense?

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#62 lore raw

Re: [PATCH v6 07/12] Add async PF initialization to PV guest.

In reply to Avi Kivity
Quoted 17 lines · Avi Kivity

arch/x86/kernel/kvm.c static void __init paravirt_ops_setup(void)

Quoted 13 lines · Gleb Natapov

Enable async PF in a guest if async PF capability is discovered.

arch/x86/kernel/kvm.c +10 -0
+void __cpuinit kvm_guest_cpu_init(void)
+{
+	if (!kvm_para_available())
+		return;
+
+	if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF)&&  kvmapf) {
+		u64 pa = __pa(&__get_cpu_var(apf_reason));
+
+		if (native_write_msr_safe(MSR_KVM_ASYNC_PF_EN,
+					  pa | KVM_ASYNC_PF_ENABLED, pa>>  32))

native_ versions of processor accessors shouldn't be used generally.

Quoted 3 lines

Also, the MSR isn't documented to fail on valid input, so you can use a normal wrmsrl() here.

Kernel will oops on wrong write then. OK, why not.

Quoted 8 lines
Quoted 8 lines
arch/x86/kernel/kvm.c +7 -0
+			return;
+		__get_cpu_var(apf_reason).enabled = 1;
+		printk(KERN_INFO"KVM setup async PF for cpu %d\n",
+		       smp_processor_id());
+	}
+}
+
Quoted 14 lines

arch/x86/kernel/kvm.c static void __init paravirt_ops_setup(void) · line 287

Quoted 11 lines
arch/x86/kernel/kvm.c +11 -0
+static int kvm_pv_reboot_notify(struct notifier_block *nb,
+				unsigned long code, void *unused)
+{
+	if (code == SYS_RESTART)
+		on_each_cpu(kvm_pv_disable_apf, NULL, 1);
+	return NOTIFY_DONE;
+}
+
+static struct notifier_block kvm_pv_reboot_nb = {
+	.notifier_call = kvm_pv_reboot_notify,
+};

Does this handle kexec?

Yes.

Quoted 11 lines

arch/x86/kernel/kvm.c static void __init paravirt_ops_setup(void) · line 303

Quoted 8 lines
arch/x86/kernel/kvm.c +8 -0
+
+static void kvm_guest_cpu_notify(void *dummy)
+{
+	if (!dummy)
+		kvm_guest_cpu_init();
+	else
+		kvm_pv_disable_apf(NULL);
+}

Why are you making decisions based on a dummy input?

Quoted 2 lines

The whole thing looks strange. Use two functions?

What is so strange? Type of notification is passed as a parameter. The code that does this is just under the function. I can rename dummy to something else. Or make it two functions.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#28 lore raw

Re: [PATCH v6 03/12] Retry fault before vmentry

In reply to Gleb Natapov
Quoted 10 lines · Gleb Natapov
Quoted 9 lines · Marcelo Tosatti
Quoted 7 lines · Gleb Natapov
Quoted 4 lines

Can't you set a bit in vcpu->requests instead, and handle it in "out:" at the end of vcpu_enter_guest?

To have a single entry point for pagefaults, after vmexit handling.

Jumping to "out:" will skip vmexit handling anyway, so we will not reuse same call site anyway. I don't see yet why the way you propose will have an advantage.

Quoted 7 lines
Quoted 6 lines

What i meant was to call pagefault handler after vmexit handling.

Because the way it is in your patch now, with pre pagefault on entry, one has to make an effort to verify ordering wrt other events on entry processing.

What events do you have in mind?

TLB flushing, event injection, etc.

Quoted 7 lines
Quoted 2 lines

With pre pagefault after vmexit, its more natural.

I do not see non-ugly way to pass information that is needed to perform the prefault to the place you want me to put it. We can skip guest entry in case prefault was done which will have the same effect as your proposal, but I want to have a good reason to do so since otherwise we will just do more work for nothing on guest entry.

The reason is that it becomes similar to normal pagefault handling. I don't have a specific bug to give you as example.

Quoted 5 lines
Quoted 2 lines

Does that make sense?

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#15 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Gleb Natapov
Quoted 20 lines · Gleb Natapov
Quoted 19 lines · Avi Kivity
Quoted 17 lines · Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

arch/x86/kvm/mmu.c +9 -0
+
+static bool can_do_async_pf(struct kvm_vcpu *vcpu)
+{
+	if (unlikely(!irqchip_in_kernel(vcpu->kvm) ||
+		     kvm_event_needs_reinjection(vcpu)))
+		return false;
+
+	return kvm_x86_ops->interrupt_allowed(vcpu);
+}
Quoted 4 lines
Quoted 2 lines

Strictly speaking, if the cpu can handle NMIs it can take an apf?

We can always do apf, but if vcpu can't do anything hwy bother. For NMI watchdog yes, may be it is worth to allow apf if nmi is allowed.

Actually it's very dangerous - the IRET from APF will re-enable NMIs. So without the guest enabling apf-in-nmi we shouldn't allow it.

Not worth the complexity IMO.

Quoted 12 lines
Quoted 12 lines
Quoted 11 lines
arch/x86/kvm/x86.c +7 -0
@@ -5112,6 +5122,13 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  	if (unlikely(r))
  		goto out;
 
+	kvm_check_async_pf_completion(vcpu);
+	if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED) {
+		/* Page is swapped out. Do synthetic halt */
+		r = 1;
+		goto out;
+	}
+
Quoted 4 lines
Quoted 2 lines

Why do it here in the fast path? Can't you halt the cpu when starting the page fault?

Page fault may complete before guest re-entry. We do not want to halt vcpu in this case.

So unhalt on completion.

Quoted 5 lines
Quoted 3 lines

I guess the apf threads can't touch mp_state, but they can have a KVM_REQ to trigger the check.

This will require KVM_REQ check on fast path, so what's the difference performance wise.

We already have a KVM_REQ check (if (vcpu->requests)) so it doesn't cost anything extra.

Quoted 10 lines
Quoted 10 lines
Quoted 9 lines
arch/x86/kvm/x86.c +1 -0
@@ -6040,6 +6064,7 @@ void kvm_arch_flush_shadow(struct kvm *kvm)
  int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
  {
  	return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
+		|| !list_empty_careful(&vcpu->async_pf.done)
  		|| vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
  		|| vcpu->arch.nmi_pending ||
  		(kvm_arch_interrupt_allowed(vcpu)&&
Quoted 4 lines
Quoted 2 lines

Unrelated, shouldn't kvm_arch_vcpu_runnable() look at vcpu->requests? Specifically KVM_REQ_EVENT?

I think KVM_REQ_EVENT is covered by checking nmi and interrupt queue here.

No, the nmi and interrupt queues are only filled when the lapic is polled via KVM_REQ_EVENT. I'll prepare a patch.

Quoted 10 lines
Quoted 8 lines

include/trace/events/kvm.h TRACE_EVENT(kvm_age_page, · line 208

Quoted 5 lines
include/trace/events/kvm.h +5 -0
+
+TRACE_EVENT(
+	kvm_async_pf_not_present,
+	TP_PROTO(u64 gva),
+	TP_ARGS(gva),

Do you actually have a gva with tdp? With nested virtualization, how do you interpret this gva?

With tdp it is gpa just like tdp_page_fault gets gpa where shadow page version gets gva. Nested virtualization is too complex to interpret.

It's not good to have a tracepoint that depends on cpu mode (without recording that mode). I think we have the same issue in trace_kvm_page_fault though.

Quoted 9 lines
Quoted 8 lines

include/trace/events/kvm.h TRACE_EVENT(kvm_age_page, · line 240

Quoted 5 lines
include/trace/events/kvm.h +5 -0
+
+TRACE_EVENT(
+	kvm_async_pf_completed,
+	TP_PROTO(unsigned long address, struct page *page, u64 gva),
+	TP_ARGS(address, page, gva),

What does address mean? There's also gva?

hva.

Is hva helpful here? Generally gpa is better, but may not be available since it's ambiguous.

Quoted 17 lines
Quoted 17 lines
Quoted 4 lines
virt/kvm/async_pf.c new file +2 -0
+void kvm_clear_async_pf_completion_queue(struct kvm_vcpu *vcpu)
+{

virt/kvm/async_pf.c line 105

Quoted 10 lines
virt/kvm/async_pf.c new file +10 -0
+	/* cancel outstanding work queue item */
+	while (!list_empty(&vcpu->async_pf.queue)) {
+		struct kvm_async_pf *work =
+			list_entry(vcpu->async_pf.queue.next,
+				   typeof(*work), queue);
+		cancel_work_sync(&work->work);
+		list_del(&work->queue);
+		if (!work->page) /* work was canceled */
+			kmem_cache_free(async_pf_cache, work);
+	}

Are you holding any lock here?

Quoted 8 lines
Quoted 1 line

If not, what protects vcpu->async_pf.queue?

Nothing. It is accessed only from vcpu thread.

Quoted 4 lines

If yes, cancel_work_sync() will need to aquire it too (in case work is running now and needs to take the lock, and cacncel_work_sync() needs to wait for it) -> deadlock.

Work never touches this list.

So, an apf is always in ->queue and when completed also in ->done?

Is it not cleaner to list_move the apf from ->queue to ->done? saves a ->link.

Can be done later.

Quoted 17 lines
Quoted 17 lines

virt/kvm/async_pf.c line 168

Quoted 3 lines
virt/kvm/async_pf.c new file +3 -0
+
+	/* do alloc nowait since if we are going to sleep anyway we
+	   may as well sleep faulting in page */

/*
* multi
* line
* comment
*/

(but a good one, this is subtle)

I missed where you halt the vcpu. Can you point me at the function?

Note this is a synthetic halt and must not be visible to live migration, or we risk live migrating a halted state which doesn't really exist.

Quoted 6 lines
Quoted 2 lines

Might be simplest to drain the apf queue on any of the save/restore ioctls.

So that "info cpu" will interfere with apf? Migration should work in regular way. apf state should not be migrated since it has no meaning on the destination. I'll make sure synthetic halt state will not interfere with migration.

If you deliver an apf, the guest expects a completion.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#16 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

Quoted 8 lines · Avi Kivity
Quoted 4 lines

So that "info cpu" will interfere with apf? Migration should work in regular way. apf state should not be migrated since it has no meaning on the destination. I'll make sure synthetic halt state will not interfere with migration.

If you deliver an apf, the guest expects a completion.

btw, the token generation scheme resets as well. Draining the queue fixes that as well.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#31 lore raw

Re: [PATCH v6 03/12] Retry fault before vmentry

In reply to Gleb Natapov
Quoted 9 lines · Gleb Natapov
Quoted 8 lines · Avi Kivity
Quoted 6 lines · Gleb Natapov

When page is swapped in it is mapped into guest memory only after guest tries to access it again and generate another fault. To save this fault we can map it immediately since we know that guest is going to access the page. Do it only when tdp is enabled for now. Shadow paging case is more complicated. CR[034] and EFER registers should be switched before doing mapping and then switched back.

Quoted 4 lines
Quoted 1 line

With non-pv apf, I don't think we can do shadow paging. The guest

Yes, with non-pv this trick will not work without tdp. I haven't even considered it for that case.

What about nnpt? The same issues exist.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#54 lore raw

Re: [PATCH v6 06/12] Add PV MSR to enable asynchronous page faults delivery.

In reply to Gleb Natapov
Quoted 18 lines · Gleb Natapov
Quoted 17 lines · Avi Kivity

Documentation/kvm/msr.txt MSR_KVM_SYSTEM_TIME: 0x12 · line 164

Quoted 6 lines · Gleb Natapov
Documentation/kvm/msr.txt +6 -0
+
+	Physical address points to 32 bit memory location that will be written
+	to by the hypervisor at the time of asynchronous page fault injection to
+	indicate type of asynchronous page fault. Value of 1 means that the page
+	referred to by the page fault is not present. Value 2 means that the
+	page is now available.

"The must not enable interrupts before the reason is read, or it may be overwritten by another apf".

Document the fact that disabling interrupts disables APFs.

How does the guest distinguish betweem APFs and ordinary page faults?

What's the role of cr2?

Quoted 8 lines
Quoted 6 lines

When disabling APF, all pending APFs are flushed and may or may not get a completion.

Is a "page available" notification guaranteed to arrive on the same vcpu that took the "page not present" fault?

You mean documentation is lacking? :)

I mean you should be able to write guest support code without reading the host code, just the documentation.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#63 lore raw

Re: [PATCH v6 07/12] Add async PF initialization to PV guest.

In reply to Gleb Natapov
Quoted 9 lines · Gleb Natapov
Quoted 9 lines
Quoted 8 lines
arch/x86/kernel/kvm.c +8 -0
+
+static void kvm_guest_cpu_notify(void *dummy)
+{
+	if (!dummy)
+		kvm_guest_cpu_init();
+	else
+		kvm_pv_disable_apf(NULL);
+}
Quoted 7 lines
Quoted 4 lines

Why are you making decisions based on a dummy input?

The whole thing looks strange. Use two functions?

What is so strange? Type of notification is passed as a parameter. The code that does this is just under the function. I can rename dummy to something else. Or make it two functions.

Two separate functions is simplest.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#70 lore raw

Re: [PATCH v6 08/12] Handle async PF in a guest.

In reply to Gleb Natapov
Quoted 8 lines · Gleb Natapov
Quoted 6 lines
Quoted 3 lines
Quoted 1 line

Host side keeps track of outstanding apfs and will not send apf for the same phys address twice. It will halt vcpu instead.

What about different pages, running the scheduler code?

We can get couple of nested apfs, just like we can get nested interrupts. Since scheduler disables preemption second apf will halt.

How much is a couple?

Consider:

SIGSTOP
Entire process swapped out
SIGCONT

We can get APF's on the current code, the scheduler code, the stack, any debugging code in between (e.g. ftrace), and the page tables for all of these.

Signature · 8 lines
I have a truly marvellous patch that fixes the bug which this
signature is too narrow to contain.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#18 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Avi Kivity
Quoted 21 lines · Avi Kivity
Quoted 20 lines · Gleb Natapov
Quoted 19 lines · Avi Kivity
Quoted 17 lines · Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

arch/x86/kvm/mmu.c +9 -0
+
+static bool can_do_async_pf(struct kvm_vcpu *vcpu)
+{
+	if (unlikely(!irqchip_in_kernel(vcpu->kvm) ||
+		     kvm_event_needs_reinjection(vcpu)))
+		return false;
+
+	return kvm_x86_ops->interrupt_allowed(vcpu);
+}
Quoted 9 lines
Quoted 4 lines
Quoted 2 lines

Strictly speaking, if the cpu can handle NMIs it can take an apf?

We can always do apf, but if vcpu can't do anything hwy bother. For NMI watchdog yes, may be it is worth to allow apf if nmi is allowed.

Actually it's very dangerous - the IRET from APF will re-enable NMIs. So without the guest enabling apf-in-nmi we shouldn't allow it.

Good point.

Quoted 14 lines

Not worth the complexity IMO.

Quoted 12 lines
Quoted 12 lines
Quoted 11 lines
arch/x86/kvm/x86.c +7 -0
@@ -5112,6 +5122,13 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  	if (unlikely(r))
  		goto out;
 
+	kvm_check_async_pf_completion(vcpu);
+	if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED) {
+		/* Page is swapped out. Do synthetic halt */
+		r = 1;
+		goto out;
+	}
+
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

Why do it here in the fast path? Can't you halt the cpu when starting the page fault?

Page fault may complete before guest re-entry. We do not want to halt vcpu in this case.

So unhalt on completion.

I want to avoid touching vcpu state from work if possible. Work code does not contain arch dependent code right now and mp_state is x86 thing

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

I guess the apf threads can't touch mp_state, but they can have a KVM_REQ to trigger the check.

This will require KVM_REQ check on fast path, so what's the difference performance wise.

We already have a KVM_REQ check (if (vcpu->requests)) so it doesn't cost anything extra.

if (vcpu->requests) does not clear req bit, so what will have to be added
is: if (kvm_check_request(KVM_REQ_APF_HLT, vcpu)) which is even more expensive then my check (but not so expensive to worry about).

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
arch/x86/kvm/x86.c +1 -0
@@ -6040,6 +6064,7 @@ void kvm_arch_flush_shadow(struct kvm *kvm)
  int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
  {
  	return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
+		|| !list_empty_careful(&vcpu->async_pf.done)
  		|| vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
  		|| vcpu->arch.nmi_pending ||
  		(kvm_arch_interrupt_allowed(vcpu)&&
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

Unrelated, shouldn't kvm_arch_vcpu_runnable() look at vcpu->requests? Specifically KVM_REQ_EVENT?

I think KVM_REQ_EVENT is covered by checking nmi and interrupt queue here.

No, the nmi and interrupt queues are only filled when the lapic is polled via KVM_REQ_EVENT. I'll prepare a patch.

I don't think you are correct. nmi_pending is filled before setting KVM_REQ_EVENT and kvm_cpu_has_interrupt() checks directly in apic/pic.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
include/trace/events/kvm.h +5 -0
+
+TRACE_EVENT(
+	kvm_async_pf_not_present,
+	TP_PROTO(u64 gva),
+	TP_ARGS(gva),
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

Do you actually have a gva with tdp? With nested virtualization, how do you interpret this gva?

With tdp it is gpa just like tdp_page_fault gets gpa where shadow page version gets gva. Nested virtualization is too complex to interpret.

It's not good to have a tracepoint that depends on cpu mode (without recording that mode). I think we have the same issue in trace_kvm_page_fault though.

We have mmu_is_nested(). I'll just disable apf while vcpu is in nested mode for now.

Quoted 38 lines
Quoted 10 lines
Quoted 9 lines

include/trace/events/kvm.h TRACE_EVENT(kvm_age_page, · line 240

Quoted 6 lines
include/trace/events/kvm.h +5 -0
+
+TRACE_EVENT(
+	kvm_async_pf_completed,
+	TP_PROTO(unsigned long address, struct page *page, u64 gva),
+	TP_ARGS(address, page, gva),

What does address mean? There's also gva?

hva.

Is hva helpful here? Generally gpa is better, but may not be available since it's ambiguous.

Quoted 24 lines
Quoted 17 lines
Quoted 4 lines
virt/kvm/async_pf.c new file +2 -0
+void kvm_clear_async_pf_completion_queue(struct kvm_vcpu *vcpu)
+{

virt/kvm/async_pf.c line 105

Quoted 10 lines
virt/kvm/async_pf.c new file +10 -0
+	/* cancel outstanding work queue item */
+	while (!list_empty(&vcpu->async_pf.queue)) {
+		struct kvm_async_pf *work =
+			list_entry(vcpu->async_pf.queue.next,
+				   typeof(*work), queue);
+		cancel_work_sync(&work->work);
+		list_del(&work->queue);
+		if (!work->page) /* work was canceled */
+			kmem_cache_free(async_pf_cache, work);
+	}

Are you holding any lock here?

Quoted 1 line

If not, what protects vcpu->async_pf.queue?

Nothing. It is accessed only from vcpu thread.

Quoted 4 lines

If yes, cancel_work_sync() will need to aquire it too (in case work is running now and needs to take the lock, and cacncel_work_sync() needs to wait for it) -> deadlock.

Quoted 6 lines
Quoted 1 line

Work never touches this list.

So, an apf is always in ->queue and when completed also in ->done?

Is it not cleaner to list_move the apf from ->queue to ->done? saves a ->link.

Then you have more complicated locking issues.

Quoted 20 lines

Can be done later.

Quoted 17 lines
Quoted 17 lines

virt/kvm/async_pf.c line 168

Quoted 3 lines
virt/kvm/async_pf.c new file +3 -0
+
+	/* do alloc nowait since if we are going to sleep anyway we
+	   may as well sleep faulting in page */

/*
* multi
* line
* comment
*/

(but a good one, this is subtle)

I missed where you halt the vcpu. Can you point me at the function?

Note this is a synthetic halt and must not be visible to live migration, or we risk live migrating a halted state which doesn't really exist.

Quoted 9 lines
Quoted 6 lines
Quoted 2 lines

Might be simplest to drain the apf queue on any of the save/restore ioctls.

So that "info cpu" will interfere with apf? Migration should work in regular way. apf state should not be migrated since it has no meaning on the destination. I'll make sure synthetic halt state will not interfere with migration.

If you deliver an apf, the guest expects a completion.

There is special completion that tells guest to wake all sleeping tasks on vcpu. It is delivered after migration on the destination.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#17 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Avi Kivity
Quoted 7 lines · Avi Kivity
Quoted 6 lines · Avi Kivity
Quoted 4 lines

So that "info cpu" will interfere with apf? Migration should work in regular way. apf state should not be migrated since it has no meaning on the destination. I'll make sure synthetic halt state will not interfere with migration.

Quoted 6 lines
Quoted 2 lines

If you deliver an apf, the guest expects a completion.

btw, the token generation scheme resets as well. Draining the queue fixes that as well.

I don't see what's there to fix. Can you explain what problem you see in the way current code works?

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#32 lore raw

Re: [PATCH v6 03/12] Retry fault before vmentry

In reply to Avi Kivity
Quoted 10 lines · Avi Kivity
Quoted 9 lines · Gleb Natapov
Quoted 8 lines · Avi Kivity
Quoted 6 lines · Gleb Natapov

When page is swapped in it is mapped into guest memory only after guest tries to access it again and generate another fault. To save this fault we can map it immediately since we know that guest is going to access the page. Do it only when tdp is enabled for now. Shadow paging case is more complicated. CR[034] and EFER registers should be switched before doing mapping and then switched back.

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

With non-pv apf, I don't think we can do shadow paging. The guest

Yes, with non-pv this trick will not work without tdp. I haven't even considered it for that case.

What about nnpt? The same issues exist.

I am not sure how nntp works. What is the problem there? In case of tdp prefault instantiates page in direct_map, how nntp interfere with that?

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#71 lore raw

Re: [PATCH v6 08/12] Handle async PF in a guest.

In reply to Avi Kivity
Quoted 14 lines · Avi Kivity
Quoted 8 lines · Gleb Natapov
Quoted 6 lines
Quoted 3 lines
Quoted 1 line

Host side keeps track of outstanding apfs and will not send apf for the same phys address twice. It will halt vcpu instead.

What about different pages, running the scheduler code?

We can get couple of nested apfs, just like we can get nested interrupts. Since scheduler disables preemption second apf will halt.

How much is a couple?

Consider:

Quoted 8 lines

SIGSTOP
Entire process swapped out
SIGCONT

We can get APF's on the current code, the scheduler code, the stack, any debugging code in between (e.g. ftrace), and the page tables for all of these.

Lets count them all. Suppose guest is in a userspace process code and guest memory is completely swapped out. Guest starts to run and faults in userspace. Apf is queued but can't be delivered due to faults in idt and exception stack. All of them will be taken synchronously due to event pending check. After apf is delivered any fault in apf code will be takes synchronously since interrupt are disabled. Just before calling schedule() interrupts are enabled, so next pf that will happen during call to schedule() will be taken asynchronously. Which will cause another call to schedule() at which point vcpu will be halted since two apfs happened at the same address. So I counted two of them.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#73 lore raw

Re: [PATCH v6 08/12] Handle async PF in a guest.

In reply to Avi Kivity
Quoted 10 lines · Avi Kivity
Quoted 6 lines · Gleb Natapov

When async PF capability is detected hook up special page fault handler that will handle async page fault events and bypass other page faults to regular page fault handler. Also add async PF handling to nested SVM emulation. Async PF always generates exit to L1 where vcpu thread will be scheduled out until page is available.

Please separate guest and host changes.

Hmm. There are only guest changes here as far as I can see.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#74 lore raw

Re: [PATCH v6 08/12] Handle async PF in a guest.

Quoted 9 lines · Gleb Natapov
Quoted 8 lines · Avi Kivity
Quoted 6 lines · Gleb Natapov

When async PF capability is detected hook up special page fault handler that will handle async page fault events and bypass other page faults to regular page fault handler. Also add async PF handling to nested SVM emulation. Async PF always generates exit to L1 where vcpu thread will be scheduled out until page is available.

Quoted 3 lines
Quoted 2 lines

Please separate guest and host changes.

Hmm. There are only guest changes here as far as I can see.

From the diffstat:

Quoted 6 lines
  arch/x86/include/asm/kvm_para.h |   12 +++
  arch/x86/include/asm/traps.h    |    1 +
  arch/x86/kernel/entry_32.S      |   10 ++
  arch/x86/kernel/entry_64.S      |    3 +
  arch/x86/kernel/kvm.c           |  184 ++++++++++++++++++++++++++++++++++++++-
  arch/x86/kvm/svm.c              |   43 +++++++--

svm.c is host code.

Signature · 7 lines
error compiling committee.c: too many arguments to function

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#72 lore raw

Re: [PATCH v6 08/12] Handle async PF in a guest.

In reply to Gleb Natapov
Quoted 23 lines · Gleb Natapov
Quoted 14 lines · Avi Kivity
Quoted 8 lines · Gleb Natapov
Quoted 6 lines
Quoted 3 lines
Quoted 1 line

Host side keeps track of outstanding apfs and will not send apf for the same phys address twice. It will halt vcpu instead.

What about different pages, running the scheduler code?

We can get couple of nested apfs, just like we can get nested interrupts. Since scheduler disables preemption second apf will halt.

How much is a couple?

Consider:

Quoted 8 lines

SIGSTOP
Entire process swapped out
SIGCONT

We can get APF's on the current code, the scheduler code, the stack, any debugging code in between (e.g. ftrace), and the page tables for all of these.

Quoted 11 lines

Lets count them all. Suppose guest is in a userspace process code and guest memory is completely swapped out. Guest starts to run and faults in userspace. Apf is queued but can't be delivered due to faults in idt and exception stack. All of them will be taken synchronously due to event pending check. After apf is delivered any fault in apf code will be takes synchronously since interrupt are disabled. Just before calling schedule() interrupts are enabled, so next pf that will happen during call to schedule() will be taken asynchronously. Which will cause another call to schedule() at which point vcpu will be halted since two apfs happened at the same address. So I counted two of them.

Ok. Feels weird, but I guess this is fine.

Signature · 7 lines
error compiling committee.c: too many arguments to function

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#50 lore raw

Re: [PATCH v6 06/12] Add PV MSR to enable asynchronous page faults delivery.

In reply to Gleb Natapov
Quoted 9 lines · Gleb Natapov
Quoted 8 lines · Avi Kivity
Quoted 6 lines · Gleb Natapov

Guest enables async PF vcpu functionality using this MSR.

return NON_PRESENT;

Documentation/kvm/msr.txt +3 -0
+
+MSR_KVM_ASYNC_PF_EN: 0x4b564d02
+	data: Bits 63-6 hold 64-byte aligned physical address of a 32bit memory
Quoted 6 lines
Quoted 5 lines

Given that it must be aligned anyway, we can require it to be a 64-byte region and also require that the guest zero it before writing the MSR. That will give us a little more flexibility in the future.

No code change needed, so OK.

The guest needs to allocate a 64-byte per-cpu entry instead of a 4-byte entry.

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
arch/x86/kvm/x86.c +5 -0
+		return 0;
+	}
+
+	if (kvm_gfn_to_hva_cache_init(vcpu->kvm,&vcpu->arch.apf.data, gpa))
+		return 1;
Quoted 7 lines
Quoted 5 lines

Note: we need to handle the memory being removed from underneath kvm_gfn_to_hve_cache(). Given that, we can just make kvm_gfn_to_hva_cache_init() return void. "success" means nothing when future changes can invalidate it.

I want to catch guest doing stupid things. If guest give us non-existent address I want wrmsr to #GP.

Ok.

Quoted 7 lines
Quoted 5 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+
+	kvm_async_pf_wakeup_all(vcpu);

Why is this needed? If all apfs are flushed at disable time, what do we need to wake up?

For migration. Destination will rewrite msr and all processes will be waked up.

Ok. What happens to apf completions that happen after all vcpus are stopped?

Quoted 5 lines
Quoted 4 lines

Need to list the MSR for save/restore/reset.

This patch adds it to msrs_to_save, no?

Yes, missed it somehow.

Signature · 7 lines
error compiling committee.c: too many arguments to function

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#44 lore raw

Re: [PATCH v6 04/12] Add memory slot versioning and use it to provide fast guest write interface

In reply to Gleb Natapov
Quoted 12 lines · Gleb Natapov
Quoted 11 lines · Avi Kivity
Quoted 9 lines · Gleb Natapov
Quoted 6 lines
Quoted 3 lines

Isn't SET_USER_MEMORY_REGION so slow that calling it 2^32 times isn't really feasible?

Assuming it takes 1ms, it would take 49 days.

We may fail ioctl when max value is reached. The question is how much slot changes can we expect from real guest during its lifetime.

Quoted 6 lines
Quoted 4 lines

A normal guest has a 30 Hz timer for reading the vga framebuffer, multiple slots. Let's assume 100 Hz frequency, that gives 490 days until things stop working.

And reading vga framebuffer needs slots changes because of dirty map tracking?

Yes.

Signature · 7 lines
error compiling committee.c: too many arguments to function

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#75 lore raw

Re: [PATCH v6 08/12] Handle async PF in a guest.

In reply to Avi Kivity
Quoted 16 lines · Avi Kivity
Quoted 9 lines · Gleb Natapov
Quoted 8 lines · Avi Kivity
Quoted 6 lines · Gleb Natapov

When async PF capability is detected hook up special page fault handler that will handle async page fault events and bypass other page faults to regular page fault handler. Also add async PF handling to nested SVM emulation. Async PF always generates exit to L1 where vcpu thread will be scheduled out until page is available.

Quoted 3 lines
Quoted 2 lines

Please separate guest and host changes.

Hmm. There are only guest changes here as far as I can see.

From the diffstat:

Quoted 9 lines
Quoted 6 lines
 arch/x86/include/asm/kvm_para.h |   12 +++
 arch/x86/include/asm/traps.h    |    1 +
 arch/x86/kernel/entry_32.S      |   10 ++
 arch/x86/kernel/entry_64.S      |    3 +
 arch/x86/kernel/kvm.c           |  184 ++++++++++++++++++++++++++++++++++++++-
 arch/x86/kvm/svm.c              |   43 +++++++--

svm.c is host code.

Not exactly :) It is a host code from nested guest perspective, but guest code from L0 perspective.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#51 lore raw

Re: [PATCH v6 06/12] Add PV MSR to enable asynchronous page faults delivery.

In reply to Avi Kivity
Quoted 15 lines · Avi Kivity
Quoted 14 lines · Gleb Natapov
Quoted 13 lines · Avi Kivity

Documentation/kvm/msr.txt MSR_KVM_SYSTEM_TIME: 0x12 · line 155

Quoted 6 lines · Gleb Natapov

Guest enables async PF vcpu functionality using this MSR.

return NON_PRESENT;

Documentation/kvm/msr.txt +3 -0
+
+MSR_KVM_ASYNC_PF_EN: 0x4b564d02
+	data: Bits 63-6 hold 64-byte aligned physical address of a 32bit memory

Given that it must be aligned anyway, we can require it to be a 64-byte region and also require that the guest zero it before writing the MSR. That will give us a little more flexibility in the future.

Quoted 5 lines
Quoted 1 line

No code change needed, so OK.

The guest needs to allocate a 64-byte per-cpu entry instead of a 4-byte entry.

Yes, noticed that already :(

Quoted 11 lines
Quoted 8 lines
Quoted 6 lines

Review

Quoted 3 lines
(quoted diff) +2 -0
+
+	kvm_async_pf_wakeup_all(vcpu);

Why is this needed? If all apfs are flushed at disable time, what do we need to wake up?

For migration. Destination will rewrite msr and all processes will be waked up.

Ok. What happens to apf completions that happen after all vcpus are stopped?

They will be cleaned by kvm_clear_async_pf_completion_queue() on vcpu destroy.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#83 lore raw

Re: [PATCH v6 10/12] Handle async PF in non preemptable context

In reply to Gleb Natapov
Quoted 55 lines · Gleb Natapov
Quoted 47 lines · Marcelo Tosatti
Quoted 46 lines · Gleb Natapov

If async page fault is received by idle task or when preemp_count is not zero guest cannot reschedule, so do sti; hlt and wait for page to be ready. vcpu can still process interrupts while it waits for the page to be ready.

---
 arch/x86/kernel/kvm.c |   40 ++++++++++++++++++++++++++++++++++------
 1 files changed, 34 insertions(+), 6 deletions(-)
arch/x86/kernel/kvm.c +8 -0
index 36fb3e4..f73946f 100644
@@ -37,6 +37,7 @@
 #include <asm/cpu.h>
 #include <asm/traps.h>
 #include <asm/desc.h>
+#include <asm/tlbflush.h>
 
 #define MMU_QUEUE_SIZE 1024
 
@@ -78,6 +79,8 @@ struct kvm_task_sleep_node {
 	wait_queue_head_t wq;
 	u32 token;
 	int cpu;
+	bool halted;
+	struct mm_struct *mm;
 };
 
 static struct kvm_task_sleep_head {
@@ -106,6 +109,11 @@ void kvm_async_pf_task_wait(u32 token)
 	struct kvm_task_sleep_head *b = &async_pf_sleepers[key];
 	struct kvm_task_sleep_node n, *e;
 	DEFINE_WAIT(wait);
+	int cpu, idle;
+
+	cpu = get_cpu();
+	idle = idle_cpu(cpu);
+	put_cpu();
 
 	spin_lock(&b->lock);
 	e = _find_apf_task(b, token);
@@ -119,19 +127,33 @@ void kvm_async_pf_task_wait(u32 token)
 
Quoted 7 lines

arch/x86/kernel/kvm.c void kvm_async_pf_task_wait(u32 token) · line 132

Quoted 5 lines
arch/x86/kernel/kvm.c +3 -0
 	n.token = token;
 	n.cpu = smp_processor_id();
+	n.mm = current->active_mm;
+	n.halted = idle || preempt_count() > 1;
+	atomic_inc(&n.mm->mm_count);

Can't see why this reference is needed.

Quoted 5 lines

I thought that if kernel thread does fault on behalf of some process mm can go away while kernel thread is sleeping. But it looks like kernel thread increase reference to mm it runs with by himself, so may be this is redundant (but not harmful).

Actually it is not redundant. Kernel thread will release reference to active_mm on reschedule.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#19 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Gleb Natapov
Quoted 52 lines · Gleb Natapov
Quoted 21 lines · Avi Kivity
Quoted 20 lines · Gleb Natapov
Quoted 19 lines · Avi Kivity
Quoted 17 lines · Gleb Natapov

If a guest accesses swapped out memory do not swap it in from vcpu thread context. Schedule work to do swapping and put vcpu into halted state instead.

Interrupts will still be delivered to the guest and if interrupt will cause reschedule guest will continue to run another task.

arch/x86/kvm/mmu.c +9 -0
+
+static bool can_do_async_pf(struct kvm_vcpu *vcpu)
+{
+	if (unlikely(!irqchip_in_kernel(vcpu->kvm) ||
+		     kvm_event_needs_reinjection(vcpu)))
+		return false;
+
+	return kvm_x86_ops->interrupt_allowed(vcpu);
+}
Quoted 9 lines
Quoted 4 lines
Quoted 2 lines

Strictly speaking, if the cpu can handle NMIs it can take an apf?

We can always do apf, but if vcpu can't do anything hwy bother. For NMI watchdog yes, may be it is worth to allow apf if nmi is allowed.

Actually it's very dangerous - the IRET from APF will re-enable NMIs. So without the guest enabling apf-in-nmi we shouldn't allow it.

Good point.

Quoted 19 lines

Not worth the complexity IMO.

Quoted 16 lines
Quoted 4 lines
Quoted 4 lines
arch/x86/kvm/x86.c +0 -0
@@ -5112,6 +5122,13 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
   	if (unlikely(r))
   		goto out;
 
Quoted 10 lines

arch/x86/kvm/x86.c static int vcpu_enter_guest(struct kvm_vcpu *vcpu) · line 5131

Quoted 7 lines
arch/x86/kvm/x86.c +7 -0
+	kvm_check_async_pf_completion(vcpu);
+	if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED) {
+		/* Page is swapped out. Do synthetic halt */
+		r = 1;
+		goto out;
+	}
+

Why do it here in the fast path? Can't you halt the cpu when starting the page fault?

Page fault may complete before guest re-entry. We do not want to halt vcpu in this case.

Quoted 5 lines
Quoted 2 lines

So unhalt on completion.

I want to avoid touching vcpu state from work if possible. Work code does not contain arch dependent code right now and mp_state is x86 thing

Use a KVM_REQ.

Quoted 11 lines
Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

I guess the apf threads can't touch mp_state, but they can have a KVM_REQ to trigger the check.

This will require KVM_REQ check on fast path, so what's the difference performance wise.

We already have a KVM_REQ check (if (vcpu->requests)) so it doesn't cost anything extra.

if (vcpu->requests) does not clear req bit, so what will have to be added
is: if (kvm_check_request(KVM_REQ_APF_HLT, vcpu)) which is even more expensive then my check (but not so expensive to worry about).

It's only expensive when it happens. Most entries will have the bit clear.

Quoted 16 lines
Quoted 16 lines
Quoted 15 lines
Quoted 13 lines

arch/x86/kvm/x86.c void kvm_arch_flush_shadow(struct kvm *kvm) · line 6070

Quoted 10 lines
arch/x86/kvm/x86.c +1 -0
@@ -6040,6 +6064,7 @@ void kvm_arch_flush_shadow(struct kvm *kvm)
   int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
   {
   	return vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE
+		|| !list_empty_careful(&vcpu->async_pf.done)
   		|| vcpu->arch.mp_state == KVM_MP_STATE_SIPI_RECEIVED
   		|| vcpu->arch.nmi_pending ||
   		(kvm_arch_interrupt_allowed(vcpu)&&

Unrelated, shouldn't kvm_arch_vcpu_runnable() look at vcpu->requests? Specifically KVM_REQ_EVENT?

I think KVM_REQ_EVENT is covered by checking nmi and interrupt queue here.

Quoted 4 lines
Quoted 2 lines

No, the nmi and interrupt queues are only filled when the lapic is polled via KVM_REQ_EVENT. I'll prepare a patch.

I don't think you are correct. nmi_pending is filled before setting KVM_REQ_EVENT and kvm_cpu_has_interrupt() checks directly in apic/pic.

Right.

Quoted 12 lines
Quoted 12 lines
Quoted 11 lines
Quoted 9 lines

include/trace/events/kvm.h TRACE_EVENT(kvm_age_page, · line 208

Quoted 6 lines
include/trace/events/kvm.h +5 -0
+
+TRACE_EVENT(
+	kvm_async_pf_not_present,
+	TP_PROTO(u64 gva),
+	TP_ARGS(gva),

Do you actually have a gva with tdp? With nested virtualization, how do you interpret this gva?

With tdp it is gpa just like tdp_page_fault gets gpa where shadow page version gets gva. Nested virtualization is too complex to interpret.

Quoted 5 lines
Quoted 3 lines

It's not good to have a tracepoint that depends on cpu mode (without recording that mode). I think we have the same issue in trace_kvm_page_fault though.

We have mmu_is_nested(). I'll just disable apf while vcpu is in nested mode for now.

What if we get the apf in non-nested mode and it completes in nested mode?

Quoted 25 lines
Quoted 25 lines
Quoted 24 lines
Quoted 12 lines

virt/kvm/async_pf.c line 168

Quoted 4 lines
virt/kvm/async_pf.c new file +3 -0
+
+	/* do alloc nowait since if we are going to sleep anyway we
+	   may as well sleep faulting in page */

/*
* multi
* line
* comment
*/

(but a good one, this is subtle)

Quoted 8 lines

I missed where you halt the vcpu. Can you point me at the function?

Note this is a synthetic halt and must not be visible to live migration, or we risk live migrating a halted state which doesn't really exist.

Might be simplest to drain the apf queue on any of the save/restore ioctls.

So that "info cpu" will interfere with apf? Migration should work in regular way. apf state should not be migrated since it has no meaning on the destination. I'll make sure synthetic halt state will not interfere with migration.

Quoted 5 lines
Quoted 2 lines

If you deliver an apf, the guest expects a completion.

There is special completion that tells guest to wake all sleeping tasks on vcpu. It is delivered after migration on the destination.

Yes, I saw.

What if you can't deliver it? is it possible that some other vcpu will start receiving apfs that alias the old ones? Or is the broadcast global?

Signature · 7 lines
error compiling committee.c: too many arguments to function

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#20 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

Quoted 9 lines · Avi Kivity
Quoted 4 lines

There is special completion that tells guest to wake all sleeping tasks on vcpu. It is delivered after migration on the destination.

Yes, I saw.

What if you can't deliver it? is it possible that some other vcpu will start receiving apfs that alias the old ones? Or is the broadcast global?

And, is the broadcast used only for migrations?

Signature · 7 lines
error compiling committee.c: too many arguments to function

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#22 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Avi Kivity
Quoted 18 lines · Avi Kivity
Quoted 18 lines
Quoted 18 lines
Quoted 17 lines
Quoted 5 lines
Quoted 5 lines
arch/x86/kvm/x86.c +0 -0
@@ -5112,6 +5122,13 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
   	if (unlikely(r))
   		goto out;
 
Quoted 10 lines

arch/x86/kvm/x86.c static int vcpu_enter_guest(struct kvm_vcpu *vcpu) · line 5131

Quoted 7 lines
arch/x86/kvm/x86.c +7 -0
+	kvm_check_async_pf_completion(vcpu);
+	if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED) {
+		/* Page is swapped out. Do synthetic halt */
+		r = 1;
+		goto out;
+	}
+

Why do it here in the fast path? Can't you halt the cpu when starting the page fault?

Page fault may complete before guest re-entry. We do not want to halt vcpu in this case.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

So unhalt on completion.

I want to avoid touching vcpu state from work if possible. Work code does not contain arch dependent code right now and mp_state is x86 thing

Use a KVM_REQ.

Completion happens asynchronously. CPU may not be even halted at that point. Actually completion does unhalt vcpu. It puts completed work into vcpu->async_pf.done list and wakes vcpu thread if it sleeps. Next invocation of kvm_arch_vcpu_runnable() will return true since vcpu->async_pf.done is not empty and vcpu will be unhalted in usual way by kvm_vcpu_block().

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
Quoted 4 lines

I guess the apf threads can't touch mp_state, but they can have a KVM_REQ to trigger the check.

This will require KVM_REQ check on fast path, so what's the difference performance wise.

Quoted 7 lines
Quoted 5 lines
Quoted 2 lines

We already have a KVM_REQ check (if (vcpu->requests)) so it doesn't cost anything extra.

if (vcpu->requests) does not clear req bit, so what will have to be added
is: if (kvm_check_request(KVM_REQ_APF_HLT, vcpu)) which is even more expensive then my check (but not so expensive to worry about).

It's only expensive when it happens. Most entries will have the bit clear.

kvm_check_async_pf_completion() (the one that detects if vcpu should be halted) is called after vcpu->requests processing. It is done in order to delay completion checking as far as possible in hope to get completion before next vcpu entry and skip sending apf, so I do it at the last possible moment before event injection.

Quoted 12 lines
Quoted 12 lines
Quoted 12 lines
Quoted 11 lines
Quoted 9 lines

include/trace/events/kvm.h TRACE_EVENT(kvm_age_page, · line 208

Quoted 6 lines
include/trace/events/kvm.h +5 -0
+
+TRACE_EVENT(
+	kvm_async_pf_not_present,
+	TP_PROTO(u64 gva),
+	TP_ARGS(gva),

Do you actually have a gva with tdp? With nested virtualization, how do you interpret this gva?

With tdp it is gpa just like tdp_page_fault gets gpa where shadow page version gets gva. Nested virtualization is too complex to interpret.

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

It's not good to have a tracepoint that depends on cpu mode (without recording that mode). I think we have the same issue in trace_kvm_page_fault though.

We have mmu_is_nested(). I'll just disable apf while vcpu is in nested mode for now.

What if we get the apf in non-nested mode and it completes in nested mode?

I am not yet sure we have any problem with nested mode at all. I am looking at it. If we have we can skip prefault if in nested.

Quoted 27 lines
Quoted 27 lines
Quoted 27 lines
Quoted 18 lines
Quoted 18 lines

virt/kvm/async_pf.c line 168

Quoted 4 lines
virt/kvm/async_pf.c new file +3 -0
+
+	/* do alloc nowait since if we are going to sleep anyway we
+	   may as well sleep faulting in page */

/*
* multi
* line
* comment
*/

(but a good one, this is subtle)

I missed where you halt the vcpu. Can you point me at the function?

Note this is a synthetic halt and must not be visible to live migration, or we risk live migrating a halted state which doesn't really exist.

Quoted 6 lines
Quoted 2 lines

Might be simplest to drain the apf queue on any of the save/restore ioctls.

So that "info cpu" will interfere with apf? Migration should work in regular way. apf state should not be migrated since it has no meaning on the destination. I'll make sure synthetic halt state will not interfere with migration.

If you deliver an apf, the guest expects a completion.

Quoted 7 lines
Quoted 3 lines

There is special completion that tells guest to wake all sleeping tasks on vcpu. It is delivered after migration on the destination.

Yes, I saw.

What if you can't deliver it? is it possible that some other vcpu

How can this happen? If I can't deliverer it I can't deliver non-broadcast apfs too.

Quoted 3 lines

will start receiving apfs that alias the old ones? Or is the broadcast global?

Broadcast is not global but tokens are unique per cpu so other vcpu will not be able to receiving apfs that alias the old ones (if I understand what you mean correctly).

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#21 lore raw

Re: [PATCH v6 02/12] Halt vcpu if page it tries to access is swapped out.

In reply to Avi Kivity
Quoted 6 lines · Avi Kivity
Quoted 5 lines · Avi Kivity
Quoted 4 lines

There is special completion that tells guest to wake all sleeping tasks on vcpu. It is delivered after migration on the destination.

Quoted 9 lines
Quoted 6 lines

Yes, I saw.

What if you can't deliver it? is it possible that some other vcpu will start receiving apfs that alias the old ones? Or is the broadcast global?

And, is the broadcast used only for migrations?

Any time apf is enabled on vcpu broadcast is sent to the vcpu. Guest should be careful here and do not write to apf msr without a reason.

--
Gleb.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>