linux/arch/powerpc/kvm/book3s_64_mmu_hv.c
<<
>>
Prefs
   1/*
   2 * This program is free software; you can redistribute it and/or modify
   3 * it under the terms of the GNU General Public License, version 2, as
   4 * published by the Free Software Foundation.
   5 *
   6 * This program is distributed in the hope that it will be useful,
   7 * but WITHOUT ANY WARRANTY; without even the implied warranty of
   8 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   9 * GNU General Public License for more details.
  10 *
  11 * You should have received a copy of the GNU General Public License
  12 * along with this program; if not, write to the Free Software
  13 * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
  14 *
  15 * Copyright 2010 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
  16 */
  17
  18#include <linux/types.h>
  19#include <linux/string.h>
  20#include <linux/kvm.h>
  21#include <linux/kvm_host.h>
  22#include <linux/highmem.h>
  23#include <linux/gfp.h>
  24#include <linux/slab.h>
  25#include <linux/hugetlb.h>
  26#include <linux/vmalloc.h>
  27#include <linux/srcu.h>
  28#include <linux/anon_inodes.h>
  29#include <linux/file.h>
  30#include <linux/debugfs.h>
  31
  32#include <asm/tlbflush.h>
  33#include <asm/kvm_ppc.h>
  34#include <asm/kvm_book3s.h>
  35#include <asm/book3s/64/mmu-hash.h>
  36#include <asm/hvcall.h>
  37#include <asm/synch.h>
  38#include <asm/ppc-opcode.h>
  39#include <asm/cputable.h>
  40#include <asm/pte-walk.h>
  41
  42#include "trace_hv.h"
  43
  44//#define DEBUG_RESIZE_HPT      1
  45
  46#ifdef DEBUG_RESIZE_HPT
  47#define resize_hpt_debug(resize, ...)                           \
  48        do {                                                    \
  49                printk(KERN_DEBUG "RESIZE HPT %p: ", resize);   \
  50                printk(__VA_ARGS__);                            \
  51        } while (0)
  52#else
  53#define resize_hpt_debug(resize, ...)                           \
  54        do { } while (0)
  55#endif
  56
  57static long kvmppc_virtmode_do_h_enter(struct kvm *kvm, unsigned long flags,
  58                                long pte_index, unsigned long pteh,
  59                                unsigned long ptel, unsigned long *pte_idx_ret);
  60
  61struct kvm_resize_hpt {
  62        /* These fields read-only after init */
  63        struct kvm *kvm;
  64        struct work_struct work;
  65        u32 order;
  66
  67        /* These fields protected by kvm->lock */
  68
  69        /* Possible values and their usage:
  70         *  <0     an error occurred during allocation,
  71         *  -EBUSY allocation is in the progress,
  72         *  0      allocation made successfuly.
  73         */
  74        int error;
  75
  76        /* Private to the work thread, until error != -EBUSY,
  77         * then protected by kvm->lock.
  78         */
  79        struct kvm_hpt_info hpt;
  80};
  81
  82int kvmppc_allocate_hpt(struct kvm_hpt_info *info, u32 order)
  83{
  84        unsigned long hpt = 0;
  85        int cma = 0;
  86        struct page *page = NULL;
  87        struct revmap_entry *rev;
  88        unsigned long npte;
  89
  90        if ((order < PPC_MIN_HPT_ORDER) || (order > PPC_MAX_HPT_ORDER))
  91                return -EINVAL;
  92
  93        page = kvm_alloc_hpt_cma(1ul << (order - PAGE_SHIFT));
  94        if (page) {
  95                hpt = (unsigned long)pfn_to_kaddr(page_to_pfn(page));
  96                memset((void *)hpt, 0, (1ul << order));
  97                cma = 1;
  98        }
  99
 100        if (!hpt)
 101                hpt = __get_free_pages(GFP_KERNEL|__GFP_ZERO|__GFP_RETRY_MAYFAIL
 102                                       |__GFP_NOWARN, order - PAGE_SHIFT);
 103
 104        if (!hpt)
 105                return -ENOMEM;
 106
 107        /* HPTEs are 2**4 bytes long */
 108        npte = 1ul << (order - 4);
 109
 110        /* Allocate reverse map array */
 111        rev = vmalloc(sizeof(struct revmap_entry) * npte);
 112        if (!rev) {
 113                if (cma)
 114                        kvm_free_hpt_cma(page, 1 << (order - PAGE_SHIFT));
 115                else
 116                        free_pages(hpt, order - PAGE_SHIFT);
 117                return -ENOMEM;
 118        }
 119
 120        info->order = order;
 121        info->virt = hpt;
 122        info->cma = cma;
 123        info->rev = rev;
 124
 125        return 0;
 126}
 127
 128void kvmppc_set_hpt(struct kvm *kvm, struct kvm_hpt_info *info)
 129{
 130        atomic64_set(&kvm->arch.mmio_update, 0);
 131        kvm->arch.hpt = *info;
 132        kvm->arch.sdr1 = __pa(info->virt) | (info->order - 18);
 133
 134        pr_debug("KVM guest htab at %lx (order %ld), LPID %x\n",
 135                 info->virt, (long)info->order, kvm->arch.lpid);
 136}
 137
 138long kvmppc_alloc_reset_hpt(struct kvm *kvm, int order)
 139{
 140        long err = -EBUSY;
 141        struct kvm_hpt_info info;
 142
 143        mutex_lock(&kvm->lock);
 144        if (kvm->arch.mmu_ready) {
 145                kvm->arch.mmu_ready = 0;
 146                /* order mmu_ready vs. vcpus_running */
 147                smp_mb();
 148                if (atomic_read(&kvm->arch.vcpus_running)) {
 149                        kvm->arch.mmu_ready = 1;
 150                        goto out;
 151                }
 152        }
 153        if (kvm_is_radix(kvm)) {
 154                err = kvmppc_switch_mmu_to_hpt(kvm);
 155                if (err)
 156                        goto out;
 157        }
 158
 159        if (kvm->arch.hpt.order == order) {
 160                /* We already have a suitable HPT */
 161
 162                /* Set the entire HPT to 0, i.e. invalid HPTEs */
 163                memset((void *)kvm->arch.hpt.virt, 0, 1ul << order);
 164                /*
 165                 * Reset all the reverse-mapping chains for all memslots
 166                 */
 167                kvmppc_rmap_reset(kvm);
 168                err = 0;
 169                goto out;
 170        }
 171
 172        if (kvm->arch.hpt.virt) {
 173                kvmppc_free_hpt(&kvm->arch.hpt);
 174                kvmppc_rmap_reset(kvm);
 175        }
 176
 177        err = kvmppc_allocate_hpt(&info, order);
 178        if (err < 0)
 179                goto out;
 180        kvmppc_set_hpt(kvm, &info);
 181
 182out:
 183        if (err == 0)
 184                /* Ensure that each vcpu will flush its TLB on next entry. */
 185                cpumask_setall(&kvm->arch.need_tlb_flush);
 186
 187        mutex_unlock(&kvm->lock);
 188        return err;
 189}
 190
 191void kvmppc_free_hpt(struct kvm_hpt_info *info)
 192{
 193        vfree(info->rev);
 194        info->rev = NULL;
 195        if (info->cma)
 196                kvm_free_hpt_cma(virt_to_page(info->virt),
 197                                 1 << (info->order - PAGE_SHIFT));
 198        else if (info->virt)
 199                free_pages(info->virt, info->order - PAGE_SHIFT);
 200        info->virt = 0;
 201        info->order = 0;
 202}
 203
 204/* Bits in first HPTE dword for pagesize 4k, 64k or 16M */
 205static inline unsigned long hpte0_pgsize_encoding(unsigned long pgsize)
 206{
 207        return (pgsize > 0x1000) ? HPTE_V_LARGE : 0;
 208}
 209
 210/* Bits in second HPTE dword for pagesize 4k, 64k or 16M */
 211static inline unsigned long hpte1_pgsize_encoding(unsigned long pgsize)
 212{
 213        return (pgsize == 0x10000) ? 0x1000 : 0;
 214}
 215
 216void kvmppc_map_vrma(struct kvm_vcpu *vcpu, struct kvm_memory_slot *memslot,
 217                     unsigned long porder)
 218{
 219        unsigned long i;
 220        unsigned long npages;
 221        unsigned long hp_v, hp_r;
 222        unsigned long addr, hash;
 223        unsigned long psize;
 224        unsigned long hp0, hp1;
 225        unsigned long idx_ret;
 226        long ret;
 227        struct kvm *kvm = vcpu->kvm;
 228
 229        psize = 1ul << porder;
 230        npages = memslot->npages >> (porder - PAGE_SHIFT);
 231
 232        /* VRMA can't be > 1TB */
 233        if (npages > 1ul << (40 - porder))
 234                npages = 1ul << (40 - porder);
 235        /* Can't use more than 1 HPTE per HPTEG */
 236        if (npages > kvmppc_hpt_mask(&kvm->arch.hpt) + 1)
 237                npages = kvmppc_hpt_mask(&kvm->arch.hpt) + 1;
 238
 239        hp0 = HPTE_V_1TB_SEG | (VRMA_VSID << (40 - 16)) |
 240                HPTE_V_BOLTED | hpte0_pgsize_encoding(psize);
 241        hp1 = hpte1_pgsize_encoding(psize) |
 242                HPTE_R_R | HPTE_R_C | HPTE_R_M | PP_RWXX;
 243
 244        for (i = 0; i < npages; ++i) {
 245                addr = i << porder;
 246                /* can't use hpt_hash since va > 64 bits */
 247                hash = (i ^ (VRMA_VSID ^ (VRMA_VSID << 25)))
 248                        & kvmppc_hpt_mask(&kvm->arch.hpt);
 249                /*
 250                 * We assume that the hash table is empty and no
 251                 * vcpus are using it at this stage.  Since we create
 252                 * at most one HPTE per HPTEG, we just assume entry 7
 253                 * is available and use it.
 254                 */
 255                hash = (hash << 3) + 7;
 256                hp_v = hp0 | ((addr >> 16) & ~0x7fUL);
 257                hp_r = hp1 | addr;
 258                ret = kvmppc_virtmode_do_h_enter(kvm, H_EXACT, hash, hp_v, hp_r,
 259                                                 &idx_ret);
 260                if (ret != H_SUCCESS) {
 261                        pr_err("KVM: map_vrma at %lx failed, ret=%ld\n",
 262                               addr, ret);
 263                        break;
 264                }
 265        }
 266}
 267
 268int kvmppc_mmu_hv_init(void)
 269{
 270        unsigned long host_lpid, rsvd_lpid;
 271
 272        if (!cpu_has_feature(CPU_FTR_HVMODE))
 273                return -EINVAL;
 274
 275        /* POWER7 has 10-bit LPIDs (12-bit in POWER8) */
 276        host_lpid = mfspr(SPRN_LPID);
 277        rsvd_lpid = LPID_RSVD;
 278
 279        kvmppc_init_lpid(rsvd_lpid + 1);
 280
 281        kvmppc_claim_lpid(host_lpid);
 282        /* rsvd_lpid is reserved for use in partition switching */
 283        kvmppc_claim_lpid(rsvd_lpid);
 284
 285        return 0;
 286}
 287
 288static void kvmppc_mmu_book3s_64_hv_reset_msr(struct kvm_vcpu *vcpu)
 289{
 290        unsigned long msr = vcpu->arch.intr_msr;
 291
 292        /* If transactional, change to suspend mode on IRQ delivery */
 293        if (MSR_TM_TRANSACTIONAL(vcpu->arch.shregs.msr))
 294                msr |= MSR_TS_S;
 295        else
 296                msr |= vcpu->arch.shregs.msr & MSR_TS_MASK;
 297        kvmppc_set_msr(vcpu, msr);
 298}
 299
 300static long kvmppc_virtmode_do_h_enter(struct kvm *kvm, unsigned long flags,
 301                                long pte_index, unsigned long pteh,
 302                                unsigned long ptel, unsigned long *pte_idx_ret)
 303{
 304        long ret;
 305
 306        /* Protect linux PTE lookup from page table destruction */
 307        rcu_read_lock_sched();  /* this disables preemption too */
 308        ret = kvmppc_do_h_enter(kvm, flags, pte_index, pteh, ptel,
 309                                current->mm->pgd, false, pte_idx_ret);
 310        rcu_read_unlock_sched();
 311        if (ret == H_TOO_HARD) {
 312                /* this can't happen */
 313                pr_err("KVM: Oops, kvmppc_h_enter returned too hard!\n");
 314                ret = H_RESOURCE;       /* or something */
 315        }
 316        return ret;
 317
 318}
 319
 320static struct kvmppc_slb *kvmppc_mmu_book3s_hv_find_slbe(struct kvm_vcpu *vcpu,
 321                                                         gva_t eaddr)
 322{
 323        u64 mask;
 324        int i;
 325
 326        for (i = 0; i < vcpu->arch.slb_nr; i++) {
 327                if (!(vcpu->arch.slb[i].orige & SLB_ESID_V))
 328                        continue;
 329
 330                if (vcpu->arch.slb[i].origv & SLB_VSID_B_1T)
 331                        mask = ESID_MASK_1T;
 332                else
 333                        mask = ESID_MASK;
 334
 335                if (((vcpu->arch.slb[i].orige ^ eaddr) & mask) == 0)
 336                        return &vcpu->arch.slb[i];
 337        }
 338        return NULL;
 339}
 340
 341static unsigned long kvmppc_mmu_get_real_addr(unsigned long v, unsigned long r,
 342                        unsigned long ea)
 343{
 344        unsigned long ra_mask;
 345
 346        ra_mask = kvmppc_actual_pgsz(v, r) - 1;
 347        return (r & HPTE_R_RPN & ~ra_mask) | (ea & ra_mask);
 348}
 349
 350static int kvmppc_mmu_book3s_64_hv_xlate(struct kvm_vcpu *vcpu, gva_t eaddr,
 351                        struct kvmppc_pte *gpte, bool data, bool iswrite)
 352{
 353        struct kvm *kvm = vcpu->kvm;
 354        struct kvmppc_slb *slbe;
 355        unsigned long slb_v;
 356        unsigned long pp, key;
 357        unsigned long v, orig_v, gr;
 358        __be64 *hptep;
 359        int index;
 360        int virtmode = vcpu->arch.shregs.msr & (data ? MSR_DR : MSR_IR);
 361
 362        if (kvm_is_radix(vcpu->kvm))
 363                return kvmppc_mmu_radix_xlate(vcpu, eaddr, gpte, data, iswrite);
 364
 365        /* Get SLB entry */
 366        if (virtmode) {
 367                slbe = kvmppc_mmu_book3s_hv_find_slbe(vcpu, eaddr);
 368                if (!slbe)
 369                        return -EINVAL;
 370                slb_v = slbe->origv;
 371        } else {
 372                /* real mode access */
 373                slb_v = vcpu->kvm->arch.vrma_slb_v;
 374        }
 375
 376        preempt_disable();
 377        /* Find the HPTE in the hash table */
 378        index = kvmppc_hv_find_lock_hpte(kvm, eaddr, slb_v,
 379                                         HPTE_V_VALID | HPTE_V_ABSENT);
 380        if (index < 0) {
 381                preempt_enable();
 382                return -ENOENT;
 383        }
 384        hptep = (__be64 *)(kvm->arch.hpt.virt + (index << 4));
 385        v = orig_v = be64_to_cpu(hptep[0]) & ~HPTE_V_HVLOCK;
 386        if (cpu_has_feature(CPU_FTR_ARCH_300))
 387                v = hpte_new_to_old_v(v, be64_to_cpu(hptep[1]));
 388        gr = kvm->arch.hpt.rev[index].guest_rpte;
 389
 390        unlock_hpte(hptep, orig_v);
 391        preempt_enable();
 392
 393        gpte->eaddr = eaddr;
 394        gpte->vpage = ((v & HPTE_V_AVPN) << 4) | ((eaddr >> 12) & 0xfff);
 395
 396        /* Get PP bits and key for permission check */
 397        pp = gr & (HPTE_R_PP0 | HPTE_R_PP);
 398        key = (vcpu->arch.shregs.msr & MSR_PR) ? SLB_VSID_KP : SLB_VSID_KS;
 399        key &= slb_v;
 400
 401        /* Calculate permissions */
 402        gpte->may_read = hpte_read_permission(pp, key);
 403        gpte->may_write = hpte_write_permission(pp, key);
 404        gpte->may_execute = gpte->may_read && !(gr & (HPTE_R_N | HPTE_R_G));
 405
 406        /* Storage key permission check for POWER7 */
 407        if (data && virtmode) {
 408                int amrfield = hpte_get_skey_perm(gr, vcpu->arch.amr);
 409                if (amrfield & 1)
 410                        gpte->may_read = 0;
 411                if (amrfield & 2)
 412                        gpte->may_write = 0;
 413        }
 414
 415        /* Get the guest physical address */
 416        gpte->raddr = kvmppc_mmu_get_real_addr(v, gr, eaddr);
 417        return 0;
 418}
 419
 420/*
 421 * Quick test for whether an instruction is a load or a store.
 422 * If the instruction is a load or a store, then this will indicate
 423 * which it is, at least on server processors.  (Embedded processors
 424 * have some external PID instructions that don't follow the rule
 425 * embodied here.)  If the instruction isn't a load or store, then
 426 * this doesn't return anything useful.
 427 */
 428static int instruction_is_store(unsigned int instr)
 429{
 430        unsigned int mask;
 431
 432        mask = 0x10000000;
 433        if ((instr & 0xfc000000) == 0x7c000000)
 434                mask = 0x100;           /* major opcode 31 */
 435        return (instr & mask) != 0;
 436}
 437
 438int kvmppc_hv_emulate_mmio(struct kvm_run *run, struct kvm_vcpu *vcpu,
 439                           unsigned long gpa, gva_t ea, int is_store)
 440{
 441        u32 last_inst;
 442
 443        /*
 444         * If we fail, we just return to the guest and try executing it again.
 445         */
 446        if (kvmppc_get_last_inst(vcpu, INST_GENERIC, &last_inst) !=
 447                EMULATE_DONE)
 448                return RESUME_GUEST;
 449
 450        /*
 451         * WARNING: We do not know for sure whether the instruction we just
 452         * read from memory is the same that caused the fault in the first
 453         * place.  If the instruction we read is neither an load or a store,
 454         * then it can't access memory, so we don't need to worry about
 455         * enforcing access permissions.  So, assuming it is a load or
 456         * store, we just check that its direction (load or store) is
 457         * consistent with the original fault, since that's what we
 458         * checked the access permissions against.  If there is a mismatch
 459         * we just return and retry the instruction.
 460         */
 461
 462        if (instruction_is_store(last_inst) != !!is_store)
 463                return RESUME_GUEST;
 464
 465        /*
 466         * Emulated accesses are emulated by looking at the hash for
 467         * translation once, then performing the access later. The
 468         * translation could be invalidated in the meantime in which
 469         * point performing the subsequent memory access on the old
 470         * physical address could possibly be a security hole for the
 471         * guest (but not the host).
 472         *
 473         * This is less of an issue for MMIO stores since they aren't
 474         * globally visible. It could be an issue for MMIO loads to
 475         * a certain extent but we'll ignore it for now.
 476         */
 477
 478        vcpu->arch.paddr_accessed = gpa;
 479        vcpu->arch.vaddr_accessed = ea;
 480        return kvmppc_emulate_mmio(run, vcpu);
 481}
 482
 483int kvmppc_book3s_hv_page_fault(struct kvm_run *run, struct kvm_vcpu *vcpu,
 484                                unsigned long ea, unsigned long dsisr)
 485{
 486        struct kvm *kvm = vcpu->kvm;
 487        unsigned long hpte[3], r;
 488        unsigned long hnow_v, hnow_r;
 489        __be64 *hptep;
 490        unsigned long mmu_seq, psize, pte_size;
 491        unsigned long gpa_base, gfn_base;
 492        unsigned long gpa, gfn, hva, pfn;
 493        struct kvm_memory_slot *memslot;
 494        unsigned long *rmap;
 495        struct revmap_entry *rev;
 496        struct page *page, *pages[1];
 497        long index, ret, npages;
 498        bool is_ci;
 499        unsigned int writing, write_ok;
 500        struct vm_area_struct *vma;
 501        unsigned long rcbits;
 502        long mmio_update;
 503
 504        if (kvm_is_radix(kvm))
 505                return kvmppc_book3s_radix_page_fault(run, vcpu, ea, dsisr);
 506
 507        /*
 508         * Real-mode code has already searched the HPT and found the
 509         * entry we're interested in.  Lock the entry and check that
 510         * it hasn't changed.  If it has, just return and re-execute the
 511         * instruction.
 512         */
 513        if (ea != vcpu->arch.pgfault_addr)
 514                return RESUME_GUEST;
 515
 516        if (vcpu->arch.pgfault_cache) {
 517                mmio_update = atomic64_read(&kvm->arch.mmio_update);
 518                if (mmio_update == vcpu->arch.pgfault_cache->mmio_update) {
 519                        r = vcpu->arch.pgfault_cache->rpte;
 520                        psize = kvmppc_actual_pgsz(vcpu->arch.pgfault_hpte[0],
 521                                                   r);
 522                        gpa_base = r & HPTE_R_RPN & ~(psize - 1);
 523                        gfn_base = gpa_base >> PAGE_SHIFT;
 524                        gpa = gpa_base | (ea & (psize - 1));
 525                        return kvmppc_hv_emulate_mmio(run, vcpu, gpa, ea,
 526                                                dsisr & DSISR_ISSTORE);
 527                }
 528        }
 529        index = vcpu->arch.pgfault_index;
 530        hptep = (__be64 *)(kvm->arch.hpt.virt + (index << 4));
 531        rev = &kvm->arch.hpt.rev[index];
 532        preempt_disable();
 533        while (!try_lock_hpte(hptep, HPTE_V_HVLOCK))
 534                cpu_relax();
 535        hpte[0] = be64_to_cpu(hptep[0]) & ~HPTE_V_HVLOCK;
 536        hpte[1] = be64_to_cpu(hptep[1]);
 537        hpte[2] = r = rev->guest_rpte;
 538        unlock_hpte(hptep, hpte[0]);
 539        preempt_enable();
 540
 541        if (cpu_has_feature(CPU_FTR_ARCH_300)) {
 542                hpte[0] = hpte_new_to_old_v(hpte[0], hpte[1]);
 543                hpte[1] = hpte_new_to_old_r(hpte[1]);
 544        }
 545        if (hpte[0] != vcpu->arch.pgfault_hpte[0] ||
 546            hpte[1] != vcpu->arch.pgfault_hpte[1])
 547                return RESUME_GUEST;
 548
 549        /* Translate the logical address and get the page */
 550        psize = kvmppc_actual_pgsz(hpte[0], r);
 551        gpa_base = r & HPTE_R_RPN & ~(psize - 1);
 552        gfn_base = gpa_base >> PAGE_SHIFT;
 553        gpa = gpa_base | (ea & (psize - 1));
 554        gfn = gpa >> PAGE_SHIFT;
 555        memslot = gfn_to_memslot(kvm, gfn);
 556
 557        trace_kvm_page_fault_enter(vcpu, hpte, memslot, ea, dsisr);
 558
 559        /* No memslot means it's an emulated MMIO region */
 560        if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
 561                return kvmppc_hv_emulate_mmio(run, vcpu, gpa, ea,
 562                                              dsisr & DSISR_ISSTORE);
 563
 564        /*
 565         * This should never happen, because of the slot_is_aligned()
 566         * check in kvmppc_do_h_enter().
 567         */
 568        if (gfn_base < memslot->base_gfn)
 569                return -EFAULT;
 570
 571        /* used to check for invalidations in progress */
 572        mmu_seq = kvm->mmu_notifier_seq;
 573        smp_rmb();
 574
 575        ret = -EFAULT;
 576        is_ci = false;
 577        pfn = 0;
 578        page = NULL;
 579        pte_size = PAGE_SIZE;
 580        writing = (dsisr & DSISR_ISSTORE) != 0;
 581        /* If writing != 0, then the HPTE must allow writing, if we get here */
 582        write_ok = writing;
 583        hva = gfn_to_hva_memslot(memslot, gfn);
 584        npages = get_user_pages_fast(hva, 1, writing, pages);
 585        if (npages < 1) {
 586                /* Check if it's an I/O mapping */
 587                down_read(&current->mm->mmap_sem);
 588                vma = find_vma(current->mm, hva);
 589                if (vma && vma->vm_start <= hva && hva + psize <= vma->vm_end &&
 590                    (vma->vm_flags & VM_PFNMAP)) {
 591                        pfn = vma->vm_pgoff +
 592                                ((hva - vma->vm_start) >> PAGE_SHIFT);
 593                        pte_size = psize;
 594                        is_ci = pte_ci(__pte((pgprot_val(vma->vm_page_prot))));
 595                        write_ok = vma->vm_flags & VM_WRITE;
 596                }
 597                up_read(&current->mm->mmap_sem);
 598                if (!pfn)
 599                        goto out_put;
 600        } else {
 601                page = pages[0];
 602                pfn = page_to_pfn(page);
 603                if (PageHuge(page)) {
 604                        page = compound_head(page);
 605                        pte_size <<= compound_order(page);
 606                }
 607                /* if the guest wants write access, see if that is OK */
 608                if (!writing && hpte_is_writable(r)) {
 609                        pte_t *ptep, pte;
 610                        unsigned long flags;
 611                        /*
 612                         * We need to protect against page table destruction
 613                         * hugepage split and collapse.
 614                         */
 615                        local_irq_save(flags);
 616                        ptep = find_current_mm_pte(current->mm->pgd,
 617                                                   hva, NULL, NULL);
 618                        if (ptep) {
 619                                pte = kvmppc_read_update_linux_pte(ptep, 1);
 620                                if (__pte_write(pte))
 621                                        write_ok = 1;
 622                        }
 623                        local_irq_restore(flags);
 624                }
 625        }
 626
 627        if (psize > pte_size)
 628                goto out_put;
 629
 630        /* Check WIMG vs. the actual page we're accessing */
 631        if (!hpte_cache_flags_ok(r, is_ci)) {
 632                if (is_ci)
 633                        goto out_put;
 634                /*
 635                 * Allow guest to map emulated device memory as
 636                 * uncacheable, but actually make it cacheable.
 637                 */
 638                r = (r & ~(HPTE_R_W|HPTE_R_I|HPTE_R_G)) | HPTE_R_M;
 639        }
 640
 641        /*
 642         * Set the HPTE to point to pfn.
 643         * Since the pfn is at PAGE_SIZE granularity, make sure we
 644         * don't mask out lower-order bits if psize < PAGE_SIZE.
 645         */
 646        if (psize < PAGE_SIZE)
 647                psize = PAGE_SIZE;
 648        r = (r & HPTE_R_KEY_HI) | (r & ~(HPTE_R_PP0 - psize)) |
 649                                        ((pfn << PAGE_SHIFT) & ~(psize - 1));
 650        if (hpte_is_writable(r) && !write_ok)
 651                r = hpte_make_readonly(r);
 652        ret = RESUME_GUEST;
 653        preempt_disable();
 654        while (!try_lock_hpte(hptep, HPTE_V_HVLOCK))
 655                cpu_relax();
 656        hnow_v = be64_to_cpu(hptep[0]);
 657        hnow_r = be64_to_cpu(hptep[1]);
 658        if (cpu_has_feature(CPU_FTR_ARCH_300)) {
 659                hnow_v = hpte_new_to_old_v(hnow_v, hnow_r);
 660                hnow_r = hpte_new_to_old_r(hnow_r);
 661        }
 662
 663        /*
 664         * If the HPT is being resized, don't update the HPTE,
 665         * instead let the guest retry after the resize operation is complete.
 666         * The synchronization for mmu_ready test vs. set is provided
 667         * by the HPTE lock.
 668         */
 669        if (!kvm->arch.mmu_ready)
 670                goto out_unlock;
 671
 672        if ((hnow_v & ~HPTE_V_HVLOCK) != hpte[0] || hnow_r != hpte[1] ||
 673            rev->guest_rpte != hpte[2])
 674                /* HPTE has been changed under us; let the guest retry */
 675                goto out_unlock;
 676        hpte[0] = (hpte[0] & ~HPTE_V_ABSENT) | HPTE_V_VALID;
 677
 678        /* Always put the HPTE in the rmap chain for the page base address */
 679        rmap = &memslot->arch.rmap[gfn_base - memslot->base_gfn];
 680        lock_rmap(rmap);
 681
 682        /* Check if we might have been invalidated; let the guest retry if so */
 683        ret = RESUME_GUEST;
 684        if (mmu_notifier_retry(vcpu->kvm, mmu_seq)) {
 685                unlock_rmap(rmap);
 686                goto out_unlock;
 687        }
 688
 689        /* Only set R/C in real HPTE if set in both *rmap and guest_rpte */
 690        rcbits = *rmap >> KVMPPC_RMAP_RC_SHIFT;
 691        r &= rcbits | ~(HPTE_R_R | HPTE_R_C);
 692
 693        if (be64_to_cpu(hptep[0]) & HPTE_V_VALID) {
 694                /* HPTE was previously valid, so we need to invalidate it */
 695                unlock_rmap(rmap);
 696                hptep[0] |= cpu_to_be64(HPTE_V_ABSENT);
 697                kvmppc_invalidate_hpte(kvm, hptep, index);
 698                /* don't lose previous R and C bits */
 699                r |= be64_to_cpu(hptep[1]) & (HPTE_R_R | HPTE_R_C);
 700        } else {
 701                kvmppc_add_revmap_chain(kvm, rev, rmap, index, 0);
 702        }
 703
 704        if (cpu_has_feature(CPU_FTR_ARCH_300)) {
 705                r = hpte_old_to_new_r(hpte[0], r);
 706                hpte[0] = hpte_old_to_new_v(hpte[0]);
 707        }
 708        hptep[1] = cpu_to_be64(r);
 709        eieio();
 710        __unlock_hpte(hptep, hpte[0]);
 711        asm volatile("ptesync" : : : "memory");
 712        preempt_enable();
 713        if (page && hpte_is_writable(r))
 714                SetPageDirty(page);
 715
 716 out_put:
 717        trace_kvm_page_fault_exit(vcpu, hpte, ret);
 718
 719        if (page) {
 720                /*
 721                 * We drop pages[0] here, not page because page might
 722                 * have been set to the head page of a compound, but
 723                 * we have to drop the reference on the correct tail
 724                 * page to match the get inside gup()
 725                 */
 726                put_page(pages[0]);
 727        }
 728        return ret;
 729
 730 out_unlock:
 731        __unlock_hpte(hptep, be64_to_cpu(hptep[0]));
 732        preempt_enable();
 733        goto out_put;
 734}
 735
 736void kvmppc_rmap_reset(struct kvm *kvm)
 737{
 738        struct kvm_memslots *slots;
 739        struct kvm_memory_slot *memslot;
 740        int srcu_idx;
 741
 742        srcu_idx = srcu_read_lock(&kvm->srcu);
 743        slots = kvm_memslots(kvm);
 744        kvm_for_each_memslot(memslot, slots) {
 745                /*
 746                 * This assumes it is acceptable to lose reference and
 747                 * change bits across a reset.
 748                 */
 749                memset(memslot->arch.rmap, 0,
 750                       memslot->npages * sizeof(*memslot->arch.rmap));
 751        }
 752        srcu_read_unlock(&kvm->srcu, srcu_idx);
 753}
 754
 755typedef int (*hva_handler_fn)(struct kvm *kvm, struct kvm_memory_slot *memslot,
 756                              unsigned long gfn);
 757
 758static int kvm_handle_hva_range(struct kvm *kvm,
 759                                unsigned long start,
 760                                unsigned long end,
 761                                hva_handler_fn handler)
 762{
 763        int ret;
 764        int retval = 0;
 765        struct kvm_memslots *slots;
 766        struct kvm_memory_slot *memslot;
 767
 768        slots = kvm_memslots(kvm);
 769        kvm_for_each_memslot(memslot, slots) {
 770                unsigned long hva_start, hva_end;
 771                gfn_t gfn, gfn_end;
 772
 773                hva_start = max(start, memslot->userspace_addr);
 774                hva_end = min(end, memslot->userspace_addr +
 775                                        (memslot->npages << PAGE_SHIFT));
 776                if (hva_start >= hva_end)
 777                        continue;
 778                /*
 779                 * {gfn(page) | page intersects with [hva_start, hva_end)} =
 780                 * {gfn, gfn+1, ..., gfn_end-1}.
 781                 */
 782                gfn = hva_to_gfn_memslot(hva_start, memslot);
 783                gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
 784
 785                for (; gfn < gfn_end; ++gfn) {
 786                        ret = handler(kvm, memslot, gfn);
 787                        retval |= ret;
 788                }
 789        }
 790
 791        return retval;
 792}
 793
 794static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
 795                          hva_handler_fn handler)
 796{
 797        return kvm_handle_hva_range(kvm, hva, hva + 1, handler);
 798}
 799
 800/* Must be called with both HPTE and rmap locked */
 801static void kvmppc_unmap_hpte(struct kvm *kvm, unsigned long i,
 802                              struct kvm_memory_slot *memslot,
 803                              unsigned long *rmapp, unsigned long gfn)
 804{
 805        __be64 *hptep = (__be64 *) (kvm->arch.hpt.virt + (i << 4));
 806        struct revmap_entry *rev = kvm->arch.hpt.rev;
 807        unsigned long j, h;
 808        unsigned long ptel, psize, rcbits;
 809
 810        j = rev[i].forw;
 811        if (j == i) {
 812                /* chain is now empty */
 813                *rmapp &= ~(KVMPPC_RMAP_PRESENT | KVMPPC_RMAP_INDEX);
 814        } else {
 815                /* remove i from chain */
 816                h = rev[i].back;
 817                rev[h].forw = j;
 818                rev[j].back = h;
 819                rev[i].forw = rev[i].back = i;
 820                *rmapp = (*rmapp & ~KVMPPC_RMAP_INDEX) | j;
 821        }
 822
 823        /* Now check and modify the HPTE */
 824        ptel = rev[i].guest_rpte;
 825        psize = kvmppc_actual_pgsz(be64_to_cpu(hptep[0]), ptel);
 826        if ((be64_to_cpu(hptep[0]) & HPTE_V_VALID) &&
 827            hpte_rpn(ptel, psize) == gfn) {
 828                hptep[0] |= cpu_to_be64(HPTE_V_ABSENT);
 829                kvmppc_invalidate_hpte(kvm, hptep, i);
 830                hptep[1] &= ~cpu_to_be64(HPTE_R_KEY_HI | HPTE_R_KEY_LO);
 831                /* Harvest R and C */
 832                rcbits = be64_to_cpu(hptep[1]) & (HPTE_R_R | HPTE_R_C);
 833                *rmapp |= rcbits << KVMPPC_RMAP_RC_SHIFT;
 834                if ((rcbits & HPTE_R_C) && memslot->dirty_bitmap)
 835                        kvmppc_update_dirty_map(memslot, gfn, psize);
 836                if (rcbits & ~rev[i].guest_rpte) {
 837                        rev[i].guest_rpte = ptel | rcbits;
 838                        note_hpte_modification(kvm, &rev[i]);
 839                }
 840        }
 841}
 842
 843static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot,
 844                           unsigned long gfn)
 845{
 846        unsigned long i;
 847        __be64 *hptep;
 848        unsigned long *rmapp;
 849
 850        rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
 851        for (;;) {
 852                lock_rmap(rmapp);
 853                if (!(*rmapp & KVMPPC_RMAP_PRESENT)) {
 854                        unlock_rmap(rmapp);
 855                        break;
 856                }
 857
 858                /*
 859                 * To avoid an ABBA deadlock with the HPTE lock bit,
 860                 * we can't spin on the HPTE lock while holding the
 861                 * rmap chain lock.
 862                 */
 863                i = *rmapp & KVMPPC_RMAP_INDEX;
 864                hptep = (__be64 *) (kvm->arch.hpt.virt + (i << 4));
 865                if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) {
 866                        /* unlock rmap before spinning on the HPTE lock */
 867                        unlock_rmap(rmapp);
 868                        while (be64_to_cpu(hptep[0]) & HPTE_V_HVLOCK)
 869                                cpu_relax();
 870                        continue;
 871                }
 872
 873                kvmppc_unmap_hpte(kvm, i, memslot, rmapp, gfn);
 874                unlock_rmap(rmapp);
 875                __unlock_hpte(hptep, be64_to_cpu(hptep[0]));
 876        }
 877        return 0;
 878}
 879
 880int kvm_unmap_hva_hv(struct kvm *kvm, unsigned long hva)
 881{
 882        hva_handler_fn handler;
 883
 884        handler = kvm_is_radix(kvm) ? kvm_unmap_radix : kvm_unmap_rmapp;
 885        kvm_handle_hva(kvm, hva, handler);
 886        return 0;
 887}
 888
 889int kvm_unmap_hva_range_hv(struct kvm *kvm, unsigned long start, unsigned long end)
 890{
 891        hva_handler_fn handler;
 892
 893        handler = kvm_is_radix(kvm) ? kvm_unmap_radix : kvm_unmap_rmapp;
 894        kvm_handle_hva_range(kvm, start, end, handler);
 895        return 0;
 896}
 897
 898void kvmppc_core_flush_memslot_hv(struct kvm *kvm,
 899                                  struct kvm_memory_slot *memslot)
 900{
 901        unsigned long gfn;
 902        unsigned long n;
 903        unsigned long *rmapp;
 904
 905        gfn = memslot->base_gfn;
 906        rmapp = memslot->arch.rmap;
 907        for (n = memslot->npages; n; --n, ++gfn) {
 908                if (kvm_is_radix(kvm)) {
 909                        kvm_unmap_radix(kvm, memslot, gfn);
 910                        continue;
 911                }
 912                /*
 913                 * Testing the present bit without locking is OK because
 914                 * the memslot has been marked invalid already, and hence
 915                 * no new HPTEs referencing this page can be created,
 916                 * thus the present bit can't go from 0 to 1.
 917                 */
 918                if (*rmapp & KVMPPC_RMAP_PRESENT)
 919                        kvm_unmap_rmapp(kvm, memslot, gfn);
 920                ++rmapp;
 921        }
 922}
 923
 924static int kvm_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot,
 925                         unsigned long gfn)
 926{
 927        struct revmap_entry *rev = kvm->arch.hpt.rev;
 928        unsigned long head, i, j;
 929        __be64 *hptep;
 930        int ret = 0;
 931        unsigned long *rmapp;
 932
 933        rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
 934 retry:
 935        lock_rmap(rmapp);
 936        if (*rmapp & KVMPPC_RMAP_REFERENCED) {
 937                *rmapp &= ~KVMPPC_RMAP_REFERENCED;
 938                ret = 1;
 939        }
 940        if (!(*rmapp & KVMPPC_RMAP_PRESENT)) {
 941                unlock_rmap(rmapp);
 942                return ret;
 943        }
 944
 945        i = head = *rmapp & KVMPPC_RMAP_INDEX;
 946        do {
 947                hptep = (__be64 *) (kvm->arch.hpt.virt + (i << 4));
 948                j = rev[i].forw;
 949
 950                /* If this HPTE isn't referenced, ignore it */
 951                if (!(be64_to_cpu(hptep[1]) & HPTE_R_R))
 952                        continue;
 953
 954                if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) {
 955                        /* unlock rmap before spinning on the HPTE lock */
 956                        unlock_rmap(rmapp);
 957                        while (be64_to_cpu(hptep[0]) & HPTE_V_HVLOCK)
 958                                cpu_relax();
 959                        goto retry;
 960                }
 961
 962                /* Now check and modify the HPTE */
 963                if ((be64_to_cpu(hptep[0]) & HPTE_V_VALID) &&
 964                    (be64_to_cpu(hptep[1]) & HPTE_R_R)) {
 965                        kvmppc_clear_ref_hpte(kvm, hptep, i);
 966                        if (!(rev[i].guest_rpte & HPTE_R_R)) {
 967                                rev[i].guest_rpte |= HPTE_R_R;
 968                                note_hpte_modification(kvm, &rev[i]);
 969                        }
 970                        ret = 1;
 971                }
 972                __unlock_hpte(hptep, be64_to_cpu(hptep[0]));
 973        } while ((i = j) != head);
 974
 975        unlock_rmap(rmapp);
 976        return ret;
 977}
 978
 979int kvm_age_hva_hv(struct kvm *kvm, unsigned long start, unsigned long end)
 980{
 981        hva_handler_fn handler;
 982
 983        handler = kvm_is_radix(kvm) ? kvm_age_radix : kvm_age_rmapp;
 984        return kvm_handle_hva_range(kvm, start, end, handler);
 985}
 986
 987static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_memory_slot *memslot,
 988                              unsigned long gfn)
 989{
 990        struct revmap_entry *rev = kvm->arch.hpt.rev;
 991        unsigned long head, i, j;
 992        unsigned long *hp;
 993        int ret = 1;
 994        unsigned long *rmapp;
 995
 996        rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
 997        if (*rmapp & KVMPPC_RMAP_REFERENCED)
 998                return 1;
 999
1000        lock_rmap(rmapp);
1001        if (*rmapp & KVMPPC_RMAP_REFERENCED)
1002                goto out;
1003
1004        if (*rmapp & KVMPPC_RMAP_PRESENT) {
1005                i = head = *rmapp & KVMPPC_RMAP_INDEX;
1006                do {
1007                        hp = (unsigned long *)(kvm->arch.hpt.virt + (i << 4));
1008                        j = rev[i].forw;
1009                        if (be64_to_cpu(hp[1]) & HPTE_R_R)
1010                                goto out;
1011                } while ((i = j) != head);
1012        }
1013        ret = 0;
1014
1015 out:
1016        unlock_rmap(rmapp);
1017        return ret;
1018}
1019
1020int kvm_test_age_hva_hv(struct kvm *kvm, unsigned long hva)
1021{
1022        hva_handler_fn handler;
1023
1024        handler = kvm_is_radix(kvm) ? kvm_test_age_radix : kvm_test_age_rmapp;
1025        return kvm_handle_hva(kvm, hva, handler);
1026}
1027
1028void kvm_set_spte_hva_hv(struct kvm *kvm, unsigned long hva, pte_t pte)
1029{
1030        hva_handler_fn handler;
1031
1032        handler = kvm_is_radix(kvm) ? kvm_unmap_radix : kvm_unmap_rmapp;
1033        kvm_handle_hva(kvm, hva, handler);
1034}
1035
1036static int vcpus_running(struct kvm *kvm)
1037{
1038        return atomic_read(&kvm->arch.vcpus_running) != 0;
1039}
1040
1041/*
1042 * Returns the number of system pages that are dirty.
1043 * This can be more than 1 if we find a huge-page HPTE.
1044 */
1045static int kvm_test_clear_dirty_npages(struct kvm *kvm, unsigned long *rmapp)
1046{
1047        struct revmap_entry *rev = kvm->arch.hpt.rev;
1048        unsigned long head, i, j;
1049        unsigned long n;
1050        unsigned long v, r;
1051        __be64 *hptep;
1052        int npages_dirty = 0;
1053
1054 retry:
1055        lock_rmap(rmapp);
1056        if (!(*rmapp & KVMPPC_RMAP_PRESENT)) {
1057                unlock_rmap(rmapp);
1058                return npages_dirty;
1059        }
1060
1061        i = head = *rmapp & KVMPPC_RMAP_INDEX;
1062        do {
1063                unsigned long hptep1;
1064                hptep = (__be64 *) (kvm->arch.hpt.virt + (i << 4));
1065                j = rev[i].forw;
1066
1067                /*
1068                 * Checking the C (changed) bit here is racy since there
1069                 * is no guarantee about when the hardware writes it back.
1070                 * If the HPTE is not writable then it is stable since the
1071                 * page can't be written to, and we would have done a tlbie
1072                 * (which forces the hardware to complete any writeback)
1073                 * when making the HPTE read-only.
1074                 * If vcpus are running then this call is racy anyway
1075                 * since the page could get dirtied subsequently, so we
1076                 * expect there to be a further call which would pick up
1077                 * any delayed C bit writeback.
1078                 * Otherwise we need to do the tlbie even if C==0 in
1079                 * order to pick up any delayed writeback of C.
1080                 */
1081                hptep1 = be64_to_cpu(hptep[1]);
1082                if (!(hptep1 & HPTE_R_C) &&
1083                    (!hpte_is_writable(hptep1) || vcpus_running(kvm)))
1084                        continue;
1085
1086                if (!try_lock_hpte(hptep, HPTE_V_HVLOCK)) {
1087                        /* unlock rmap before spinning on the HPTE lock */
1088                        unlock_rmap(rmapp);
1089                        while (hptep[0] & cpu_to_be64(HPTE_V_HVLOCK))
1090                                cpu_relax();
1091                        goto retry;
1092                }
1093
1094                /* Now check and modify the HPTE */
1095                if (!(hptep[0] & cpu_to_be64(HPTE_V_VALID))) {
1096                        __unlock_hpte(hptep, be64_to_cpu(hptep[0]));
1097                        continue;
1098                }
1099
1100                /* need to make it temporarily absent so C is stable */
1101                hptep[0] |= cpu_to_be64(HPTE_V_ABSENT);
1102                kvmppc_invalidate_hpte(kvm, hptep, i);
1103                v = be64_to_cpu(hptep[0]);
1104                r = be64_to_cpu(hptep[1]);
1105                if (r & HPTE_R_C) {
1106                        hptep[1] = cpu_to_be64(r & ~HPTE_R_C);
1107                        if (!(rev[i].guest_rpte & HPTE_R_C)) {
1108                                rev[i].guest_rpte |= HPTE_R_C;
1109                                note_hpte_modification(kvm, &rev[i]);
1110                        }
1111                        n = kvmppc_actual_pgsz(v, r);
1112                        n = (n + PAGE_SIZE - 1) >> PAGE_SHIFT;
1113                        if (n > npages_dirty)
1114                                npages_dirty = n;
1115                        eieio();
1116                }
1117                v &= ~HPTE_V_ABSENT;
1118                v |= HPTE_V_VALID;
1119                __unlock_hpte(hptep, v);
1120        } while ((i = j) != head);
1121
1122        unlock_rmap(rmapp);
1123        return npages_dirty;
1124}
1125
1126void kvmppc_harvest_vpa_dirty(struct kvmppc_vpa *vpa,
1127                              struct kvm_memory_slot *memslot,
1128                              unsigned long *map)
1129{
1130        unsigned long gfn;
1131
1132        if (!vpa->dirty || !vpa->pinned_addr)
1133                return;
1134        gfn = vpa->gpa >> PAGE_SHIFT;
1135        if (gfn < memslot->base_gfn ||
1136            gfn >= memslot->base_gfn + memslot->npages)
1137                return;
1138
1139        vpa->dirty = false;
1140        if (map)
1141                __set_bit_le(gfn - memslot->base_gfn, map);
1142}
1143
1144long kvmppc_hv_get_dirty_log_hpt(struct kvm *kvm,
1145                        struct kvm_memory_slot *memslot, unsigned long *map)
1146{
1147        unsigned long i;
1148        unsigned long *rmapp;
1149
1150        preempt_disable();
1151        rmapp = memslot->arch.rmap;
1152        for (i = 0; i < memslot->npages; ++i) {
1153                int npages = kvm_test_clear_dirty_npages(kvm, rmapp);
1154                /*
1155                 * Note that if npages > 0 then i must be a multiple of npages,
1156                 * since we always put huge-page HPTEs in the rmap chain
1157                 * corresponding to their page base address.
1158                 */
1159                if (npages)
1160                        set_dirty_bits(map, i, npages);
1161                ++rmapp;
1162        }
1163        preempt_enable();
1164        return 0;
1165}
1166
1167void *kvmppc_pin_guest_page(struct kvm *kvm, unsigned long gpa,
1168                            unsigned long *nb_ret)
1169{
1170        struct kvm_memory_slot *memslot;
1171        unsigned long gfn = gpa >> PAGE_SHIFT;
1172        struct page *page, *pages[1];
1173        int npages;
1174        unsigned long hva, offset;
1175        int srcu_idx;
1176
1177        srcu_idx = srcu_read_lock(&kvm->srcu);
1178        memslot = gfn_to_memslot(kvm, gfn);
1179        if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
1180                goto err;
1181        hva = gfn_to_hva_memslot(memslot, gfn);
1182        npages = get_user_pages_fast(hva, 1, 1, pages);
1183        if (npages < 1)
1184                goto err;
1185        page = pages[0];
1186        srcu_read_unlock(&kvm->srcu, srcu_idx);
1187
1188        offset = gpa & (PAGE_SIZE - 1);
1189        if (nb_ret)
1190                *nb_ret = PAGE_SIZE - offset;
1191        return page_address(page) + offset;
1192
1193 err:
1194        srcu_read_unlock(&kvm->srcu, srcu_idx);
1195        return NULL;
1196}
1197
1198void kvmppc_unpin_guest_page(struct kvm *kvm, void *va, unsigned long gpa,
1199                             bool dirty)
1200{
1201        struct page *page = virt_to_page(va);
1202        struct kvm_memory_slot *memslot;
1203        unsigned long gfn;
1204        int srcu_idx;
1205
1206        put_page(page);
1207
1208        if (!dirty)
1209                return;
1210
1211        /* We need to mark this page dirty in the memslot dirty_bitmap, if any */
1212        gfn = gpa >> PAGE_SHIFT;
1213        srcu_idx = srcu_read_lock(&kvm->srcu);
1214        memslot = gfn_to_memslot(kvm, gfn);
1215        if (memslot && memslot->dirty_bitmap)
1216                set_bit_le(gfn - memslot->base_gfn, memslot->dirty_bitmap);
1217        srcu_read_unlock(&kvm->srcu, srcu_idx);
1218}
1219
1220/*
1221 * HPT resizing
1222 */
1223static int resize_hpt_allocate(struct kvm_resize_hpt *resize)
1224{
1225        int rc;
1226
1227        rc = kvmppc_allocate_hpt(&resize->hpt, resize->order);
1228        if (rc < 0)
1229                return rc;
1230
1231        resize_hpt_debug(resize, "resize_hpt_allocate(): HPT @ 0x%lx\n",
1232                         resize->hpt.virt);
1233
1234        return 0;
1235}
1236
1237static unsigned long resize_hpt_rehash_hpte(struct kvm_resize_hpt *resize,
1238                                            unsigned long idx)
1239{
1240        struct kvm *kvm = resize->kvm;
1241        struct kvm_hpt_info *old = &kvm->arch.hpt;
1242        struct kvm_hpt_info *new = &resize->hpt;
1243        unsigned long old_hash_mask = (1ULL << (old->order - 7)) - 1;
1244        unsigned long new_hash_mask = (1ULL << (new->order - 7)) - 1;
1245        __be64 *hptep, *new_hptep;
1246        unsigned long vpte, rpte, guest_rpte;
1247        int ret;
1248        struct revmap_entry *rev;
1249        unsigned long apsize, avpn, pteg, hash;
1250        unsigned long new_idx, new_pteg, replace_vpte;
1251        int pshift;
1252
1253        hptep = (__be64 *)(old->virt + (idx << 4));
1254
1255        /* Guest is stopped, so new HPTEs can't be added or faulted
1256         * in, only unmapped or altered by host actions.  So, it's
1257         * safe to check this before we take the HPTE lock */
1258        vpte = be64_to_cpu(hptep[0]);
1259        if (!(vpte & HPTE_V_VALID) && !(vpte & HPTE_V_ABSENT))
1260                return 0; /* nothing to do */
1261
1262        while (!try_lock_hpte(hptep, HPTE_V_HVLOCK))
1263                cpu_relax();
1264
1265        vpte = be64_to_cpu(hptep[0]);
1266
1267        ret = 0;
1268        if (!(vpte & HPTE_V_VALID) && !(vpte & HPTE_V_ABSENT))
1269                /* Nothing to do */
1270                goto out;
1271
1272        if (cpu_has_feature(CPU_FTR_ARCH_300)) {
1273                rpte = be64_to_cpu(hptep[1]);
1274                vpte = hpte_new_to_old_v(vpte, rpte);
1275        }
1276
1277        /* Unmap */
1278        rev = &old->rev[idx];
1279        guest_rpte = rev->guest_rpte;
1280
1281        ret = -EIO;
1282        apsize = kvmppc_actual_pgsz(vpte, guest_rpte);
1283        if (!apsize)
1284                goto out;
1285
1286        if (vpte & HPTE_V_VALID) {
1287                unsigned long gfn = hpte_rpn(guest_rpte, apsize);
1288                int srcu_idx = srcu_read_lock(&kvm->srcu);
1289                struct kvm_memory_slot *memslot =
1290                        __gfn_to_memslot(kvm_memslots(kvm), gfn);
1291
1292                if (memslot) {
1293                        unsigned long *rmapp;
1294                        rmapp = &memslot->arch.rmap[gfn - memslot->base_gfn];
1295
1296                        lock_rmap(rmapp);
1297                        kvmppc_unmap_hpte(kvm, idx, memslot, rmapp, gfn);
1298                        unlock_rmap(rmapp);
1299                }
1300
1301                srcu_read_unlock(&kvm->srcu, srcu_idx);
1302        }
1303
1304        /* Reload PTE after unmap */
1305        vpte = be64_to_cpu(hptep[0]);
1306        BUG_ON(vpte & HPTE_V_VALID);
1307        BUG_ON(!(vpte & HPTE_V_ABSENT));
1308
1309        ret = 0;
1310        if (!(vpte & HPTE_V_BOLTED))
1311                goto out;
1312
1313        rpte = be64_to_cpu(hptep[1]);
1314
1315        if (cpu_has_feature(CPU_FTR_ARCH_300)) {
1316                vpte = hpte_new_to_old_v(vpte, rpte);
1317                rpte = hpte_new_to_old_r(rpte);
1318        }
1319
1320        pshift = kvmppc_hpte_base_page_shift(vpte, rpte);
1321        avpn = HPTE_V_AVPN_VAL(vpte) & ~(((1ul << pshift) - 1) >> 23);
1322        pteg = idx / HPTES_PER_GROUP;
1323        if (vpte & HPTE_V_SECONDARY)
1324                pteg = ~pteg;
1325
1326        if (!(vpte & HPTE_V_1TB_SEG)) {
1327                unsigned long offset, vsid;
1328
1329                /* We only have 28 - 23 bits of offset in avpn */
1330                offset = (avpn & 0x1f) << 23;
1331                vsid = avpn >> 5;
1332                /* We can find more bits from the pteg value */
1333                if (pshift < 23)
1334                        offset |= ((vsid ^ pteg) & old_hash_mask) << pshift;
1335
1336                hash = vsid ^ (offset >> pshift);
1337        } else {
1338                unsigned long offset, vsid;
1339
1340                /* We only have 40 - 23 bits of seg_off in avpn */
1341                offset = (avpn & 0x1ffff) << 23;
1342                vsid = avpn >> 17;
1343                if (pshift < 23)
1344                        offset |= ((vsid ^ (vsid << 25) ^ pteg) & old_hash_mask) << pshift;
1345
1346                hash = vsid ^ (vsid << 25) ^ (offset >> pshift);
1347        }
1348
1349        new_pteg = hash & new_hash_mask;
1350        if (vpte & HPTE_V_SECONDARY)
1351                new_pteg = ~hash & new_hash_mask;
1352
1353        new_idx = new_pteg * HPTES_PER_GROUP + (idx % HPTES_PER_GROUP);
1354        new_hptep = (__be64 *)(new->virt + (new_idx << 4));
1355
1356        replace_vpte = be64_to_cpu(new_hptep[0]);
1357        if (cpu_has_feature(CPU_FTR_ARCH_300)) {
1358                unsigned long replace_rpte = be64_to_cpu(new_hptep[1]);
1359                replace_vpte = hpte_new_to_old_v(replace_vpte, replace_rpte);
1360        }
1361
1362        if (replace_vpte & (HPTE_V_VALID | HPTE_V_ABSENT)) {
1363                BUG_ON(new->order >= old->order);
1364
1365                if (replace_vpte & HPTE_V_BOLTED) {
1366                        if (vpte & HPTE_V_BOLTED)
1367                                /* Bolted collision, nothing we can do */
1368                                ret = -ENOSPC;
1369                        /* Discard the new HPTE */
1370                        goto out;
1371                }
1372
1373                /* Discard the previous HPTE */
1374        }
1375
1376        if (cpu_has_feature(CPU_FTR_ARCH_300)) {
1377                rpte = hpte_old_to_new_r(vpte, rpte);
1378                vpte = hpte_old_to_new_v(vpte);
1379        }
1380
1381        new_hptep[1] = cpu_to_be64(rpte);
1382        new->rev[new_idx].guest_rpte = guest_rpte;
1383        /* No need for a barrier, since new HPT isn't active */
1384        new_hptep[0] = cpu_to_be64(vpte);
1385        unlock_hpte(new_hptep, vpte);
1386
1387out:
1388        unlock_hpte(hptep, vpte);
1389        return ret;
1390}
1391
1392static int resize_hpt_rehash(struct kvm_resize_hpt *resize)
1393{
1394        struct kvm *kvm = resize->kvm;
1395        unsigned  long i;
1396        int rc;
1397
1398        for (i = 0; i < kvmppc_hpt_npte(&kvm->arch.hpt); i++) {
1399                rc = resize_hpt_rehash_hpte(resize, i);
1400                if (rc != 0)
1401                        return rc;
1402        }
1403
1404        return 0;
1405}
1406
1407static void resize_hpt_pivot(struct kvm_resize_hpt *resize)
1408{
1409        struct kvm *kvm = resize->kvm;
1410        struct kvm_hpt_info hpt_tmp;
1411
1412        /* Exchange the pending tables in the resize structure with
1413         * the active tables */
1414
1415        resize_hpt_debug(resize, "resize_hpt_pivot()\n");
1416
1417        spin_lock(&kvm->mmu_lock);
1418        asm volatile("ptesync" : : : "memory");
1419
1420        hpt_tmp = kvm->arch.hpt;
1421        kvmppc_set_hpt(kvm, &resize->hpt);
1422        resize->hpt = hpt_tmp;
1423
1424        spin_unlock(&kvm->mmu_lock);
1425
1426        synchronize_srcu_expedited(&kvm->srcu);
1427
1428        if (cpu_has_feature(CPU_FTR_ARCH_300))
1429                kvmppc_setup_partition_table(kvm);
1430
1431        resize_hpt_debug(resize, "resize_hpt_pivot() done\n");
1432}
1433
1434static void resize_hpt_release(struct kvm *kvm, struct kvm_resize_hpt *resize)
1435{
1436        if (WARN_ON(!mutex_is_locked(&kvm->lock)))
1437                return;
1438
1439        if (!resize)
1440                return;
1441
1442        if (resize->error != -EBUSY) {
1443                if (resize->hpt.virt)
1444                        kvmppc_free_hpt(&resize->hpt);
1445                kfree(resize);
1446        }
1447
1448        if (kvm->arch.resize_hpt == resize)
1449                kvm->arch.resize_hpt = NULL;
1450}
1451
1452static void resize_hpt_prepare_work(struct work_struct *work)
1453{
1454        struct kvm_resize_hpt *resize = container_of(work,
1455                                                     struct kvm_resize_hpt,
1456                                                     work);
1457        struct kvm *kvm = resize->kvm;
1458        int err = 0;
1459
1460        if (WARN_ON(resize->error != -EBUSY))
1461                return;
1462
1463        mutex_lock(&kvm->lock);
1464
1465        /* Request is still current? */
1466        if (kvm->arch.resize_hpt == resize) {
1467                /* We may request large allocations here:
1468                 * do not sleep with kvm->lock held for a while.
1469                 */
1470                mutex_unlock(&kvm->lock);
1471
1472                resize_hpt_debug(resize, "resize_hpt_prepare_work(): order = %d\n",
1473                                 resize->order);
1474
1475                err = resize_hpt_allocate(resize);
1476
1477                /* We have strict assumption about -EBUSY
1478                 * when preparing for HPT resize.
1479                 */
1480                if (WARN_ON(err == -EBUSY))
1481                        err = -EINPROGRESS;
1482
1483                mutex_lock(&kvm->lock);
1484                /* It is possible that kvm->arch.resize_hpt != resize
1485                 * after we grab kvm->lock again.
1486                 */
1487        }
1488
1489        resize->error = err;
1490
1491        if (kvm->arch.resize_hpt != resize)
1492                resize_hpt_release(kvm, resize);
1493
1494        mutex_unlock(&kvm->lock);
1495}
1496
1497long kvm_vm_ioctl_resize_hpt_prepare(struct kvm *kvm,
1498                                     struct kvm_ppc_resize_hpt *rhpt)
1499{
1500        unsigned long flags = rhpt->flags;
1501        unsigned long shift = rhpt->shift;
1502        struct kvm_resize_hpt *resize;
1503        int ret;
1504
1505        if (flags != 0 || kvm_is_radix(kvm))
1506                return -EINVAL;
1507
1508        if (shift && ((shift < 18) || (shift > 46)))
1509                return -EINVAL;
1510
1511        mutex_lock(&kvm->lock);
1512
1513        resize = kvm->arch.resize_hpt;
1514
1515        if (resize) {
1516                if (resize->order == shift) {
1517                        /* Suitable resize in progress? */
1518                        ret = resize->error;
1519                        if (ret == -EBUSY)
1520                                ret = 100; /* estimated time in ms */
1521                        else if (ret)
1522                                resize_hpt_release(kvm, resize);
1523
1524                        goto out;
1525                }
1526
1527                /* not suitable, cancel it */
1528                resize_hpt_release(kvm, resize);
1529        }
1530
1531        ret = 0;
1532        if (!shift)
1533                goto out; /* nothing to do */
1534
1535        /* start new resize */
1536
1537        resize = kzalloc(sizeof(*resize), GFP_KERNEL);
1538        if (!resize) {
1539                ret = -ENOMEM;
1540                goto out;
1541        }
1542
1543        resize->error = -EBUSY;
1544        resize->order = shift;
1545        resize->kvm = kvm;
1546        INIT_WORK(&resize->work, resize_hpt_prepare_work);
1547        kvm->arch.resize_hpt = resize;
1548
1549        schedule_work(&resize->work);
1550
1551        ret = 100; /* estimated time in ms */
1552
1553out:
1554        mutex_unlock(&kvm->lock);
1555        return ret;
1556}
1557
1558static void resize_hpt_boot_vcpu(void *opaque)
1559{
1560        /* Nothing to do, just force a KVM exit */
1561}
1562
1563long kvm_vm_ioctl_resize_hpt_commit(struct kvm *kvm,
1564                                    struct kvm_ppc_resize_hpt *rhpt)
1565{
1566        unsigned long flags = rhpt->flags;
1567        unsigned long shift = rhpt->shift;
1568        struct kvm_resize_hpt *resize;
1569        long ret;
1570
1571        if (flags != 0 || kvm_is_radix(kvm))
1572                return -EINVAL;
1573
1574        if (shift && ((shift < 18) || (shift > 46)))
1575                return -EINVAL;
1576
1577        mutex_lock(&kvm->lock);
1578
1579        resize = kvm->arch.resize_hpt;
1580
1581        /* This shouldn't be possible */
1582        ret = -EIO;
1583        if (WARN_ON(!kvm->arch.mmu_ready))
1584                goto out_no_hpt;
1585
1586        /* Stop VCPUs from running while we mess with the HPT */
1587        kvm->arch.mmu_ready = 0;
1588        smp_mb();
1589
1590        /* Boot all CPUs out of the guest so they re-read
1591         * mmu_ready */
1592        on_each_cpu(resize_hpt_boot_vcpu, NULL, 1);
1593
1594        ret = -ENXIO;
1595        if (!resize || (resize->order != shift))
1596                goto out;
1597
1598        ret = resize->error;
1599        if (ret)
1600                goto out;
1601
1602        ret = resize_hpt_rehash(resize);
1603        if (ret)
1604                goto out;
1605
1606        resize_hpt_pivot(resize);
1607
1608out:
1609        /* Let VCPUs run again */
1610        kvm->arch.mmu_ready = 1;
1611        smp_mb();
1612out_no_hpt:
1613        resize_hpt_release(kvm, resize);
1614        mutex_unlock(&kvm->lock);
1615        return ret;
1616}
1617
1618/*
1619 * Functions for reading and writing the hash table via reads and
1620 * writes on a file descriptor.
1621 *
1622 * Reads return the guest view of the hash table, which has to be
1623 * pieced together from the real hash table and the guest_rpte
1624 * values in the revmap array.
1625 *
1626 * On writes, each HPTE written is considered in turn, and if it
1627 * is valid, it is written to the HPT as if an H_ENTER with the
1628 * exact flag set was done.  When the invalid count is non-zero
1629 * in the header written to the stream, the kernel will make
1630 * sure that that many HPTEs are invalid, and invalidate them
1631 * if not.
1632 */
1633
1634struct kvm_htab_ctx {
1635        unsigned long   index;
1636        unsigned long   flags;
1637        struct kvm      *kvm;
1638        int             first_pass;
1639};
1640
1641#define HPTE_SIZE       (2 * sizeof(unsigned long))
1642
1643/*
1644 * Returns 1 if this HPT entry has been modified or has pending
1645 * R/C bit changes.
1646 */
1647static int hpte_dirty(struct revmap_entry *revp, __be64 *hptp)
1648{
1649        unsigned long rcbits_unset;
1650
1651        if (revp->guest_rpte & HPTE_GR_MODIFIED)
1652                return 1;
1653
1654        /* Also need to consider changes in reference and changed bits */
1655        rcbits_unset = ~revp->guest_rpte & (HPTE_R_R | HPTE_R_C);
1656        if ((be64_to_cpu(hptp[0]) & HPTE_V_VALID) &&
1657            (be64_to_cpu(hptp[1]) & rcbits_unset))
1658                return 1;
1659
1660        return 0;
1661}
1662
1663static long record_hpte(unsigned long flags, __be64 *hptp,
1664                        unsigned long *hpte, struct revmap_entry *revp,
1665                        int want_valid, int first_pass)
1666{
1667        unsigned long v, r, hr;
1668        unsigned long rcbits_unset;
1669        int ok = 1;
1670        int valid, dirty;
1671
1672        /* Unmodified entries are uninteresting except on the first pass */
1673        dirty = hpte_dirty(revp, hptp);
1674        if (!first_pass && !dirty)
1675                return 0;
1676
1677        valid = 0;
1678        if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT)) {
1679                valid = 1;
1680                if ((flags & KVM_GET_HTAB_BOLTED_ONLY) &&
1681                    !(be64_to_cpu(hptp[0]) & HPTE_V_BOLTED))
1682                        valid = 0;
1683        }
1684        if (valid != want_valid)
1685                return 0;
1686
1687        v = r = 0;
1688        if (valid || dirty) {
1689                /* lock the HPTE so it's stable and read it */
1690                preempt_disable();
1691                while (!try_lock_hpte(hptp, HPTE_V_HVLOCK))
1692                        cpu_relax();
1693                v = be64_to_cpu(hptp[0]);
1694                hr = be64_to_cpu(hptp[1]);
1695                if (cpu_has_feature(CPU_FTR_ARCH_300)) {
1696                        v = hpte_new_to_old_v(v, hr);
1697                        hr = hpte_new_to_old_r(hr);
1698                }
1699
1700                /* re-evaluate valid and dirty from synchronized HPTE value */
1701                valid = !!(v & HPTE_V_VALID);
1702                dirty = !!(revp->guest_rpte & HPTE_GR_MODIFIED);
1703
1704                /* Harvest R and C into guest view if necessary */
1705                rcbits_unset = ~revp->guest_rpte & (HPTE_R_R | HPTE_R_C);
1706                if (valid && (rcbits_unset & hr)) {
1707                        revp->guest_rpte |= (hr &
1708                                (HPTE_R_R | HPTE_R_C)) | HPTE_GR_MODIFIED;
1709                        dirty = 1;
1710                }
1711
1712                if (v & HPTE_V_ABSENT) {
1713                        v &= ~HPTE_V_ABSENT;
1714                        v |= HPTE_V_VALID;
1715                        valid = 1;
1716                }
1717                if ((flags & KVM_GET_HTAB_BOLTED_ONLY) && !(v & HPTE_V_BOLTED))
1718                        valid = 0;
1719
1720                r = revp->guest_rpte;
1721                /* only clear modified if this is the right sort of entry */
1722                if (valid == want_valid && dirty) {
1723                        r &= ~HPTE_GR_MODIFIED;
1724                        revp->guest_rpte = r;
1725                }
1726                unlock_hpte(hptp, be64_to_cpu(hptp[0]));
1727                preempt_enable();
1728                if (!(valid == want_valid && (first_pass || dirty)))
1729                        ok = 0;
1730        }
1731        hpte[0] = cpu_to_be64(v);
1732        hpte[1] = cpu_to_be64(r);
1733        return ok;
1734}
1735
1736static ssize_t kvm_htab_read(struct file *file, char __user *buf,
1737                             size_t count, loff_t *ppos)
1738{
1739        struct kvm_htab_ctx *ctx = file->private_data;
1740        struct kvm *kvm = ctx->kvm;
1741        struct kvm_get_htab_header hdr;
1742        __be64 *hptp;
1743        struct revmap_entry *revp;
1744        unsigned long i, nb, nw;
1745        unsigned long __user *lbuf;
1746        struct kvm_get_htab_header __user *hptr;
1747        unsigned long flags;
1748        int first_pass;
1749        unsigned long hpte[2];
1750
1751        if (!access_ok(VERIFY_WRITE, buf, count))
1752                return -EFAULT;
1753        if (kvm_is_radix(kvm))
1754                return 0;
1755
1756        first_pass = ctx->first_pass;
1757        flags = ctx->flags;
1758
1759        i = ctx->index;
1760        hptp = (__be64 *)(kvm->arch.hpt.virt + (i * HPTE_SIZE));
1761        revp = kvm->arch.hpt.rev + i;
1762        lbuf = (unsigned long __user *)buf;
1763
1764        nb = 0;
1765        while (nb + sizeof(hdr) + HPTE_SIZE < count) {
1766                /* Initialize header */
1767                hptr = (struct kvm_get_htab_header __user *)buf;
1768                hdr.n_valid = 0;
1769                hdr.n_invalid = 0;
1770                nw = nb;
1771                nb += sizeof(hdr);
1772                lbuf = (unsigned long __user *)(buf + sizeof(hdr));
1773
1774                /* Skip uninteresting entries, i.e. clean on not-first pass */
1775                if (!first_pass) {
1776                        while (i < kvmppc_hpt_npte(&kvm->arch.hpt) &&
1777                               !hpte_dirty(revp, hptp)) {
1778                                ++i;
1779                                hptp += 2;
1780                                ++revp;
1781                        }
1782                }
1783                hdr.index = i;
1784
1785                /* Grab a series of valid entries */
1786                while (i < kvmppc_hpt_npte(&kvm->arch.hpt) &&
1787                       hdr.n_valid < 0xffff &&
1788                       nb + HPTE_SIZE < count &&
1789                       record_hpte(flags, hptp, hpte, revp, 1, first_pass)) {
1790                        /* valid entry, write it out */
1791                        ++hdr.n_valid;
1792                        if (__put_user(hpte[0], lbuf) ||
1793                            __put_user(hpte[1], lbuf + 1))
1794                                return -EFAULT;
1795                        nb += HPTE_SIZE;
1796                        lbuf += 2;
1797                        ++i;
1798                        hptp += 2;
1799                        ++revp;
1800                }
1801                /* Now skip invalid entries while we can */
1802                while (i < kvmppc_hpt_npte(&kvm->arch.hpt) &&
1803                       hdr.n_invalid < 0xffff &&
1804                       record_hpte(flags, hptp, hpte, revp, 0, first_pass)) {
1805                        /* found an invalid entry */
1806                        ++hdr.n_invalid;
1807                        ++i;
1808                        hptp += 2;
1809                        ++revp;
1810                }
1811
1812                if (hdr.n_valid || hdr.n_invalid) {
1813                        /* write back the header */
1814                        if (__copy_to_user(hptr, &hdr, sizeof(hdr)))
1815                                return -EFAULT;
1816                        nw = nb;
1817                        buf = (char __user *)lbuf;
1818                } else {
1819                        nb = nw;
1820                }
1821
1822                /* Check if we've wrapped around the hash table */
1823                if (i >= kvmppc_hpt_npte(&kvm->arch.hpt)) {
1824                        i = 0;
1825                        ctx->first_pass = 0;
1826                        break;
1827                }
1828        }
1829
1830        ctx->index = i;
1831
1832        return nb;
1833}
1834
1835static ssize_t kvm_htab_write(struct file *file, const char __user *buf,
1836                              size_t count, loff_t *ppos)
1837{
1838        struct kvm_htab_ctx *ctx = file->private_data;
1839        struct kvm *kvm = ctx->kvm;
1840        struct kvm_get_htab_header hdr;
1841        unsigned long i, j;
1842        unsigned long v, r;
1843        unsigned long __user *lbuf;
1844        __be64 *hptp;
1845        unsigned long tmp[2];
1846        ssize_t nb;
1847        long int err, ret;
1848        int mmu_ready;
1849        int pshift;
1850
1851        if (!access_ok(VERIFY_READ, buf, count))
1852                return -EFAULT;
1853        if (kvm_is_radix(kvm))
1854                return -EINVAL;
1855
1856        /* lock out vcpus from running while we're doing this */
1857        mutex_lock(&kvm->lock);
1858        mmu_ready = kvm->arch.mmu_ready;
1859        if (mmu_ready) {
1860                kvm->arch.mmu_ready = 0;        /* temporarily */
1861                /* order mmu_ready vs. vcpus_running */
1862                smp_mb();
1863                if (atomic_read(&kvm->arch.vcpus_running)) {
1864                        kvm->arch.mmu_ready = 1;
1865                        mutex_unlock(&kvm->lock);
1866                        return -EBUSY;
1867                }
1868        }
1869
1870        err = 0;
1871        for (nb = 0; nb + sizeof(hdr) <= count; ) {
1872                err = -EFAULT;
1873                if (__copy_from_user(&hdr, buf, sizeof(hdr)))
1874                        break;
1875
1876                err = 0;
1877                if (nb + hdr.n_valid * HPTE_SIZE > count)
1878                        break;
1879
1880                nb += sizeof(hdr);
1881                buf += sizeof(hdr);
1882
1883                err = -EINVAL;
1884                i = hdr.index;
1885                if (i >= kvmppc_hpt_npte(&kvm->arch.hpt) ||
1886                    i + hdr.n_valid + hdr.n_invalid > kvmppc_hpt_npte(&kvm->arch.hpt))
1887                        break;
1888
1889                hptp = (__be64 *)(kvm->arch.hpt.virt + (i * HPTE_SIZE));
1890                lbuf = (unsigned long __user *)buf;
1891                for (j = 0; j < hdr.n_valid; ++j) {
1892                        __be64 hpte_v;
1893                        __be64 hpte_r;
1894
1895                        err = -EFAULT;
1896                        if (__get_user(hpte_v, lbuf) ||
1897                            __get_user(hpte_r, lbuf + 1))
1898                                goto out;
1899                        v = be64_to_cpu(hpte_v);
1900                        r = be64_to_cpu(hpte_r);
1901                        err = -EINVAL;
1902                        if (!(v & HPTE_V_VALID))
1903                                goto out;
1904                        pshift = kvmppc_hpte_base_page_shift(v, r);
1905                        if (pshift <= 0)
1906                                goto out;
1907                        lbuf += 2;
1908                        nb += HPTE_SIZE;
1909
1910                        if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT))
1911                                kvmppc_do_h_remove(kvm, 0, i, 0, tmp);
1912                        err = -EIO;
1913                        ret = kvmppc_virtmode_do_h_enter(kvm, H_EXACT, i, v, r,
1914                                                         tmp);
1915                        if (ret != H_SUCCESS) {
1916                                pr_err("kvm_htab_write ret %ld i=%ld v=%lx "
1917                                       "r=%lx\n", ret, i, v, r);
1918                                goto out;
1919                        }
1920                        if (!mmu_ready && is_vrma_hpte(v)) {
1921                                unsigned long senc, lpcr;
1922
1923                                senc = slb_pgsize_encoding(1ul << pshift);
1924                                kvm->arch.vrma_slb_v = senc | SLB_VSID_B_1T |
1925                                        (VRMA_VSID << SLB_VSID_SHIFT_1T);
1926                                if (!cpu_has_feature(CPU_FTR_ARCH_300)) {
1927                                        lpcr = senc << (LPCR_VRMASD_SH - 4);
1928                                        kvmppc_update_lpcr(kvm, lpcr,
1929                                                           LPCR_VRMASD);
1930                                } else {
1931                                        kvmppc_setup_partition_table(kvm);
1932                                }
1933                                mmu_ready = 1;
1934                        }
1935                        ++i;
1936                        hptp += 2;
1937                }
1938
1939                for (j = 0; j < hdr.n_invalid; ++j) {
1940                        if (be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT))
1941                                kvmppc_do_h_remove(kvm, 0, i, 0, tmp);
1942                        ++i;
1943                        hptp += 2;
1944                }
1945                err = 0;
1946        }
1947
1948 out:
1949        /* Order HPTE updates vs. mmu_ready */
1950        smp_wmb();
1951        kvm->arch.mmu_ready = mmu_ready;
1952        mutex_unlock(&kvm->lock);
1953
1954        if (err)
1955                return err;
1956        return nb;
1957}
1958
1959static int kvm_htab_release(struct inode *inode, struct file *filp)
1960{
1961        struct kvm_htab_ctx *ctx = filp->private_data;
1962
1963        filp->private_data = NULL;
1964        if (!(ctx->flags & KVM_GET_HTAB_WRITE))
1965                atomic_dec(&ctx->kvm->arch.hpte_mod_interest);
1966        kvm_put_kvm(ctx->kvm);
1967        kfree(ctx);
1968        return 0;
1969}
1970
1971static const struct file_operations kvm_htab_fops = {
1972        .read           = kvm_htab_read,
1973        .write          = kvm_htab_write,
1974        .llseek         = default_llseek,
1975        .release        = kvm_htab_release,
1976};
1977
1978int kvm_vm_ioctl_get_htab_fd(struct kvm *kvm, struct kvm_get_htab_fd *ghf)
1979{
1980        int ret;
1981        struct kvm_htab_ctx *ctx;
1982        int rwflag;
1983
1984        /* reject flags we don't recognize */
1985        if (ghf->flags & ~(KVM_GET_HTAB_BOLTED_ONLY | KVM_GET_HTAB_WRITE))
1986                return -EINVAL;
1987        ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1988        if (!ctx)
1989                return -ENOMEM;
1990        kvm_get_kvm(kvm);
1991        ctx->kvm = kvm;
1992        ctx->index = ghf->start_index;
1993        ctx->flags = ghf->flags;
1994        ctx->first_pass = 1;
1995
1996        rwflag = (ghf->flags & KVM_GET_HTAB_WRITE) ? O_WRONLY : O_RDONLY;
1997        ret = anon_inode_getfd("kvm-htab", &kvm_htab_fops, ctx, rwflag | O_CLOEXEC);
1998        if (ret < 0) {
1999                kfree(ctx);
2000                kvm_put_kvm(kvm);
2001                return ret;
2002        }
2003
2004        if (rwflag == O_RDONLY) {
2005                mutex_lock(&kvm->slots_lock);
2006                atomic_inc(&kvm->arch.hpte_mod_interest);
2007                /* make sure kvmppc_do_h_enter etc. see the increment */
2008                synchronize_srcu_expedited(&kvm->srcu);
2009                mutex_unlock(&kvm->slots_lock);
2010        }
2011
2012        return ret;
2013}
2014
2015struct debugfs_htab_state {
2016        struct kvm      *kvm;
2017        struct mutex    mutex;
2018        unsigned long   hpt_index;
2019        int             chars_left;
2020        int             buf_index;
2021        char            buf[64];
2022};
2023
2024static int debugfs_htab_open(struct inode *inode, struct file *file)
2025{
2026        struct kvm *kvm = inode->i_private;
2027        struct debugfs_htab_state *p;
2028
2029        p = kzalloc(sizeof(*p), GFP_KERNEL);
2030        if (!p)
2031                return -ENOMEM;
2032
2033        kvm_get_kvm(kvm);
2034        p->kvm = kvm;
2035        mutex_init(&p->mutex);
2036        file->private_data = p;
2037
2038        return nonseekable_open(inode, file);
2039}
2040
2041static int debugfs_htab_release(struct inode *inode, struct file *file)
2042{
2043        struct debugfs_htab_state *p = file->private_data;
2044
2045        kvm_put_kvm(p->kvm);
2046        kfree(p);
2047        return 0;
2048}
2049
2050static ssize_t debugfs_htab_read(struct file *file, char __user *buf,
2051                                 size_t len, loff_t *ppos)
2052{
2053        struct debugfs_htab_state *p = file->private_data;
2054        ssize_t ret, r;
2055        unsigned long i, n;
2056        unsigned long v, hr, gr;
2057        struct kvm *kvm;
2058        __be64 *hptp;
2059
2060        kvm = p->kvm;
2061        if (kvm_is_radix(kvm))
2062                return 0;
2063
2064        ret = mutex_lock_interruptible(&p->mutex);
2065        if (ret)
2066                return ret;
2067
2068        if (p->chars_left) {
2069                n = p->chars_left;
2070                if (n > len)
2071                        n = len;
2072                r = copy_to_user(buf, p->buf + p->buf_index, n);
2073                n -= r;
2074                p->chars_left -= n;
2075                p->buf_index += n;
2076                buf += n;
2077                len -= n;
2078                ret = n;
2079                if (r) {
2080                        if (!n)
2081                                ret = -EFAULT;
2082                        goto out;
2083                }
2084        }
2085
2086        i = p->hpt_index;
2087        hptp = (__be64 *)(kvm->arch.hpt.virt + (i * HPTE_SIZE));
2088        for (; len != 0 && i < kvmppc_hpt_npte(&kvm->arch.hpt);
2089             ++i, hptp += 2) {
2090                if (!(be64_to_cpu(hptp[0]) & (HPTE_V_VALID | HPTE_V_ABSENT)))
2091                        continue;
2092
2093                /* lock the HPTE so it's stable and read it */
2094                preempt_disable();
2095                while (!try_lock_hpte(hptp, HPTE_V_HVLOCK))
2096                        cpu_relax();
2097                v = be64_to_cpu(hptp[0]) & ~HPTE_V_HVLOCK;
2098                hr = be64_to_cpu(hptp[1]);
2099                gr = kvm->arch.hpt.rev[i].guest_rpte;
2100                unlock_hpte(hptp, v);
2101                preempt_enable();
2102
2103                if (!(v & (HPTE_V_VALID | HPTE_V_ABSENT)))
2104                        continue;
2105
2106                n = scnprintf(p->buf, sizeof(p->buf),
2107                              "%6lx %.16lx %.16lx %.16lx\n",
2108                              i, v, hr, gr);
2109                p->chars_left = n;
2110                if (n > len)
2111                        n = len;
2112                r = copy_to_user(buf, p->buf, n);
2113                n -= r;
2114                p->chars_left -= n;
2115                p->buf_index = n;
2116                buf += n;
2117                len -= n;
2118                ret += n;
2119                if (r) {
2120                        if (!ret)
2121                                ret = -EFAULT;
2122                        goto out;
2123                }
2124        }
2125        p->hpt_index = i;
2126
2127 out:
2128        mutex_unlock(&p->mutex);
2129        return ret;
2130}
2131
2132static ssize_t debugfs_htab_write(struct file *file, const char __user *buf,
2133                           size_t len, loff_t *ppos)
2134{
2135        return -EACCES;
2136}
2137
2138static const struct file_operations debugfs_htab_fops = {
2139        .owner   = THIS_MODULE,
2140        .open    = debugfs_htab_open,
2141        .release = debugfs_htab_release,
2142        .read    = debugfs_htab_read,
2143        .write   = debugfs_htab_write,
2144        .llseek  = generic_file_llseek,
2145};
2146
2147void kvmppc_mmu_debugfs_init(struct kvm *kvm)
2148{
2149        kvm->arch.htab_dentry = debugfs_create_file("htab", 0400,
2150                                                    kvm->arch.debugfs_dir, kvm,
2151                                                    &debugfs_htab_fops);
2152}
2153
2154void kvmppc_mmu_book3s_hv_init(struct kvm_vcpu *vcpu)
2155{
2156        struct kvmppc_mmu *mmu = &vcpu->arch.mmu;
2157
2158        vcpu->arch.slb_nr = 32;         /* POWER7/POWER8 */
2159
2160        mmu->xlate = kvmppc_mmu_book3s_64_hv_xlate;
2161        mmu->reset_msr = kvmppc_mmu_book3s_64_hv_reset_msr;
2162
2163        vcpu->arch.hflags |= BOOK3S_HFLAG_SLB;
2164}
2165