book3s_64_mmu_hv.c 52.8 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 *
 * Copyright 2010 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
 */

#include <linux/types.h>
#include <linux/string.h>
#include <linux/kvm.h>
#include <linux/kvm_host.h>
#include <linux/highmem.h>
#include <linux/gfp.h>
#include <linux/slab.h>
#include <linux/hugetlb.h>
15
#include <linux/vmalloc.h>
16
#include <linux/srcu.h>
17 18
#include <linux/anon_inodes.h>
#include <linux/file.h>
19
#include <linux/debugfs.h>
20 21 22

#include <asm/kvm_ppc.h>
#include <asm/kvm_book3s.h>
23
#include <asm/book3s/64/mmu-hash.h>
24 25 26 27
#include <asm/hvcall.h>
#include <asm/synch.h>
#include <asm/ppc-opcode.h>
#include <asm/cputable.h>
28
#include <asm/pte-walk.h>
29

30 31
#include "trace_hv.h"

32 33 34 35 36 37 38 39 40 41 42 43 44
//#define DEBUG_RESIZE_HPT	1

#ifdef DEBUG_RESIZE_HPT
#define resize_hpt_debug(resize, ...)				\
	do {							\
		printk(KERN_DEBUG "RESIZE HPT %p: ", resize);	\
		printk(__VA_ARGS__);				\
	} while (0)
#else
#define resize_hpt_debug(resize, ...)				\
	do { } while (0)
#endif

45 46 47
static long kvmppc_virtmode_do_h_enter(struct kvm *kvm, unsigned long flags,
				long pte_index, unsigned long pteh,
				unsigned long ptel, unsigned long *pte_idx_ret);
48 49 50 51 52 53 54

struct kvm_resize_hpt {
	/* These fields read-only after init */
	struct kvm *kvm;
	struct work_struct work;
	u32 order;

55
	/* These fields protected by kvm->arch.mmu_setup_lock */
56 57 58 59 60 61

	/* Possible values and their usage:
	 *  <0     an error occurred during allocation,
	 *  -EBUSY allocation is in the progress,
	 *  0      allocation made successfuly.
	 */
62
	int error;
63

64
	/* Private to the work thread, until error != -EBUSY,
65
	 * then protected by kvm->arch.mmu_setup_lock.
66
	 */
67
	struct kvm_hpt_info hpt;
68 69
};

70
int kvmppc_allocate_hpt(struct kvm_hpt_info *info, u32 order)
71
{
72
	unsigned long hpt = 0;
73
	int cma = 0;
74
	struct page *page = NULL;
75 76
	struct revmap_entry *rev;
	unsigned long npte;
77

78 79
	if ((order < PPC_MIN_HPT_ORDER) || (order > PPC_MAX_HPT_ORDER))
		return -EINVAL;
80

81
	page = kvm_alloc_hpt_cma(1ul << (order - PAGE_SHIFT));
82 83
	if (page) {
		hpt = (unsigned long)pfn_to_kaddr(page_to_pfn(page));
84
		memset((void *)hpt, 0, (1ul << order));
85
		cma = 1;
86
	}
87

88
	if (!hpt)
89
		hpt = __get_free_pages(GFP_KERNEL|__GFP_ZERO|__GFP_RETRY_MAYFAIL
90
				       |__GFP_NOWARN, order - PAGE_SHIFT);
91 92 93 94

	if (!hpt)
		return -ENOMEM;

95 96
	/* HPTEs are 2**4 bytes long */
	npte = 1ul << (order - 4);
97

98
	/* Allocate reverse map array */
99
	rev = vmalloc(array_size(npte, sizeof(struct revmap_entry)));
100
	if (!rev) {
101 102 103 104 105
		if (cma)
			kvm_free_hpt_cma(page, 1 << (order - PAGE_SHIFT));
		else
			free_pages(hpt, order - PAGE_SHIFT);
		return -ENOMEM;
106 107
	}

108 109 110 111
	info->order = order;
	info->virt = hpt;
	info->cma = cma;
	info->rev = rev;
112 113

	return 0;
114
}
115

116 117 118 119 120 121
void kvmppc_set_hpt(struct kvm *kvm, struct kvm_hpt_info *info)
{
	atomic64_set(&kvm->arch.mmio_update, 0);
	kvm->arch.hpt = *info;
	kvm->arch.sdr1 = __pa(info->virt) | (info->order - 18);

122 123
	pr_debug("KVM guest htab at %lx (order %ld), LPID %x\n",
		 info->virt, (long)info->order, kvm->arch.lpid);
124 125
}

126
long kvmppc_alloc_reset_hpt(struct kvm *kvm, int order)
127 128
{
	long err = -EBUSY;
129
	struct kvm_hpt_info info;
130

131
	mutex_lock(&kvm->arch.mmu_setup_lock);
132 133 134
	if (kvm->arch.mmu_ready) {
		kvm->arch.mmu_ready = 0;
		/* order mmu_ready vs. vcpus_running */
135 136
		smp_mb();
		if (atomic_read(&kvm->arch.vcpus_running)) {
137
			kvm->arch.mmu_ready = 1;
138 139 140
			goto out;
		}
	}
141 142 143 144 145 146
	if (kvm_is_radix(kvm)) {
		err = kvmppc_switch_mmu_to_hpt(kvm);
		if (err)
			goto out;
	}

147 148 149
	if (kvm->arch.hpt.order == order) {
		/* We already have a suitable HPT */

150
		/* Set the entire HPT to 0, i.e. invalid HPTEs */
151
		memset((void *)kvm->arch.hpt.virt, 0, 1ul << order);
152 153 154 155
		/*
		 * Reset all the reverse-mapping chains for all memslots
		 */
		kvmppc_rmap_reset(kvm);
156
		err = 0;
157
		goto out;
158
	}
159

160
	if (kvm->arch.hpt.virt) {
161
		kvmppc_free_hpt(&kvm->arch.hpt);
162 163
		kvmppc_rmap_reset(kvm);
	}
164 165 166 167 168 169 170

	err = kvmppc_allocate_hpt(&info, order);
	if (err < 0)
		goto out;
	kvmppc_set_hpt(kvm, &info);

out:
171 172 173 174
	if (err == 0)
		/* Ensure that each vcpu will flush its TLB on next entry. */
		cpumask_setall(&kvm->arch.need_tlb_flush);

175
	mutex_unlock(&kvm->arch.mmu_setup_lock);
176 177 178
	return err;
}

179
void kvmppc_free_hpt(struct kvm_hpt_info *info)
180
{
181
	vfree(info->rev);
182
	info->rev = NULL;
183 184 185 186 187 188 189
	if (info->cma)
		kvm_free_hpt_cma(virt_to_page(info->virt),
				 1 << (info->order - PAGE_SHIFT));
	else if (info->virt)
		free_pages(info->virt, info->order - PAGE_SHIFT);
	info->virt = 0;
	info->order = 0;
190 191
}

192 193 194 195 196 197 198 199 200 201 202 203 204 205
/* Bits in first HPTE dword for pagesize 4k, 64k or 16M */
static inline unsigned long hpte0_pgsize_encoding(unsigned long pgsize)
{
	return (pgsize > 0x1000) ? HPTE_V_LARGE : 0;
}

/* Bits in second HPTE dword for pagesize 4k, 64k or 16M */
static inline unsigned long hpte1_pgsize_encoding(unsigned long pgsize)
{
	return (pgsize == 0x10000) ? 0x1000 : 0;
}

void kvmppc_map_vrma(struct kvm_vcpu *vcpu, struct kvm_memory_slot *memslot,
		     unsigned long porder)
206 207
{
	unsigned long i;
208
	unsigned long npages;
209 210
	unsigned long hp_v, hp_r;
	unsigned long addr, hash;
211 212
	unsigned long psize;
	unsigned long hp0, hp1;
213
	unsigned long idx_ret;
214
	long ret;
215
	struct kvm *kvm = vcpu->kvm;
216

217 218
	psize = 1ul << porder;
	npages = memslot->npages >> (porder - PAGE_SHIFT);
219 220

	/* VRMA can't be > 1TB */
221 222
	if (npages > 1ul << (40 - porder))
		npages = 1ul << (40 - porder);
223
	/* Can't use more than 1 HPTE per HPTEG */
224 225
	if (npages > kvmppc_hpt_mask(&kvm->arch.hpt) + 1)
		npages = kvmppc_hpt_mask(&kvm->arch.hpt) + 1;
226

227 228 229 230 231
	hp0 = HPTE_V_1TB_SEG | (VRMA_VSID << (40 - 16)) |
		HPTE_V_BOLTED | hpte0_pgsize_encoding(psize);
	hp1 = hpte1_pgsize_encoding(psize) |
		HPTE_R_R | HPTE_R_C | HPTE_R_M | PP_RWXX;

232
	for (i = 0; i < npages; ++i) {
233
		addr = i << porder;
234
		/* can't use hpt_hash since va > 64 bits */
235 236
		hash = (i ^ (VRMA_VSID ^ (VRMA_VSID << 25)))
			& kvmppc_hpt_mask(&kvm->arch.hpt);
237 238 239 240 241 242
		/*
		 * We assume that the hash table is empty and no
		 * vcpus are using it at this stage.  Since we create
		 * at most one HPTE per HPTEG, we just assume entry 7
		 * is available and use it.
		 */
243
		hash = (hash << 3) + 7;
244 245
		hp_v = hp0 | ((addr >> 16) & ~0x7fUL);
		hp_r = hp1 | addr;
246 247
		ret = kvmppc_virtmode_do_h_enter(kvm, H_EXACT, hash, hp_v, hp_r,
						 &idx_ret);
248 249 250 251 252
		if (ret != H_SUCCESS) {
			pr_err("KVM: map_vrma at %lx failed, ret=%ld\n",
			       addr, ret);
			break;
		}
253 254 255 256 257
	}
}

int kvmppc_mmu_hv_init(void)
{
258 259
	unsigned long host_lpid, rsvd_lpid;

260 261 262
	if (!mmu_has_feature(MMU_FTR_LOCKLESS_TLBIE))
		return -EINVAL;

263 264 265
	host_lpid = 0;
	if (cpu_has_feature(CPU_FTR_HVMODE))
		host_lpid = mfspr(SPRN_LPID);
266 267 268 269 270 271

	/* POWER8 and above have 12-bit LPIDs (10-bit in POWER7) */
	if (cpu_has_feature(CPU_FTR_ARCH_207S))
		rsvd_lpid = LPID_RSVD;
	else
		rsvd_lpid = LPID_RSVD_POWER7;
272

273 274 275
	kvmppc_init_lpid(rsvd_lpid + 1);

	kvmppc_claim_lpid(host_lpid);
276
	/* rsvd_lpid is reserved for use in partition switching */
277
	kvmppc_claim_lpid(rsvd_lpid);
278 279 280 281

	return 0;
}

282
static long kvmppc_virtmode_do_h_enter(struct kvm *kvm, unsigned long flags,
283 284
				long pte_index, unsigned long pteh,
				unsigned long ptel, unsigned long *pte_idx_ret)
285 286 287
{
	long ret;

288
	preempt_disable();
289
	ret = kvmppc_do_h_enter(kvm, flags, pte_index, pteh, ptel,
290
				kvm->mm->pgd, false, pte_idx_ret);
291
	preempt_enable();
292 293 294 295 296 297 298 299 300
	if (ret == H_TOO_HARD) {
		/* this can't happen */
		pr_err("KVM: Oops, kvmppc_h_enter returned too hard!\n");
		ret = H_RESOURCE;	/* or something */
	}
	return ret;

}

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
static struct kvmppc_slb *kvmppc_mmu_book3s_hv_find_slbe(struct kvm_vcpu *vcpu,
							 gva_t eaddr)
{
	u64 mask;
	int i;

	for (i = 0; i < vcpu->arch.slb_nr; i++) {
		if (!(vcpu->arch.slb[i].orige & SLB_ESID_V))
			continue;

		if (vcpu->arch.slb[i].origv & SLB_VSID_B_1T)
			mask = ESID_MASK_1T;
		else
			mask = ESID_MASK;

		if (((vcpu->arch.slb[i].orige ^ eaddr) & mask) == 0)
			return &vcpu->arch.slb[i];
	}
	return NULL;
}

static unsigned long kvmppc_mmu_get_real_addr(unsigned long v, unsigned long r,
			unsigned long ea)
{
	unsigned long ra_mask;

327
	ra_mask = kvmppc_actual_pgsz(v, r) - 1;
328 329 330
	return (r & HPTE_R_RPN & ~ra_mask) | (ea & ra_mask);
}

331
static int kvmppc_mmu_book3s_64_hv_xlate(struct kvm_vcpu *vcpu, gva_t eaddr,
332
			struct kvmppc_pte *gpte, bool data, bool iswrite)
333
{
334 335 336 337
	struct kvm *kvm = vcpu->kvm;
	struct kvmppc_slb *slbe;
	unsigned long slb_v;
	unsigned long pp, key;
338
	unsigned long v, orig_v, gr;
339
	__be64 *hptep;
340
	long int index;
341 342
	int virtmode = vcpu->arch.shregs.msr & (data ? MSR_DR : MSR_IR);

343 344 345
	if (kvm_is_radix(vcpu->kvm))
		return kvmppc_mmu_radix_xlate(vcpu, eaddr, gpte, data, iswrite);

346 347 348 349 350 351 352 353 354 355 356
	/* Get SLB entry */
	if (virtmode) {
		slbe = kvmppc_mmu_book3s_hv_find_slbe(vcpu, eaddr);
		if (!slbe)
			return -EINVAL;
		slb_v = slbe->origv;
	} else {
		/* real mode access */
		slb_v = vcpu->kvm->arch.vrma_slb_v;
	}

357
	preempt_disable();
358 359 360
	/* Find the HPTE in the hash table */
	index = kvmppc_hv_find_lock_hpte(kvm, eaddr, slb_v,
					 HPTE_V_VALID | HPTE_V_ABSENT);
361 362
	if (index < 0) {
		preempt_enable();
363
		return -ENOENT;
364
	}
365
	hptep = (__be64 *)(kvm->arch.hpt.virt + (index << 4));
366 367 368
	v = orig_v = be64_to_cpu(hptep[0]) & ~HPTE_V_HVLOCK;
	if (cpu_has_feature(CPU_FTR_ARCH_300))
		v = hpte_new_to_old_v(v, be64_to_cpu(hptep[1]));
369
	gr = kvm->arch.hpt.rev[index].guest_rpte;
370

371
	unlock_hpte(hptep, orig_v);
372
	preempt_enable();
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387

	gpte->eaddr = eaddr;
	gpte->vpage = ((v & HPTE_V_AVPN) << 4) | ((eaddr >> 12) & 0xfff);

	/* Get PP bits and key for permission check */
	pp = gr & (HPTE_R_PP0 | HPTE_R_PP);
	key = (vcpu->arch.shregs.msr & MSR_PR) ? SLB_VSID_KP : SLB_VSID_KS;
	key &= slb_v;

	/* Calculate permissions */
	gpte->may_read = hpte_read_permission(pp, key);
	gpte->may_write = hpte_write_permission(pp, key);
	gpte->may_execute = gpte->may_read && !(gr & (HPTE_R_N | HPTE_R_G));

	/* Storage key permission check for POWER7 */
388
	if (data && virtmode) {
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
		int amrfield = hpte_get_skey_perm(gr, vcpu->arch.amr);
		if (amrfield & 1)
			gpte->may_read = 0;
		if (amrfield & 2)
			gpte->may_write = 0;
	}

	/* Get the guest physical address */
	gpte->raddr = kvmppc_mmu_get_real_addr(v, gr, eaddr);
	return 0;
}

/*
 * Quick test for whether an instruction is a load or a store.
 * If the instruction is a load or a store, then this will indicate
 * which it is, at least on server processors.  (Embedded processors
 * have some external PID instructions that don't follow the rule
 * embodied here.)  If the instruction isn't a load or store, then
 * this doesn't return anything useful.
 */
static int instruction_is_store(unsigned int instr)
{
	unsigned int mask;

	mask = 0x10000000;
	if ((instr & 0xfc000000) == 0x7c000000)
		mask = 0x100;		/* major opcode 31 */
	return (instr & mask) != 0;
}

419
int kvmppc_hv_emulate_mmio(struct kvm_vcpu *vcpu,
420
			   unsigned long gpa, gva_t ea, int is_store)
421 422 423
{
	u32 last_inst;

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
	/*
	 * Fast path - check if the guest physical address corresponds to a
	 * device on the FAST_MMIO_BUS, if so we can avoid loading the
	 * instruction all together, then we can just handle it and return.
	 */
	if (is_store) {
		int idx, ret;

		idx = srcu_read_lock(&vcpu->kvm->srcu);
		ret = kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, (gpa_t) gpa, 0,
				       NULL);
		srcu_read_unlock(&vcpu->kvm->srcu, idx);
		if (!ret) {
			kvmppc_set_pc(vcpu, kvmppc_get_pc(vcpu) + 4);
			return RESUME_GUEST;
		}
	}

442
	/*
443 444
	 * If we fail, we just return to the guest and try executing it again.
	 */
445 446 447
	if (kvmppc_get_last_inst(vcpu, INST_GENERIC, &last_inst) !=
		EMULATE_DONE)
		return RESUME_GUEST;
448 449 450 451 452 453 454 455 456 457 458 459 460

	/*
	 * WARNING: We do not know for sure whether the instruction we just
	 * read from memory is the same that caused the fault in the first
	 * place.  If the instruction we read is neither an load or a store,
	 * then it can't access memory, so we don't need to worry about
	 * enforcing access permissions.  So, assuming it is a load or
	 * store, we just check that its direction (load or store) is
	 * consistent with the original fault, since that's what we
	 * checked the access permissions against.  If there is a mismatch
	 * we just return and retry the instruction.
	 */

461
	if (instruction_is_store(last_inst) != !!is_store)
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
		return RESUME_GUEST;

	/*
	 * Emulated accesses are emulated by looking at the hash for
	 * translation once, then performing the access later. The
	 * translation could be invalidated in the meantime in which
	 * point performing the subsequent memory access on the old
	 * physical address could possibly be a security hole for the
	 * guest (but not the host).
	 *
	 * This is less of an issue for MMIO stores since they aren't
	 * globally visible. It could be an issue for MMIO loads to
	 * a certain extent but we'll ignore it for now.
	 */

	vcpu->arch.paddr_accessed = gpa;
478
	vcpu->arch.vaddr_accessed = ea;
479
	return kvmppc_emulate_mmio(vcpu);
480 481
}

482
int kvmppc_book3s_hv_page_fault(struct kvm_vcpu *vcpu,
483 484 485
				unsigned long ea, unsigned long dsisr)
{
	struct kvm *kvm = vcpu->kvm;
486
	unsigned long hpte[3], r;
487
	unsigned long hnow_v, hnow_r;
488
	__be64 *hptep;
489
	unsigned long mmu_seq, psize, pte_size;
490
	unsigned long gpa_base, gfn_base;
491
	unsigned long gpa, gfn, hva, pfn, hpa;
492
	struct kvm_memory_slot *memslot;
493
	unsigned long *rmap;
494
	struct revmap_entry *rev;
495 496
	struct page *page;
	long index, ret;
497
	bool is_ci;
498 499
	bool writing, write_ok;
	unsigned int shift;
500
	unsigned long rcbits;
501
	long mmio_update;
502
	pte_t pte, *ptep;
503

504
	if (kvm_is_radix(kvm))
505
		return kvmppc_book3s_radix_page_fault(vcpu, ea, dsisr);
506

507 508 509 510 511 512 513 514
	/*
	 * Real-mode code has already searched the HPT and found the
	 * entry we're interested in.  Lock the entry and check that
	 * it hasn't changed.  If it has, just return and re-execute the
	 * instruction.
	 */
	if (ea != vcpu->arch.pgfault_addr)
		return RESUME_GUEST;
515 516 517 518 519

	if (vcpu->arch.pgfault_cache) {
		mmio_update = atomic64_read(&kvm->arch.mmio_update);
		if (mmio_update == vcpu->arch.pgfault_cache->mmio_update) {
			r = vcpu->arch.pgfault_cache->rpte;
520 521
			psize = kvmppc_actual_pgsz(vcpu->arch.pgfault_hpte[0],
						   r);
522 523 524
			gpa_base = r & HPTE_R_RPN & ~(psize - 1);
			gfn_base = gpa_base >> PAGE_SHIFT;
			gpa = gpa_base | (ea & (psize - 1));
525
			return kvmppc_hv_emulate_mmio(vcpu, gpa, ea,
526 527 528
						dsisr & DSISR_ISSTORE);
		}
	}
529
	index = vcpu->arch.pgfault_index;
530 531
	hptep = (__be64 *)(kvm->arch.hpt.virt + (index << 4));
	rev = &kvm->arch.hpt.rev[index];
532 533 534
	preempt_disable();
	while (!try_lock_hpte(hptep, HPTE_V_HVLOCK))
		cpu_relax();
535 536
	hpte[0] = be64_to_cpu(hptep[0]) & ~HPTE_V_HVLOCK;
	hpte[1] = be64_to_cpu(hptep[1]);
537
	hpte[2] = r = rev->guest_rpte;
538
	unlock_hpte(hptep, hpte[0]);
539 540
	preempt_enable();

541 542 543 544
	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
		hpte[0] = hpte_new_to_old_v(hpte[0], hpte[1]);
		hpte[1] = hpte_new_to_old_r(hpte[1]);
	}
545 546 547 548 549
	if (hpte[0] != vcpu->arch.pgfault_hpte[0] ||
	    hpte[1] != vcpu->arch.pgfault_hpte[1])
		return RESUME_GUEST;

	/* Translate the logical address and get the page */
550
	psize = kvmppc_actual_pgsz(hpte[0], r);
551 552 553
	gpa_base = r & HPTE_R_RPN & ~(psize - 1);
	gfn_base = gpa_base >> PAGE_SHIFT;
	gpa = gpa_base | (ea & (psize - 1));
554
	gfn = gpa >> PAGE_SHIFT;
555 556
	memslot = gfn_to_memslot(kvm, gfn);

557 558
	trace_kvm_page_fault_enter(vcpu, hpte, memslot, ea, dsisr);

559
	/* No memslot means it's an emulated MMIO region */
560
	if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
561
		return kvmppc_hv_emulate_mmio(vcpu, gpa, ea,
562 563
					      dsisr & DSISR_ISSTORE);

564 565 566 567 568 569 570
	/*
	 * This should never happen, because of the slot_is_aligned()
	 * check in kvmppc_do_h_enter().
	 */
	if (gfn_base < memslot->base_gfn)
		return -EFAULT;

571 572 573 574
	/* used to check for invalidations in progress */
	mmu_seq = kvm->mmu_notifier_seq;
	smp_rmb();

575
	ret = -EFAULT;
576
	page = NULL;
577 578 579
	writing = (dsisr & DSISR_ISSTORE) != 0;
	/* If writing != 0, then the HPTE must allow writing, if we get here */
	write_ok = writing;
580
	hva = gfn_to_hva_memslot(memslot, gfn);
581 582 583 584 585 586 587

	/*
	 * Do a fast check first, since __gfn_to_pfn_memslot doesn't
	 * do it with !atomic && !async, which is how we call it.
	 * We always ask for write permission since the common case
	 * is that the page is writable.
	 */
588
	if (get_user_page_fast_only(hva, FOLL_WRITE, &page)) {
589
		write_ok = true;
590
	} else {
591 592 593 594 595 596 597 598 599 600
		/* Call KVM generic code to do the slow-path check */
		pfn = __gfn_to_pfn_memslot(memslot, gfn, false, NULL,
					   writing, &write_ok);
		if (is_error_noslot_pfn(pfn))
			return -EFAULT;
		page = NULL;
		if (pfn_valid(pfn)) {
			page = pfn_to_page(pfn);
			if (PageReserved(page))
				page = NULL;
601
		}
602 603
	}

604 605 606 607
	/*
	 * Read the PTE from the process' radix tree and use that
	 * so we get the shift and attribute bits.
	 */
608 609
	spin_lock(&kvm->mmu_lock);
	ptep = find_kvm_host_pte(kvm, mmu_seq, hva, &shift);
610 611
	pte = __pte(0);
	if (ptep)
612 613
		pte = READ_ONCE(*ptep);
	spin_unlock(&kvm->mmu_lock);
614 615 616 617
	/*
	 * If the PTE disappeared temporarily due to a THP
	 * collapse, just return and let the guest try again.
	 */
618
	if (!pte_present(pte)) {
619 620 621 622 623 624 625 626 627 628
		if (page)
			put_page(page);
		return RESUME_GUEST;
	}
	hpa = pte_pfn(pte) << PAGE_SHIFT;
	pte_size = PAGE_SIZE;
	if (shift)
		pte_size = 1ul << shift;
	is_ci = pte_ci(pte);

629 630
	if (psize > pte_size)
		goto out_put;
631 632
	if (pte_size > psize)
		hpa |= hva & (pte_size - psize);
633 634

	/* Check WIMG vs. the actual page we're accessing */
635 636
	if (!hpte_cache_flags_ok(r, is_ci)) {
		if (is_ci)
637
			goto out_put;
638 639 640 641 642 643 644
		/*
		 * Allow guest to map emulated device memory as
		 * uncacheable, but actually make it cacheable.
		 */
		r = (r & ~(HPTE_R_W|HPTE_R_I|HPTE_R_G)) | HPTE_R_M;
	}

645
	/*
646 647
	 * Set the HPTE to point to hpa.
	 * Since the hpa is at PAGE_SIZE granularity, make sure we
648 649 650 651
	 * don't mask out lower-order bits if psize < PAGE_SIZE.
	 */
	if (psize < PAGE_SIZE)
		psize = PAGE_SIZE;
652
	r = (r & HPTE_R_KEY_HI) | (r & ~(HPTE_R_PP0 - psize)) | hpa;
653 654
	if (hpte_is_writable(r) && !write_ok)
		r = hpte_make_readonly(r);
655 656 657 658
	ret = RESUME_GUEST;
	preempt_disable();
	while (!try_lock_hpte(hptep, HPTE_V_HVLOCK))
		cpu_relax();
659 660 661 662 663 664
	hnow_v = be64_to_cpu(hptep[0]);
	hnow_r = be64_to_cpu(hptep[1]);
	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
		hnow_v = hpte_new_to_old_v(hnow_v, hnow_r);
		hnow_r = hpte_new_to_old_r(hnow_r);
	}
665 666 667 668

	/*
	 * If the HPT is being resized, don't update the HPTE,
	 * instead let the guest retry after the resize operation is complete.
669
	 * The synchronization for mmu_ready test vs. set is provided
670 671
	 * by the HPTE lock.
	 */
672
	if (!kvm->arch.mmu_ready)
673 674
		goto out_unlock;

675 676
	if ((hnow_v & ~HPTE_V_HVLOCK) != hpte[0] || hnow_r != hpte[1] ||
	    rev->guest_rpte != hpte[2])
677 678 679 680
		/* HPTE has been changed under us; let the guest retry */
		goto out_unlock;
	hpte[0] = (hpte[0] & ~HPTE_V_ABSENT) | HPTE_V_VALID;

681 682
	/* Always put the HPTE in the rmap chain for the page base address */
	rmap = &memslot->arch.rmap[gfn_base - memslot->base_gfn];
683 684 685 686
	lock_rmap(rmap);

	/* Check if we might have been invalidated; let the guest retry if so */
	ret = RESUME_GUEST;
687
	if (mmu_notifier_retry(vcpu->kvm, mmu_seq)) {
688 689 690
		unlock_rmap(rmap);
		goto out_unlock;
	}
691

692 693 694 695
	/* Only set R/C in real HPTE if set in both *rmap and guest_rpte */
	rcbits = *rmap >> KVMPPC_RMAP_RC_SHIFT;
	r &= rcbits | ~(HPTE_R_R | HPTE_R_C);

696
	if (be64_to_cpu(hptep[0]) & HPTE_V_VALID) {
697 698
		/* HPTE was previously valid, so we need to invalidate it */
		unlock_rmap(rmap);
699
		hptep[0] |= cpu_to_be64(HPTE_V_ABSENT);
700
		kvmppc_invalidate_hpte(kvm, hptep, index);
701
		/* don't lose previous R and C bits */
702
		r |= be64_to_cpu(hptep[1]) & (HPTE_R_R | HPTE_R_C);
703 704 705
	} else {
		kvmppc_add_revmap_chain(kvm, rev, rmap, index, 0);
	}
706

707 708 709 710
	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
		r = hpte_old_to_new_r(hpte[0], r);
		hpte[0] = hpte_old_to_new_v(hpte[0]);
	}
711
	hptep[1] = cpu_to_be64(r);
712
	eieio();
713
	__unlock_hpte(hptep, hpte[0]);
714 715
	asm volatile("ptesync" : : : "memory");
	preempt_enable();
716
	if (page && hpte_is_writable(r))
717
		set_page_dirty_lock(page);
718 719

 out_put:
720 721
	trace_kvm_page_fault_exit(vcpu, hpte, ret);

722 723
	if (page)
		put_page(page);
724 725 726
	return ret;

 out_unlock:
727
	__unlock_hpte(hptep, be64_to_cpu(hptep[0]));
728 729 730 731
	preempt_enable();
	goto out_put;
}

732
void kvmppc_rmap_reset(struct kvm *kvm)
733 734 735 736 737 738
{
	struct kvm_memslots *slots;
	struct kvm_memory_slot *memslot;
	int srcu_idx;

	srcu_idx = srcu_read_lock(&kvm->srcu);
739
	slots = kvm_memslots(kvm);
740
	kvm_for_each_memslot(memslot, slots) {
741 742
		/* Mutual exclusion with kvm_unmap_hva_range etc. */
		spin_lock(&kvm->mmu_lock);
743 744 745 746 747 748
		/*
		 * This assumes it is acceptable to lose reference and
		 * change bits across a reset.
		 */
		memset(memslot->arch.rmap, 0,
		       memslot->npages * sizeof(*memslot->arch.rmap));
749
		spin_unlock(&kvm->mmu_lock);
750 751 752 753
	}
	srcu_read_unlock(&kvm->srcu, srcu_idx);
}

754 755 756
typedef int (*hva_handler_fn)(struct kvm *kvm, struct kvm_memory_slot *memslot,
			      unsigned long gfn);

757 758 759
static int kvm_handle_hva_range(struct kvm *kvm,
				unsigned long start,
				unsigned long end,
760
				hva_handler_fn handler)
761 762 763 764 765 766 767 768
{
	int ret;
	int retval = 0;
	struct kvm_memslots *slots;
	struct kvm_memory_slot *memslot;

	slots = kvm_memslots(kvm);
	kvm_for_each_memslot(memslot, slots) {
769 770 771 772 773 774 775 776 777 778 779 780 781 782
		unsigned long hva_start, hva_end;
		gfn_t gfn, gfn_end;

		hva_start = max(start, memslot->userspace_addr);
		hva_end = min(end, memslot->userspace_addr +
					(memslot->npages << PAGE_SHIFT));
		if (hva_start >= hva_end)
			continue;
		/*
		 * {gfn(page) | page intersects with [hva_start, hva_end)} =
		 * {gfn, gfn+1, ..., gfn_end-1}.
		 */
		gfn = hva_to_gfn_memslot(hva_start, memslot);
		gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
783

784
		for (; gfn < gfn_end; ++gfn) {
785
			ret = handler(kvm, memslot, gfn);
786 787 788 789 790 791 792
			retval |= ret;
		}
	}

	return retval;
}

793
static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
794
			  hva_handler_fn handler)
795 796 797 798
{
	return kvm_handle_hva_range(kvm, hva, hva + 1, handler);
}

799 800
/* Must be called with both HPTE and rmap locked */
static void kvmppc_unmap_hpte(struct kvm *kvm, unsigned long i,
801
			      struct kvm_memory_slot *memslot,
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
			      unsigned long *rmapp, unsigned long gfn)
{
	__be64 *hptep = (__be64 *) (kvm->arch.hpt.virt + (i << 4));
	struct revmap_entry *rev = kvm->arch.hpt.rev;
	unsigned long j, h;
	unsigned long ptel, psize, rcbits;

	j = rev[i].forw;
	if (j == i) {
		/* chain is now empty */
		*rmapp &= ~(KVMPPC_RMAP_PRESENT | KVMPPC_RMAP_INDEX);
	} else {
		/* remove i from chain */
		h = rev[i].back;
		rev[h].forw = j;
		rev[j].back = h;
		rev[i].forw = rev[i].back = i;
		*rmapp = (*rmapp & ~KVMPPC_RMAP_INDEX) | j;
	}

	/* Now check and modify the HPTE */
	ptel = rev[i].guest_rpte;
824
	psize = kvmppc_actual_pgsz(be64_to_cpu(hptep[0]), ptel);
825 826 827 828 829 830 831 832
	if ((be64_to_cpu(hptep[0]) & HPTE_V_VALID) &&
	    hpte_rpn(ptel, psize) == gfn) {
		hptep[0] |= cpu_to_be64(HPTE_V_ABSENT);
		kvmppc_invalidate_hpte(kvm, hptep, i);
		hptep[1] &= ~cpu_to_be64(HPTE_R_KEY_HI | HPTE_R_KEY_LO);
		/* Harvest R and C */
		rcbits = be64_to_cpu(hptep[1]) & (HPTE_R_R | HPTE_R_C);
		*rmapp |= rcbits << KVMPPC_RMAP_RC_SHIFT;
833 834
		if ((rcbits & HPTE_R_C) && memslot->dirty_bitmap)
			kvmppc_update_dirty_map(memslot, gfn, psize);
835 836 837 838 839 840 841
		if (rcbits & ~rev[i].guest_rpte) {
			rev[i].guest_rpte = ptel | rcbits;
			note_hpte_modification(kvm, &rev[i]);
		}
	}
}

842
static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot,
843 844
			   unsigned long gfn)
{
845
	unsigned long i;
846
	__be64 *hptep;
847
	unsigned long *rmapp;
848

849
	rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
850
	for (;;) {
851
		lock_rmap(rmapp);
852
		if (!(*rmapp & KVMPPC_RMAP_PRESENT)) {
853
			unlock_rmap(rmapp);
854 855 856 857 858
			break;
		}

		/*
		 * To avoid an ABBA deadlock with the HPTE lock bit,
859 860
		 * we can't spin on the HPTE lock while holding the
		 * rmap chain lock.
861 862
		 */
		i = *rmapp & KVMPPC_RMAP_INDEX;
863
		hptep = (__be64 *) (kvm->arch.hpt.virt + (i << 4));
864 865 866
		if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) {
			/* unlock rmap before spinning on the HPTE lock */
			unlock_rmap(rmapp);
867
			while (be64_to_cpu(hptep[0]) & HPTE_V_HVLOCK)
868 869 870
				cpu_relax();
			continue;
		}
871

872
		kvmppc_unmap_hpte(kvm, i, memslot, rmapp, gfn);
873
		unlock_rmap(rmapp);
874
		__unlock_hpte(hptep, be64_to_cpu(hptep[0]));
875 876 877 878
	}
	return 0;
}

879
int kvm_unmap_hva_range_hv(struct kvm *kvm, unsigned long start, unsigned long end)
880
{
881 882 883 884
	hva_handler_fn handler;

	handler = kvm_is_radix(kvm) ? kvm_unmap_radix : kvm_unmap_rmapp;
	kvm_handle_hva_range(kvm, start, end, handler);
885 886 887
	return 0;
}

888 889
void kvmppc_core_flush_memslot_hv(struct kvm *kvm,
				  struct kvm_memory_slot *memslot)
890 891 892
{
	unsigned long gfn;
	unsigned long n;
893
	unsigned long *rmapp;
894 895

	gfn = memslot->base_gfn;
896
	rmapp = memslot->arch.rmap;
897 898 899 900 901
	if (kvm_is_radix(kvm)) {
		kvmppc_radix_flush_memslot(kvm, memslot);
		return;
	}

902
	for (n = memslot->npages; n; --n, ++gfn) {
903 904 905 906 907 908 909
		/*
		 * Testing the present bit without locking is OK because
		 * the memslot has been marked invalid already, and hence
		 * no new HPTEs referencing this page can be created,
		 * thus the present bit can't go from 0 to 1.
		 */
		if (*rmapp & KVMPPC_RMAP_PRESENT)
910
			kvm_unmap_rmapp(kvm, memslot, gfn);
911 912 913 914
		++rmapp;
	}
}

915
static int kvm_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot,
916 917
			 unsigned long gfn)
{
918
	struct revmap_entry *rev = kvm->arch.hpt.rev;
919
	unsigned long head, i, j;
920
	__be64 *hptep;
921
	int ret = 0;
922
	unsigned long *rmapp;
923

924
	rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
925 926 927 928 929 930 931 932 933 934 935 936 937
 retry:
	lock_rmap(rmapp);
	if (*rmapp & KVMPPC_RMAP_REFERENCED) {
		*rmapp &= ~KVMPPC_RMAP_REFERENCED;
		ret = 1;
	}
	if (!(*rmapp & KVMPPC_RMAP_PRESENT)) {
		unlock_rmap(rmapp);
		return ret;
	}

	i = head = *rmapp & KVMPPC_RMAP_INDEX;
	do {
938
		hptep = (__be64 *) (kvm->arch.hpt.virt + (i << 4));
939 940 941
		j = rev[i].forw;

		/* If this HPTE isn't referenced, ignore it */
942
		if (!(be64_to_cpu(hptep[1]) & HPTE_R_R))
943 944 945 946 947
			continue;

		if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) {
			/* unlock rmap before spinning on the HPTE lock */
			unlock_rmap(rmapp);
948
			while (be64_to_cpu(hptep[0]) & HPTE_V_HVLOCK)
949 950 951 952 953
				cpu_relax();
			goto retry;
		}

		/* Now check and modify the HPTE */
954 955
		if ((be64_to_cpu(hptep[0]) & HPTE_V_VALID) &&
		    (be64_to_cpu(hptep[1]) & HPTE_R_R)) {
956
			kvmppc_clear_ref_hpte(kvm, hptep, i);
957 958 959 960
			if (!(rev[i].guest_rpte & HPTE_R_R)) {
				rev[i].guest_rpte |= HPTE_R_R;
				note_hpte_modification(kvm, &rev[i]);
			}
961 962
			ret = 1;
		}
963
		__unlock_hpte(hptep, be64_to_cpu(hptep[0]));
964 965 966 967
	} while ((i = j) != head);

	unlock_rmap(rmapp);
	return ret;
968 969
}

970
int kvm_age_hva_hv(struct kvm *kvm, unsigned long start, unsigned long end)
971
{
972 973 974 975
	hva_handler_fn handler;

	handler = kvm_is_radix(kvm) ? kvm_age_radix : kvm_age_rmapp;
	return kvm_handle_hva_range(kvm, start, end, handler);
976 977
}

978
static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot,
979 980
			      unsigned long gfn)
{
981
	struct revmap_entry *rev = kvm->arch.hpt.rev;
982 983 984
	unsigned long head, i, j;
	unsigned long *hp;
	int ret = 1;
985
	unsigned long *rmapp;
986

987
	rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
988 989 990 991 992 993 994 995 996 997
	if (*rmapp & KVMPPC_RMAP_REFERENCED)
		return 1;

	lock_rmap(rmapp);
	if (*rmapp & KVMPPC_RMAP_REFERENCED)
		goto out;

	if (*rmapp & KVMPPC_RMAP_PRESENT) {
		i = head = *rmapp & KVMPPC_RMAP_INDEX;
		do {
998
			hp = (unsigned long *)(kvm->arch.hpt.virt + (i << 4));
999
			j = rev[i].forw;
1000
			if (be64_to_cpu(hp[1]) & HPTE_R_R)
1001 1002 1003 1004 1005 1006 1007 1008
				goto out;
		} while ((i = j) != head);
	}
	ret = 0;

 out:
	unlock_rmap(rmapp);
	return ret;
1009 1010
}

1011
int kvm_test_age_hva_hv(struct kvm *kvm, unsigned long hva)
1012
{
1013 1014 1015 1016
	hva_handler_fn handler;

	handler = kvm_is_radix(kvm) ? kvm_test_age_radix : kvm_test_age_rmapp;
	return kvm_handle_hva(kvm, hva, handler);
1017 1018
}

1019
void kvm_set_spte_hva_hv(struct kvm *kvm, unsigned long hva, pte_t pte)
1020
{
1021 1022 1023 1024
	hva_handler_fn handler;

	handler = kvm_is_radix(kvm) ? kvm_unmap_radix : kvm_unmap_rmapp;
	kvm_handle_hva(kvm, hva, handler);
1025 1026
}

1027 1028 1029 1030 1031
static int vcpus_running(struct kvm *kvm)
{
	return atomic_read(&kvm->arch.vcpus_running) != 0;
}

1032 1033 1034 1035 1036
/*
 * Returns the number of system pages that are dirty.
 * This can be more than 1 if we find a huge-page HPTE.
 */
static int kvm_test_clear_dirty_npages(struct kvm *kvm, unsigned long *rmapp)
1037
{
1038
	struct revmap_entry *rev = kvm->arch.hpt.rev;
1039
	unsigned long head, i, j;
1040
	unsigned long n;
1041
	unsigned long v, r;
1042
	__be64 *hptep;
1043
	int npages_dirty = 0;
1044 1045 1046 1047 1048

 retry:
	lock_rmap(rmapp);
	if (!(*rmapp & KVMPPC_RMAP_PRESENT)) {
		unlock_rmap(rmapp);
1049
		return npages_dirty;
1050 1051 1052 1053
	}

	i = head = *rmapp & KVMPPC_RMAP_INDEX;
	do {
1054
		unsigned long hptep1;
1055
		hptep = (__be64 *) (kvm->arch.hpt.virt + (i << 4));
1056 1057
		j = rev[i].forw;

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
		/*
		 * Checking the C (changed) bit here is racy since there
		 * is no guarantee about when the hardware writes it back.
		 * If the HPTE is not writable then it is stable since the
		 * page can't be written to, and we would have done a tlbie
		 * (which forces the hardware to complete any writeback)
		 * when making the HPTE read-only.
		 * If vcpus are running then this call is racy anyway
		 * since the page could get dirtied subsequently, so we
		 * expect there to be a further call which would pick up
		 * any delayed C bit writeback.
		 * Otherwise we need to do the tlbie even if C==0 in
		 * order to pick up any delayed writeback of C.
		 */
1072 1073 1074
		hptep1 = be64_to_cpu(hptep[1]);
		if (!(hptep1 & HPTE_R_C) &&
		    (!hpte_is_writable(hptep1) || vcpus_running(kvm)))
1075 1076 1077 1078 1079
			continue;

		if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) {
			/* unlock rmap before spinning on the HPTE lock */
			unlock_rmap(rmapp);
1080
			while (hptep[0] & cpu_to_be64(HPTE_V_HVLOCK))
1081 1082 1083 1084 1085
				cpu_relax();
			goto retry;
		}

		/* Now check and modify the HPTE */
1086
		if (!(hptep[0] & cpu_to_be64(HPTE_V_VALID))) {
1087
			__unlock_hpte(hptep, be64_to_cpu(hptep[0]));
1088
			continue;
1089
		}
1090 1091

		/* need to make it temporarily absent so C is stable */
1092
		hptep[0] |= cpu_to_be64(HPTE_V_ABSENT);
1093
		kvmppc_invalidate_hpte(kvm, hptep, i);
1094 1095
		v = be64_to_cpu(hptep[0]);
		r = be64_to_cpu(hptep[1]);
1096
		if (r & HPTE_R_C) {
1097
			hptep[1] = cpu_to_be64(r & ~HPTE_R_C);
1098 1099 1100 1101
			if (!(rev[i].guest_rpte & HPTE_R_C)) {
				rev[i].guest_rpte |= HPTE_R_C;
				note_hpte_modification(kvm, &rev[i]);
			}
1102
			n = kvmppc_actual_pgsz(v, r);
1103 1104 1105
			n = (n + PAGE_SIZE - 1) >> PAGE_SHIFT;
			if (n > npages_dirty)
				npages_dirty = n;
1106
			eieio();
1107
		}
1108
		v &= ~HPTE_V_ABSENT;
1109
		v |= HPTE_V_VALID;
1110
		__unlock_hpte(hptep, v);
1111 1112 1113
	} while ((i = j) != head);

	unlock_rmap(rmapp);
1114
	return npages_dirty;
1115 1116
}

1117
void kvmppc_harvest_vpa_dirty(struct kvmppc_vpa *vpa,
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
			      struct kvm_memory_slot *memslot,
			      unsigned long *map)
{
	unsigned long gfn;

	if (!vpa->dirty || !vpa->pinned_addr)
		return;
	gfn = vpa->gpa >> PAGE_SHIFT;
	if (gfn < memslot->base_gfn ||
	    gfn >= memslot->base_gfn + memslot->npages)
		return;

	vpa->dirty = false;
	if (map)
		__set_bit_le(gfn - memslot->base_gfn, map);
}

1135 1136
long kvmppc_hv_get_dirty_log_hpt(struct kvm *kvm,
			struct kvm_memory_slot *memslot, unsigned long *map)
1137
{
1138
	unsigned long i;
1139
	unsigned long *rmapp;
1140 1141

	preempt_disable();
1142
	rmapp = memslot->arch.rmap;
1143
	for (i = 0; i < memslot->npages; ++i) {
1144 1145 1146 1147 1148 1149
		int npages = kvm_test_clear_dirty_npages(kvm, rmapp);
		/*
		 * Note that if npages > 0 then i must be a multiple of npages,
		 * since we always put huge-page HPTEs in the rmap chain
		 * corresponding to their page base address.
		 */
1150 1151
		if (npages)
			set_dirty_bits(map, i, npages);
1152 1153 1154 1155 1156 1157
		++rmapp;
	}
	preempt_enable();
	return 0;
}

1158 1159 1160 1161 1162
void *kvmppc_pin_guest_page(struct kvm *kvm, unsigned long gpa,
			    unsigned long *nb_ret)
{
	struct kvm_memory_slot *memslot;
	unsigned long gfn = gpa >> PAGE_SHIFT;
1163 1164
	struct page *page, *pages[1];
	int npages;
1165
	unsigned long hva, offset;
1166
	int srcu_idx;
1167

1168
	srcu_idx = srcu_read_lock(&kvm->srcu);
1169 1170
	memslot = gfn_to_memslot(kvm, gfn);
	if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
1171
		goto err;
1172
	hva = gfn_to_hva_memslot(memslot, gfn);
1173
	npages = get_user_pages_fast(hva, 1, FOLL_WRITE, pages);
1174 1175 1176
	if (npages < 1)
		goto err;
	page = pages[0];
1177 1178
	srcu_read_unlock(&kvm->srcu, srcu_idx);

1179
	offset = gpa & (PAGE_SIZE - 1);
1180
	if (nb_ret)
1181
		*nb_ret = PAGE_SIZE - offset;
1182
	return page_address(page) + offset;
1183 1184 1185 1186

 err:
	srcu_read_unlock(&kvm->srcu, srcu_idx);
	return NULL;
1187 1188
}

1189 1190
void kvmppc_unpin_guest_page(struct kvm *kvm, void *va, unsigned long gpa,
			     bool dirty)
1191 1192
{
	struct page *page = virt_to_page(va);
1193 1194 1195
	struct kvm_memory_slot *memslot;
	unsigned long gfn;
	int srcu_idx;
1196 1197

	put_page(page);
1198

1199
	if (!dirty)
1200 1201
		return;

1202
	/* We need to mark this page dirty in the memslot dirty_bitmap, if any */
1203 1204 1205
	gfn = gpa >> PAGE_SHIFT;
	srcu_idx = srcu_read_lock(&kvm->srcu);
	memslot = gfn_to_memslot(kvm, gfn);
1206 1207
	if (memslot && memslot->dirty_bitmap)
		set_bit_le(gfn - memslot->base_gfn, memslot->dirty_bitmap);
1208
	srcu_read_unlock(&kvm->srcu, srcu_idx);
1209 1210
}

1211 1212 1213 1214 1215
/*
 * HPT resizing
 */
static int resize_hpt_allocate(struct kvm_resize_hpt *resize)
{
1216 1217 1218 1219 1220 1221 1222 1223 1224
	int rc;

	rc = kvmppc_allocate_hpt(&resize->hpt, resize->order);
	if (rc < 0)
		return rc;

	resize_hpt_debug(resize, "resize_hpt_allocate(): HPT @ 0x%lx\n",
			 resize->hpt.virt);

1225 1226 1227
	return 0;
}

1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
static unsigned long resize_hpt_rehash_hpte(struct kvm_resize_hpt *resize,
					    unsigned long idx)
{
	struct kvm *kvm = resize->kvm;
	struct kvm_hpt_info *old = &kvm->arch.hpt;
	struct kvm_hpt_info *new = &resize->hpt;
	unsigned long old_hash_mask = (1ULL << (old->order - 7)) - 1;
	unsigned long new_hash_mask = (1ULL << (new->order - 7)) - 1;
	__be64 *hptep, *new_hptep;
	unsigned long vpte, rpte, guest_rpte;
	int ret;
	struct revmap_entry *rev;
1240
	unsigned long apsize, avpn, pteg, hash;
1241
	unsigned long new_idx, new_pteg, replace_vpte;
1242
	int pshift;
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262

	hptep = (__be64 *)(old->virt + (idx << 4));

	/* Guest is stopped, so new HPTEs can't be added or faulted
	 * in, only unmapped or altered by host actions.  So, it's
	 * safe to check this before we take the HPTE lock */
	vpte = be64_to_cpu(hptep[0]);
	if (!(vpte & HPTE_V_VALID) && !(vpte & HPTE_V_ABSENT))
		return 0; /* nothing to do */

	while (!try_lock_hpte(hptep, HPTE_V_HVLOCK))
		cpu_relax();

	vpte = be64_to_cpu(hptep[0]);

	ret = 0;
	if (!(vpte & HPTE_V_VALID) && !(vpte & HPTE_V_ABSENT))
		/* Nothing to do */
		goto out;

1263 1264 1265 1266 1267
	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
		rpte = be64_to_cpu(hptep[1]);
		vpte = hpte_new_to_old_v(vpte, rpte);
	}

1268 1269 1270 1271 1272
	/* Unmap */
	rev = &old->rev[idx];
	guest_rpte = rev->guest_rpte;

	ret = -EIO;
1273
	apsize = kvmppc_actual_pgsz(vpte, guest_rpte);
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
	if (!apsize)
		goto out;

	if (vpte & HPTE_V_VALID) {
		unsigned long gfn = hpte_rpn(guest_rpte, apsize);
		int srcu_idx = srcu_read_lock(&kvm->srcu);
		struct kvm_memory_slot *memslot =
			__gfn_to_memslot(kvm_memslots(kvm), gfn);

		if (memslot) {
			unsigned long *rmapp;
			rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];

			lock_rmap(rmapp);
1288
			kvmppc_unmap_hpte(kvm, idx, memslot, rmapp, gfn);
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
			unlock_rmap(rmapp);
		}

		srcu_read_unlock(&kvm->srcu, srcu_idx);
	}

	/* Reload PTE after unmap */
	vpte = be64_to_cpu(hptep[0]);
	BUG_ON(vpte & HPTE_V_VALID);
	BUG_ON(!(vpte & HPTE_V_ABSENT));

	ret = 0;
	if (!(vpte & HPTE_V_BOLTED))
		goto out;

	rpte = be64_to_cpu(hptep[1]);
1305 1306 1307 1308 1309 1310

	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
		vpte = hpte_new_to_old_v(vpte, rpte);
		rpte = hpte_new_to_old_r(rpte);
	}

1311 1312
	pshift = kvmppc_hpte_base_page_shift(vpte, rpte);
	avpn = HPTE_V_AVPN_VAL(vpte) & ~(((1ul << pshift) - 1) >> 23);
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
	pteg = idx / HPTES_PER_GROUP;
	if (vpte & HPTE_V_SECONDARY)
		pteg = ~pteg;

	if (!(vpte & HPTE_V_1TB_SEG)) {
		unsigned long offset, vsid;

		/* We only have 28 - 23 bits of offset in avpn */
		offset = (avpn & 0x1f) << 23;
		vsid = avpn >> 5;
		/* We can find more bits from the pteg value */
1324 1325
		if (pshift < 23)
			offset |= ((vsid ^ pteg) & old_hash_mask) << pshift;
1326

1327
		hash = vsid ^ (offset >> pshift);
1328 1329 1330 1331 1332 1333
	} else {
		unsigned long offset, vsid;

		/* We only have 40 - 23 bits of seg_off in avpn */
		offset = (avpn & 0x1ffff) << 23;
		vsid = avpn >> 17;
1334 1335
		if (pshift < 23)
			offset |= ((vsid ^ (vsid << 25) ^ pteg) & old_hash_mask) << pshift;
1336

1337
		hash = vsid ^ (vsid << 25) ^ (offset >> pshift);
1338 1339 1340
	}

	new_pteg = hash & new_hash_mask;
1341 1342
	if (vpte & HPTE_V_SECONDARY)
		new_pteg = ~hash & new_hash_mask;
1343 1344 1345 1346 1347

	new_idx = new_pteg * HPTES_PER_GROUP + (idx % HPTES_PER_GROUP);
	new_hptep = (__be64 *)(new->virt + (new_idx << 4));

	replace_vpte = be64_to_cpu(new_hptep[0]);
1348 1349 1350 1351
	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
		unsigned long replace_rpte = be64_to_cpu(new_hptep[1]);
		replace_vpte = hpte_new_to_old_v(replace_vpte, replace_rpte);
	}
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366

	if (replace_vpte & (HPTE_V_VALID | HPTE_V_ABSENT)) {
		BUG_ON(new->order >= old->order);

		if (replace_vpte & HPTE_V_BOLTED) {
			if (vpte & HPTE_V_BOLTED)
				/* Bolted collision, nothing we can do */
				ret = -ENOSPC;
			/* Discard the new HPTE */
			goto out;
		}

		/* Discard the previous HPTE */
	}

1367 1368 1369 1370 1371
	if (cpu_has_feature(CPU_FTR_ARCH_300)) {
		rpte = hpte_old_to_new_r(vpte, rpte);
		vpte = hpte_old_to_new_v(vpte);
	}

1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
	new_hptep[1] = cpu_to_be64(rpte);
	new->rev[new_idx].guest_rpte = guest_rpte;
	/* No need for a barrier, since new HPT isn't active */
	new_hptep[0] = cpu_to_be64(vpte);
	unlock_hpte(new_hptep, vpte);

out:
	unlock_hpte(hptep, vpte);
	return ret;
}

1383 1384
static int resize_hpt_rehash(struct kvm_resize_hpt *resize)
{
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
	struct kvm *kvm = resize->kvm;
	unsigned  long i;
	int rc;

	for (i = 0; i < kvmppc_hpt_npte(&kvm->arch.hpt); i++) {
		rc = resize_hpt_rehash_hpte(resize, i);
		if (rc != 0)
			return rc;
	}

	return 0;
1396 1397 1398 1399
}

static void resize_hpt_pivot(struct kvm_resize_hpt *resize)
{
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
	struct kvm *kvm = resize->kvm;
	struct kvm_hpt_info hpt_tmp;

	/* Exchange the pending tables in the resize structure with
	 * the active tables */

	resize_hpt_debug(resize, "resize_hpt_pivot()\n");

	spin_lock(&kvm->mmu_lock);
	asm volatile("ptesync" : : : "memory");

	hpt_tmp = kvm->arch.hpt;
	kvmppc_set_hpt(kvm, &resize->hpt);
	resize->hpt = hpt_tmp;

	spin_unlock(&kvm->mmu_lock);

	synchronize_srcu_expedited(&kvm->srcu);

1419 1420 1421
	if (cpu_has_feature(CPU_FTR_ARCH_300))
		kvmppc_setup_partition_table(kvm);

1422
	resize_hpt_debug(resize, "resize_hpt_pivot() done\n");
1423 1424 1425 1426
}

static void resize_hpt_release(struct kvm *kvm, struct kvm_resize_hpt *resize)
{
1427
	if (WARN_ON(!mutex_is_locked(&kvm->arch.mmu_setup_lock)))
1428
		return;
1429

1430 1431 1432
	if (!resize)
		return;

1433 1434 1435 1436 1437
	if (resize->error != -EBUSY) {
		if (resize->hpt.virt)
			kvmppc_free_hpt(&resize->hpt);
		kfree(resize);
	}
1438

1439 1440
	if (kvm->arch.resize_hpt == resize)
		kvm->arch.resize_hpt = NULL;
1441 1442 1443 1444 1445 1446 1447 1448
}

static void resize_hpt_prepare_work(struct work_struct *work)
{
	struct kvm_resize_hpt *resize = container_of(work,
						     struct kvm_resize_hpt,
						     work);
	struct kvm *kvm = resize->kvm;
1449
	int err = 0;
1450

1451 1452 1453
	if (WARN_ON(resize->error != -EBUSY))
		return;

1454
	mutex_lock(&kvm->arch.mmu_setup_lock);
1455

1456 1457 1458
	/* Request is still current? */
	if (kvm->arch.resize_hpt == resize) {
		/* We may request large allocations here:
1459
		 * do not sleep with kvm->arch.mmu_setup_lock held for a while.
1460
		 */
1461
		mutex_unlock(&kvm->arch.mmu_setup_lock);
1462

1463 1464
		resize_hpt_debug(resize, "resize_hpt_prepare_work(): order = %d\n",
				 resize->order);
1465

1466 1467 1468 1469 1470 1471 1472 1473
		err = resize_hpt_allocate(resize);

		/* We have strict assumption about -EBUSY
		 * when preparing for HPT resize.
		 */
		if (WARN_ON(err == -EBUSY))
			err = -EINPROGRESS;

1474
		mutex_lock(&kvm->arch.mmu_setup_lock);
1475
		/* It is possible that kvm->arch.resize_hpt != resize
1476
		 * after we grab kvm->arch.mmu_setup_lock again.
1477 1478
		 */
	}
1479 1480 1481

	resize->error = err;

1482 1483 1484
	if (kvm->arch.resize_hpt != resize)
		resize_hpt_release(kvm, resize);

1485
	mutex_unlock(&kvm->arch.mmu_setup_lock);
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
}

long kvm_vm_ioctl_resize_hpt_prepare(struct kvm *kvm,
				     struct kvm_ppc_resize_hpt *rhpt)
{
	unsigned long flags = rhpt->flags;
	unsigned long shift = rhpt->shift;
	struct kvm_resize_hpt *resize;
	int ret;

1496
	if (flags != 0 || kvm_is_radix(kvm))
1497 1498 1499 1500 1501
		return -EINVAL;

	if (shift && ((shift < 18) || (shift > 46)))
		return -EINVAL;

1502
	mutex_lock(&kvm->arch.mmu_setup_lock);
1503 1504 1505 1506 1507

	resize = kvm->arch.resize_hpt;

	if (resize) {
		if (resize->order == shift) {
1508 1509 1510
			/* Suitable resize in progress? */
			ret = resize->error;
			if (ret == -EBUSY)
1511
				ret = 100; /* estimated time in ms */
1512 1513
			else if (ret)
				resize_hpt_release(kvm, resize);
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528

			goto out;
		}

		/* not suitable, cancel it */
		resize_hpt_release(kvm, resize);
	}

	ret = 0;
	if (!shift)
		goto out; /* nothing to do */

	/* start new resize */

	resize = kzalloc(sizeof(*resize), GFP_KERNEL);
1529 1530 1531 1532
	if (!resize) {
		ret = -ENOMEM;
		goto out;
	}
1533 1534

	resize->error = -EBUSY;
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
	resize->order = shift;
	resize->kvm = kvm;
	INIT_WORK(&resize->work, resize_hpt_prepare_work);
	kvm->arch.resize_hpt = resize;

	schedule_work(&resize->work);

	ret = 100; /* estimated time in ms */

out:
1545
	mutex_unlock(&kvm->arch.mmu_setup_lock);
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
	return ret;
}

static void resize_hpt_boot_vcpu(void *opaque)
{
	/* Nothing to do, just force a KVM exit */
}

long kvm_vm_ioctl_resize_hpt_commit(struct kvm *kvm,
				    struct kvm_ppc_resize_hpt *rhpt)
{
	unsigned long flags = rhpt->flags;
	unsigned long shift = rhpt->shift;
	struct kvm_resize_hpt *resize;
	long ret;

1562
	if (flags != 0 || kvm_is_radix(kvm))
1563 1564 1565 1566 1567
		return -EINVAL;

	if (shift && ((shift < 18) || (shift > 46)))
		return -EINVAL;

1568
	mutex_lock(&kvm->arch.mmu_setup_lock);
1569 1570 1571 1572 1573

	resize = kvm->arch.resize_hpt;

	/* This shouldn't be possible */
	ret = -EIO;
1574
	if (WARN_ON(!kvm->arch.mmu_ready))
1575 1576 1577
		goto out_no_hpt;

	/* Stop VCPUs from running while we mess with the HPT */
1578
	kvm->arch.mmu_ready = 0;
1579 1580 1581
	smp_mb();

	/* Boot all CPUs out of the guest so they re-read
1582
	 * mmu_ready */
1583 1584 1585 1586 1587 1588 1589
	on_each_cpu(resize_hpt_boot_vcpu, NULL, 1);

	ret = -ENXIO;
	if (!resize || (resize->order != shift))
		goto out;

	ret = resize->error;
1590
	if (ret)
1591 1592 1593
		goto out;

	ret = resize_hpt_rehash(resize);
1594
	if (ret)
1595 1596 1597 1598 1599 1600
		goto out;

	resize_hpt_pivot(resize);

out:
	/* Let VCPUs run again */
1601
	kvm->arch.mmu_ready = 1;
1602 1603 1604
	smp_mb();
out_no_hpt:
	resize_hpt_release(kvm, resize);
1605
	mutex_unlock(&kvm->arch.mmu_setup_lock);
1606 1607 1608
	return ret;
}

1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
/*
 * Functions for reading and writing the hash table via reads and
 * writes on a file descriptor.
 *
 * Reads return the guest view of the hash table, which has to be
 * pieced together from the real hash table and the guest_rpte
 * values in the revmap array.
 *
 * On writes, each HPTE written is considered in turn, and if it
 * is valid, it is written to the HPT as if an H_ENTER with the
 * exact flag set was done.  When the invalid count is non-zero
 * in the header written to the stream, the kernel will make
 * sure that that many HPTEs are invalid, and invalidate them
 * if not.
 */

struct kvm_htab_ctx {
	unsigned long	index;
	unsigned long	flags;
	struct kvm	*kvm;
	int		first_pass;
};

#define HPTE_SIZE	(2 * sizeof(unsigned long))

1634 1635 1636 1637
/*
 * Returns 1 if this HPT entry has been modified or has pending
 * R/C bit changes.
 */
1638
static int hpte_dirty(struct revmap_entry *revp, __be64 *hptp)
1639 1640 1641 1642 1643 1644 1645 1646
{
	unsigned long rcbits_unset;

	if (revp->guest_rpte & HPTE_GR_MODIFIED)
		return 1;

	/* Also need to consider changes in reference and changed bits */
	rcbits_unset = ~revp->guest_rpte & (HPTE_R_R | HPTE_R_C);
1647 1648
	if ((be64_to_cpu(hptp[0]) & HPTE_V_VALID) &&
	    (be64_to_cpu(hptp[1]) & rcbits_unset))
1649 1650 1651 1652 1653
		return 1;

	return 0;
}

1654
static long record_hpte(unsigned long flags, __be64 *hptp,
1655 1656 1657
			unsigned long *hpte, struct revmap_entry *revp,
			int want_valid, int first_pass)
{
1658
	unsigned long v, r, hr;
1659
	unsigned long rcbits_unset;
1660 1661 1662 1663
	int ok = 1;
	int valid, dirty;

	/* Unmodified entries are uninteresting except on the first pass */
1664
	dirty = hpte_dirty(revp, hptp);
1665 1666 1667 1668
	if (!first_pass && !dirty)
		return 0;

	valid = 0;
1669
	if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT)) {
1670 1671
		valid = 1;
		if ((flags & KVM_GET_HTAB_BOLTED_ONLY) &&
1672
		    !(be64_to_cpu(hptp[0]) & HPTE_V_BOLTED))
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
			valid = 0;
	}
	if (valid != want_valid)
		return 0;

	v = r = 0;
	if (valid || dirty) {
		/* lock the HPTE so it's stable and read it */
		preempt_disable();
		while (!try_lock_hpte(hptp, HPTE_V_HVLOCK))
			cpu_relax();
1684
		v = be64_to_cpu(hptp[0]);
1685 1686 1687 1688 1689
		hr = be64_to_cpu(hptp[1]);
		if (cpu_has_feature(CPU_FTR_ARCH_300)) {
			v = hpte_new_to_old_v(v, hr);
			hr = hpte_new_to_old_r(hr);
		}
1690 1691 1692 1693 1694 1695 1696

		/* re-evaluate valid and dirty from synchronized HPTE value */
		valid = !!(v & HPTE_V_VALID);
		dirty = !!(revp->guest_rpte & HPTE_GR_MODIFIED);

		/* Harvest R and C into guest view if necessary */
		rcbits_unset = ~revp->guest_rpte & (HPTE_R_R | HPTE_R_C);
1697 1698
		if (valid && (rcbits_unset & hr)) {
			revp->guest_rpte |= (hr &
1699
				(HPTE_R_R | HPTE_R_C)) | HPTE_GR_MODIFIED;
1700 1701 1702
			dirty = 1;
		}

1703 1704 1705
		if (v & HPTE_V_ABSENT) {
			v &= ~HPTE_V_ABSENT;
			v |= HPTE_V_VALID;
1706
			valid = 1;
1707 1708 1709
		}
		if ((flags & KVM_GET_HTAB_BOLTED_ONLY) && !(v & HPTE_V_BOLTED))
			valid = 0;
1710 1711

		r = revp->guest_rpte;
1712 1713 1714 1715 1716
		/* only clear modified if this is the right sort of entry */
		if (valid == want_valid && dirty) {
			r &= ~HPTE_GR_MODIFIED;
			revp->guest_rpte = r;
		}
1717
		unlock_hpte(hptp, be64_to_cpu(hptp[0]));
1718 1719 1720 1721
		preempt_enable();
		if (!(valid == want_valid && (first_pass || dirty)))
			ok = 0;
	}
1722 1723
	hpte[0] = cpu_to_be64(v);
	hpte[1] = cpu_to_be64(r);
1724 1725 1726 1727 1728 1729 1730 1731 1732
	return ok;
}

static ssize_t kvm_htab_read(struct file *file, char __user *buf,
			     size_t count, loff_t *ppos)
{
	struct kvm_htab_ctx *ctx = file->private_data;
	struct kvm *kvm = ctx->kvm;
	struct kvm_get_htab_header hdr;
1733
	__be64 *hptp;
1734 1735 1736 1737 1738 1739 1740 1741
	struct revmap_entry *revp;
	unsigned long i, nb, nw;
	unsigned long __user *lbuf;
	struct kvm_get_htab_header __user *hptr;
	unsigned long flags;
	int first_pass;
	unsigned long hpte[2];

1742
	if (!access_ok(buf, count))
1743
		return -EFAULT;
1744 1745
	if (kvm_is_radix(kvm))
		return 0;
1746 1747 1748 1749 1750

	first_pass = ctx->first_pass;
	flags = ctx->flags;

	i = ctx->index;
1751 1752
	hptp = (__be64 *)(kvm->arch.hpt.virt + (i * HPTE_SIZE));
	revp = kvm->arch.hpt.rev + i;
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
	lbuf = (unsigned long __user *)buf;

	nb = 0;
	while (nb + sizeof(hdr) + HPTE_SIZE < count) {
		/* Initialize header */
		hptr = (struct kvm_get_htab_header __user *)buf;
		hdr.n_valid = 0;
		hdr.n_invalid = 0;
		nw = nb;
		nb += sizeof(hdr);
		lbuf = (unsigned long __user *)(buf + sizeof(hdr));

		/* Skip uninteresting entries, i.e. clean on not-first pass */
		if (!first_pass) {
1767
			while (i < kvmppc_hpt_npte(&kvm->arch.hpt) &&
1768
			       !hpte_dirty(revp, hptp)) {
1769 1770 1771 1772 1773
				++i;
				hptp += 2;
				++revp;
			}
		}
1774
		hdr.index = i;
1775 1776

		/* Grab a series of valid entries */
1777
		while (i < kvmppc_hpt_npte(&kvm->arch.hpt) &&
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
		       hdr.n_valid < 0xffff &&
		       nb + HPTE_SIZE < count &&
		       record_hpte(flags, hptp, hpte, revp, 1, first_pass)) {
			/* valid entry, write it out */
			++hdr.n_valid;
			if (__put_user(hpte[0], lbuf) ||
			    __put_user(hpte[1], lbuf + 1))
				return -EFAULT;
			nb += HPTE_SIZE;
			lbuf += 2;
			++i;
			hptp += 2;
			++revp;
		}
		/* Now skip invalid entries while we can */
1793
		while (i < kvmppc_hpt_npte(&kvm->arch.hpt) &&
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
		       hdr.n_invalid < 0xffff &&
		       record_hpte(flags, hptp, hpte, revp, 0, first_pass)) {
			/* found an invalid entry */
			++hdr.n_invalid;
			++i;
			hptp += 2;
			++revp;
		}

		if (hdr.n_valid || hdr.n_invalid) {
			/* write back the header */
			if (__copy_to_user(hptr, &hdr, sizeof(hdr)))
				return -EFAULT;
			nw = nb;
			buf = (char __user *)lbuf;
		} else {
			nb = nw;
		}

		/* Check if we've wrapped around the hash table */
1814
		if (i >= kvmppc_hpt_npte(&kvm->arch.hpt)) {
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
			i = 0;
			ctx->first_pass = 0;
			break;
		}
	}

	ctx->index = i;

	return nb;
}

static ssize_t kvm_htab_write(struct file *file, const char __user *buf,
			      size_t count, loff_t *ppos)
{
	struct kvm_htab_ctx *ctx = file->private_data;
	struct kvm *kvm = ctx->kvm;
	struct kvm_get_htab_header hdr;
	unsigned long i, j;
	unsigned long v, r;
	unsigned long __user *lbuf;
1835
	__be64 *hptp;
1836 1837 1838
	unsigned long tmp[2];
	ssize_t nb;
	long int err, ret;
1839
	int mmu_ready;
1840
	int pshift;
1841

1842
	if (!access_ok(buf, count))
1843
		return -EFAULT;
1844 1845
	if (kvm_is_radix(kvm))
		return -EINVAL;
1846 1847

	/* lock out vcpus from running while we're doing this */
1848
	mutex_lock(&kvm->arch.mmu_setup_lock);
1849 1850 1851 1852
	mmu_ready = kvm->arch.mmu_ready;
	if (mmu_ready) {
		kvm->arch.mmu_ready = 0;	/* temporarily */
		/* order mmu_ready vs. vcpus_running */
1853 1854
		smp_mb();
		if (atomic_read(&kvm->arch.vcpus_running)) {
1855
			kvm->arch.mmu_ready = 1;
1856
			mutex_unlock(&kvm->arch.mmu_setup_lock);
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
			return -EBUSY;
		}
	}

	err = 0;
	for (nb = 0; nb + sizeof(hdr) <= count; ) {
		err = -EFAULT;
		if (__copy_from_user(&hdr, buf, sizeof(hdr)))
			break;

		err = 0;
		if (nb + hdr.n_valid * HPTE_SIZE > count)
			break;

		nb += sizeof(hdr);
		buf += sizeof(hdr);

		err = -EINVAL;
		i = hdr.index;
1876 1877
		if (i >= kvmppc_hpt_npte(&kvm->arch.hpt) ||
		    i + hdr.n_valid + hdr.n_invalid > kvmppc_hpt_npte(&kvm->arch.hpt))
1878 1879
			break;

1880
		hptp = (__be64 *)(kvm->arch.hpt.virt + (i * HPTE_SIZE));
1881 1882
		lbuf = (unsigned long __user *)buf;
		for (j = 0; j < hdr.n_valid; ++j) {
1883 1884 1885
			__be64 hpte_v;
			__be64 hpte_r;

1886
			err = -EFAULT;
1887 1888
			if (__get_user(hpte_v, lbuf) ||
			    __get_user(hpte_r, lbuf + 1))
1889
				goto out;
1890 1891
			v = be64_to_cpu(hpte_v);
			r = be64_to_cpu(hpte_r);
1892 1893 1894
			err = -EINVAL;
			if (!(v & HPTE_V_VALID))
				goto out;
1895 1896 1897
			pshift = kvmppc_hpte_base_page_shift(v, r);
			if (pshift <= 0)
				goto out;
1898 1899 1900
			lbuf += 2;
			nb += HPTE_SIZE;

1901
			if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT))
1902 1903 1904 1905 1906 1907 1908 1909 1910
				kvmppc_do_h_remove(kvm, 0, i, 0, tmp);
			err = -EIO;
			ret = kvmppc_virtmode_do_h_enter(kvm, H_EXACT, i, v, r,
							 tmp);
			if (ret != H_SUCCESS) {
				pr_err("kvm_htab_write ret %ld i=%ld v=%lx "
				       "r=%lx\n", ret, i, v, r);
				goto out;
			}
1911
			if (!mmu_ready && is_vrma_hpte(v)) {
1912
				unsigned long senc, lpcr;
1913

1914
				senc = slb_pgsize_encoding(1ul << pshift);
1915 1916
				kvm->arch.vrma_slb_v = senc | SLB_VSID_B_1T |
					(VRMA_VSID << SLB_VSID_SHIFT_1T);
1917 1918 1919 1920 1921 1922 1923
				if (!cpu_has_feature(CPU_FTR_ARCH_300)) {
					lpcr = senc << (LPCR_VRMASD_SH - 4);
					kvmppc_update_lpcr(kvm, lpcr,
							   LPCR_VRMASD);
				} else {
					kvmppc_setup_partition_table(kvm);
				}
1924
				mmu_ready = 1;
1925 1926 1927 1928 1929 1930
			}
			++i;
			hptp += 2;
		}

		for (j = 0; j < hdr.n_invalid; ++j) {
1931
			if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT))
1932 1933 1934 1935 1936 1937 1938 1939
				kvmppc_do_h_remove(kvm, 0, i, 0, tmp);
			++i;
			hptp += 2;
		}
		err = 0;
	}

 out:
1940
	/* Order HPTE updates vs. mmu_ready */
1941
	smp_wmb();
1942
	kvm->arch.mmu_ready = mmu_ready;
1943
	mutex_unlock(&kvm->arch.mmu_setup_lock);
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961

	if (err)
		return err;
	return nb;
}

static int kvm_htab_release(struct inode *inode, struct file *filp)
{
	struct kvm_htab_ctx *ctx = filp->private_data;

	filp->private_data = NULL;
	if (!(ctx->flags & KVM_GET_HTAB_WRITE))
		atomic_dec(&ctx->kvm->arch.hpte_mod_interest);
	kvm_put_kvm(ctx->kvm);
	kfree(ctx);
	return 0;
}

1962
static const struct file_operations kvm_htab_fops = {
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
	.read		= kvm_htab_read,
	.write		= kvm_htab_write,
	.llseek		= default_llseek,
	.release	= kvm_htab_release,
};

int kvm_vm_ioctl_get_htab_fd(struct kvm *kvm, struct kvm_get_htab_fd *ghf)
{
	int ret;
	struct kvm_htab_ctx *ctx;
	int rwflag;

	/* reject flags we don't recognize */
	if (ghf->flags & ~(KVM_GET_HTAB_BOLTED_ONLY | KVM_GET_HTAB_WRITE))
		return -EINVAL;
	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
	if (!ctx)
		return -ENOMEM;
	kvm_get_kvm(kvm);
	ctx->kvm = kvm;
	ctx->index = ghf->start_index;
	ctx->flags = ghf->flags;
	ctx->first_pass = 1;

	rwflag = (ghf->flags & KVM_GET_HTAB_WRITE) ? O_WRONLY : O_RDONLY;
1988
	ret = anon_inode_getfd("kvm-htab", &kvm_htab_fops, ctx, rwflag | O_CLOEXEC);
1989
	if (ret < 0) {
1990
		kfree(ctx);
1991
		kvm_put_kvm_no_destroy(kvm);
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
		return ret;
	}

	if (rwflag == O_RDONLY) {
		mutex_lock(&kvm->slots_lock);
		atomic_inc(&kvm->arch.hpte_mod_interest);
		/* make sure kvmppc_do_h_enter etc. see the increment */
		synchronize_srcu_expedited(&kvm->srcu);
		mutex_unlock(&kvm->slots_lock);
	}

	return ret;
}

2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
struct debugfs_htab_state {
	struct kvm	*kvm;
	struct mutex	mutex;
	unsigned long	hpt_index;
	int		chars_left;
	int		buf_index;
	char		buf[64];
};

static int debugfs_htab_open(struct inode *inode, struct file *file)
{
	struct kvm *kvm = inode->i_private;
	struct debugfs_htab_state *p;

	p = kzalloc(sizeof(*p), GFP_KERNEL);
	if (!p)
		return -ENOMEM;

	kvm_get_kvm(kvm);
	p->kvm = kvm;
	mutex_init(&p->mutex);
	file->private_data = p;

	return nonseekable_open(inode, file);
}

static int debugfs_htab_release(struct inode *inode, struct file *file)
{
	struct debugfs_htab_state *p = file->private_data;

	kvm_put_kvm(p->kvm);
	kfree(p);
	return 0;
}

static ssize_t debugfs_htab_read(struct file *file, char __user *buf,
				 size_t len, loff_t *ppos)
{
	struct debugfs_htab_state *p = file->private_data;
	ssize_t ret, r;
	unsigned long i, n;
	unsigned long v, hr, gr;
	struct kvm *kvm;
	__be64 *hptp;

2051 2052 2053 2054
	kvm = p->kvm;
	if (kvm_is_radix(kvm))
		return 0;

2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
	ret = mutex_lock_interruptible(&p->mutex);
	if (ret)
		return ret;

	if (p->chars_left) {
		n = p->chars_left;
		if (n > len)
			n = len;
		r = copy_to_user(buf, p->buf + p->buf_index, n);
		n -= r;
		p->chars_left -= n;
		p->buf_index += n;
		buf += n;
		len -= n;
		ret = n;
		if (r) {
			if (!n)
				ret = -EFAULT;
			goto out;
		}
	}

	i = p->hpt_index;
2078
	hptp = (__be64 *)(kvm->arch.hpt.virt + (i * HPTE_SIZE));
2079 2080
	for (; len != 0 && i < kvmppc_hpt_npte(&kvm->arch.hpt);
	     ++i, hptp += 2) {
2081 2082 2083 2084 2085 2086 2087 2088 2089
		if (!(be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT)))
			continue;

		/* lock the HPTE so it's stable and read it */
		preempt_disable();
		while (!try_lock_hpte(hptp, HPTE_V_HVLOCK))
			cpu_relax();
		v = be64_to_cpu(hptp[0]) & ~HPTE_V_HVLOCK;
		hr = be64_to_cpu(hptp[1]);
2090
		gr = kvm->arch.hpt.rev[i].guest_rpte;
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
		unlock_hpte(hptp, v);
		preempt_enable();

		if (!(v & (HPTE_V_VALID | HPTE_V_ABSENT)))
			continue;

		n = scnprintf(p->buf, sizeof(p->buf),
			      "%6lx %.16lx %.16lx %.16lx\n",
			      i, v, hr, gr);
		p->chars_left = n;
		if (n > len)
			n = len;
		r = copy_to_user(buf, p->buf, n);
		n -= r;
		p->chars_left -= n;
		p->buf_index = n;
		buf += n;
		len -= n;
		ret += n;
		if (r) {
			if (!ret)
				ret = -EFAULT;
			goto out;
		}
	}
	p->hpt_index = i;

 out:
	mutex_unlock(&p->mutex);
	return ret;
}

2123
static ssize_t debugfs_htab_write(struct file *file, const char __user *buf,
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
			   size_t len, loff_t *ppos)
{
	return -EACCES;
}

static const struct file_operations debugfs_htab_fops = {
	.owner	 = THIS_MODULE,
	.open	 = debugfs_htab_open,
	.release = debugfs_htab_release,
	.read	 = debugfs_htab_read,
	.write	 = debugfs_htab_write,
	.llseek	 = generic_file_llseek,
};

void kvmppc_mmu_debugfs_init(struct kvm *kvm)
{
2140 2141
	debugfs_create_file("htab", 0400, kvm->arch.debugfs_dir, kvm,
			    &debugfs_htab_fops);
2142 2143
}

2144 2145 2146 2147
void kvmppc_mmu_book3s_hv_init(struct kvm_vcpu *vcpu)
{
	struct kvmppc_mmu *mmu = &vcpu->arch.mmu;

2148
	vcpu->arch.slb_nr = 32;		/* POWER7/POWER8 */
2149

2150
	mmu->xlate = kvmppc_mmu_book3s_64_hv_xlate;
2151 2152 2153

	vcpu->arch.hflags |= BOOK3S_HFLAG_SLB;
}