linux/arch/x86/kvm/mmu.c
<<
>>
Prefs
   1/*
   2 * Kernel-based Virtual Machine driver for Linux
   3 *
   4 * This module enables machines with Intel VT-x extensions to run virtual
   5 * machines without emulation or binary translation.
   6 *
   7 * MMU support
   8 *
   9 * Copyright (C) 2006 Qumranet, Inc.
  10 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  11 *
  12 * Authors:
  13 *   Yaniv Kamay  <yaniv@qumranet.com>
  14 *   Avi Kivity   <avi@qumranet.com>
  15 *
  16 * This work is licensed under the terms of the GNU GPL, version 2.  See
  17 * the COPYING file in the top-level directory.
  18 *
  19 */
  20
  21#include "irq.h"
  22#include "mmu.h"
  23#include "x86.h"
  24#include "kvm_cache_regs.h"
  25#include "cpuid.h"
  26
  27#include <linux/kvm_host.h>
  28#include <linux/types.h>
  29#include <linux/string.h>
  30#include <linux/mm.h>
  31#include <linux/highmem.h>
  32#include <linux/module.h>
  33#include <linux/swap.h>
  34#include <linux/hugetlb.h>
  35#include <linux/compiler.h>
  36#include <linux/srcu.h>
  37#include <linux/slab.h>
  38#include <linux/uaccess.h>
  39#include <linux/hash.h>
  40#include <linux/kern_levels.h>
  41
  42#include <asm/page.h>
  43#include <asm/cmpxchg.h>
  44#include <asm/io.h>
  45#include <asm/vmx.h>
  46#include <asm/kvm_page_track.h>
  47
  48/*
  49 * When setting this variable to true it enables Two-Dimensional-Paging
  50 * where the hardware walks 2 page tables:
  51 * 1. the guest-virtual to guest-physical
  52 * 2. while doing 1. it walks guest-physical to host-physical
  53 * If the hardware supports that we don't need to do shadow paging.
  54 */
  55bool tdp_enabled = false;
  56
  57enum {
  58        AUDIT_PRE_PAGE_FAULT,
  59        AUDIT_POST_PAGE_FAULT,
  60        AUDIT_PRE_PTE_WRITE,
  61        AUDIT_POST_PTE_WRITE,
  62        AUDIT_PRE_SYNC,
  63        AUDIT_POST_SYNC
  64};
  65
  66#undef MMU_DEBUG
  67
  68#ifdef MMU_DEBUG
  69static bool dbg = 0;
  70module_param(dbg, bool, 0644);
  71
  72#define pgprintk(x...) do { if (dbg) printk(x); } while (0)
  73#define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
  74#define MMU_WARN_ON(x) WARN_ON(x)
  75#else
  76#define pgprintk(x...) do { } while (0)
  77#define rmap_printk(x...) do { } while (0)
  78#define MMU_WARN_ON(x) do { } while (0)
  79#endif
  80
  81#define PTE_PREFETCH_NUM                8
  82
  83#define PT_FIRST_AVAIL_BITS_SHIFT 10
  84#define PT64_SECOND_AVAIL_BITS_SHIFT 52
  85
  86#define PT64_LEVEL_BITS 9
  87
  88#define PT64_LEVEL_SHIFT(level) \
  89                (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
  90
  91#define PT64_INDEX(address, level)\
  92        (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
  93
  94
  95#define PT32_LEVEL_BITS 10
  96
  97#define PT32_LEVEL_SHIFT(level) \
  98                (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
  99
 100#define PT32_LVL_OFFSET_MASK(level) \
 101        (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
 102                                                * PT32_LEVEL_BITS))) - 1))
 103
 104#define PT32_INDEX(address, level)\
 105        (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
 106
 107
 108#define PT64_BASE_ADDR_MASK __sme_clr((((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1)))
 109#define PT64_DIR_BASE_ADDR_MASK \
 110        (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
 111#define PT64_LVL_ADDR_MASK(level) \
 112        (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
 113                                                * PT64_LEVEL_BITS))) - 1))
 114#define PT64_LVL_OFFSET_MASK(level) \
 115        (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
 116                                                * PT64_LEVEL_BITS))) - 1))
 117
 118#define PT32_BASE_ADDR_MASK PAGE_MASK
 119#define PT32_DIR_BASE_ADDR_MASK \
 120        (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
 121#define PT32_LVL_ADDR_MASK(level) \
 122        (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
 123                                            * PT32_LEVEL_BITS))) - 1))
 124
 125#define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
 126                        | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
 127
 128#define ACC_EXEC_MASK    1
 129#define ACC_WRITE_MASK   PT_WRITABLE_MASK
 130#define ACC_USER_MASK    PT_USER_MASK
 131#define ACC_ALL          (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
 132
 133/* The mask for the R/X bits in EPT PTEs */
 134#define PT64_EPT_READABLE_MASK                  0x1ull
 135#define PT64_EPT_EXECUTABLE_MASK                0x4ull
 136
 137#include <trace/events/kvm.h>
 138
 139#define CREATE_TRACE_POINTS
 140#include "mmutrace.h"
 141
 142#define SPTE_HOST_WRITEABLE     (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
 143#define SPTE_MMU_WRITEABLE      (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
 144
 145#define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
 146
 147/* make pte_list_desc fit well in cache line */
 148#define PTE_LIST_EXT 3
 149
 150struct pte_list_desc {
 151        u64 *sptes[PTE_LIST_EXT];
 152        struct pte_list_desc *more;
 153};
 154
 155struct kvm_shadow_walk_iterator {
 156        u64 addr;
 157        hpa_t shadow_addr;
 158        u64 *sptep;
 159        int level;
 160        unsigned index;
 161};
 162
 163#define for_each_shadow_entry(_vcpu, _addr, _walker)    \
 164        for (shadow_walk_init(&(_walker), _vcpu, _addr);        \
 165             shadow_walk_okay(&(_walker));                      \
 166             shadow_walk_next(&(_walker)))
 167
 168#define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)     \
 169        for (shadow_walk_init(&(_walker), _vcpu, _addr);                \
 170             shadow_walk_okay(&(_walker)) &&                            \
 171                ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });  \
 172             __shadow_walk_next(&(_walker), spte))
 173
 174static struct kmem_cache *pte_list_desc_cache;
 175static struct kmem_cache *mmu_page_header_cache;
 176static struct percpu_counter kvm_total_used_mmu_pages;
 177
 178static u64 __read_mostly shadow_nx_mask;
 179static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
 180static u64 __read_mostly shadow_user_mask;
 181static u64 __read_mostly shadow_accessed_mask;
 182static u64 __read_mostly shadow_dirty_mask;
 183static u64 __read_mostly shadow_mmio_mask;
 184static u64 __read_mostly shadow_mmio_value;
 185static u64 __read_mostly shadow_present_mask;
 186static u64 __read_mostly shadow_me_mask;
 187
 188/*
 189 * SPTEs used by MMUs without A/D bits are marked with shadow_acc_track_value.
 190 * Non-present SPTEs with shadow_acc_track_value set are in place for access
 191 * tracking.
 192 */
 193static u64 __read_mostly shadow_acc_track_mask;
 194static const u64 shadow_acc_track_value = SPTE_SPECIAL_MASK;
 195
 196/*
 197 * The mask/shift to use for saving the original R/X bits when marking the PTE
 198 * as not-present for access tracking purposes. We do not save the W bit as the
 199 * PTEs being access tracked also need to be dirty tracked, so the W bit will be
 200 * restored only when a write is attempted to the page.
 201 */
 202static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
 203                                                    PT64_EPT_EXECUTABLE_MASK;
 204static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
 205
 206static void mmu_spte_set(u64 *sptep, u64 spte);
 207static void mmu_free_roots(struct kvm_vcpu *vcpu);
 208
 209void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value)
 210{
 211        BUG_ON((mmio_mask & mmio_value) != mmio_value);
 212        shadow_mmio_value = mmio_value | SPTE_SPECIAL_MASK;
 213        shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
 214}
 215EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
 216
 217static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
 218{
 219        return sp->role.ad_disabled;
 220}
 221
 222static inline bool spte_ad_enabled(u64 spte)
 223{
 224        MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
 225        return !(spte & shadow_acc_track_value);
 226}
 227
 228static inline u64 spte_shadow_accessed_mask(u64 spte)
 229{
 230        MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
 231        return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
 232}
 233
 234static inline u64 spte_shadow_dirty_mask(u64 spte)
 235{
 236        MMU_WARN_ON((spte & shadow_mmio_mask) == shadow_mmio_value);
 237        return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
 238}
 239
 240static inline bool is_access_track_spte(u64 spte)
 241{
 242        return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
 243}
 244
 245/*
 246 * the low bit of the generation number is always presumed to be zero.
 247 * This disables mmio caching during memslot updates.  The concept is
 248 * similar to a seqcount but instead of retrying the access we just punt
 249 * and ignore the cache.
 250 *
 251 * spte bits 3-11 are used as bits 1-9 of the generation number,
 252 * the bits 52-61 are used as bits 10-19 of the generation number.
 253 */
 254#define MMIO_SPTE_GEN_LOW_SHIFT         2
 255#define MMIO_SPTE_GEN_HIGH_SHIFT        52
 256
 257#define MMIO_GEN_SHIFT                  20
 258#define MMIO_GEN_LOW_SHIFT              10
 259#define MMIO_GEN_LOW_MASK               ((1 << MMIO_GEN_LOW_SHIFT) - 2)
 260#define MMIO_GEN_MASK                   ((1 << MMIO_GEN_SHIFT) - 1)
 261
 262static u64 generation_mmio_spte_mask(unsigned int gen)
 263{
 264        u64 mask;
 265
 266        WARN_ON(gen & ~MMIO_GEN_MASK);
 267
 268        mask = (gen & MMIO_GEN_LOW_MASK) << MMIO_SPTE_GEN_LOW_SHIFT;
 269        mask |= ((u64)gen >> MMIO_GEN_LOW_SHIFT) << MMIO_SPTE_GEN_HIGH_SHIFT;
 270        return mask;
 271}
 272
 273static unsigned int get_mmio_spte_generation(u64 spte)
 274{
 275        unsigned int gen;
 276
 277        spte &= ~shadow_mmio_mask;
 278
 279        gen = (spte >> MMIO_SPTE_GEN_LOW_SHIFT) & MMIO_GEN_LOW_MASK;
 280        gen |= (spte >> MMIO_SPTE_GEN_HIGH_SHIFT) << MMIO_GEN_LOW_SHIFT;
 281        return gen;
 282}
 283
 284static unsigned int kvm_current_mmio_generation(struct kvm_vcpu *vcpu)
 285{
 286        return kvm_vcpu_memslots(vcpu)->generation & MMIO_GEN_MASK;
 287}
 288
 289static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
 290                           unsigned access)
 291{
 292        unsigned int gen = kvm_current_mmio_generation(vcpu);
 293        u64 mask = generation_mmio_spte_mask(gen);
 294
 295        access &= ACC_WRITE_MASK | ACC_USER_MASK;
 296        mask |= shadow_mmio_value | access | gfn << PAGE_SHIFT;
 297
 298        trace_mark_mmio_spte(sptep, gfn, access, gen);
 299        mmu_spte_set(sptep, mask);
 300}
 301
 302static bool is_mmio_spte(u64 spte)
 303{
 304        return (spte & shadow_mmio_mask) == shadow_mmio_value;
 305}
 306
 307static gfn_t get_mmio_spte_gfn(u64 spte)
 308{
 309        u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
 310        return (spte & ~mask) >> PAGE_SHIFT;
 311}
 312
 313static unsigned get_mmio_spte_access(u64 spte)
 314{
 315        u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
 316        return (spte & ~mask) & ~PAGE_MASK;
 317}
 318
 319static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
 320                          kvm_pfn_t pfn, unsigned access)
 321{
 322        if (unlikely(is_noslot_pfn(pfn))) {
 323                mark_mmio_spte(vcpu, sptep, gfn, access);
 324                return true;
 325        }
 326
 327        return false;
 328}
 329
 330static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
 331{
 332        unsigned int kvm_gen, spte_gen;
 333
 334        kvm_gen = kvm_current_mmio_generation(vcpu);
 335        spte_gen = get_mmio_spte_generation(spte);
 336
 337        trace_check_mmio_spte(spte, kvm_gen, spte_gen);
 338        return likely(kvm_gen == spte_gen);
 339}
 340
 341/*
 342 * Sets the shadow PTE masks used by the MMU.
 343 *
 344 * Assumptions:
 345 *  - Setting either @accessed_mask or @dirty_mask requires setting both
 346 *  - At least one of @accessed_mask or @acc_track_mask must be set
 347 */
 348void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
 349                u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
 350                u64 acc_track_mask, u64 me_mask)
 351{
 352        BUG_ON(!dirty_mask != !accessed_mask);
 353        BUG_ON(!accessed_mask && !acc_track_mask);
 354        BUG_ON(acc_track_mask & shadow_acc_track_value);
 355
 356        shadow_user_mask = user_mask;
 357        shadow_accessed_mask = accessed_mask;
 358        shadow_dirty_mask = dirty_mask;
 359        shadow_nx_mask = nx_mask;
 360        shadow_x_mask = x_mask;
 361        shadow_present_mask = p_mask;
 362        shadow_acc_track_mask = acc_track_mask;
 363        shadow_me_mask = me_mask;
 364}
 365EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
 366
 367void kvm_mmu_clear_all_pte_masks(void)
 368{
 369        shadow_user_mask = 0;
 370        shadow_accessed_mask = 0;
 371        shadow_dirty_mask = 0;
 372        shadow_nx_mask = 0;
 373        shadow_x_mask = 0;
 374        shadow_mmio_mask = 0;
 375        shadow_present_mask = 0;
 376        shadow_acc_track_mask = 0;
 377}
 378
 379static int is_cpuid_PSE36(void)
 380{
 381        return 1;
 382}
 383
 384static int is_nx(struct kvm_vcpu *vcpu)
 385{
 386        return vcpu->arch.efer & EFER_NX;
 387}
 388
 389static int is_shadow_present_pte(u64 pte)
 390{
 391        return (pte != 0) && !is_mmio_spte(pte);
 392}
 393
 394static int is_large_pte(u64 pte)
 395{
 396        return pte & PT_PAGE_SIZE_MASK;
 397}
 398
 399static int is_last_spte(u64 pte, int level)
 400{
 401        if (level == PT_PAGE_TABLE_LEVEL)
 402                return 1;
 403        if (is_large_pte(pte))
 404                return 1;
 405        return 0;
 406}
 407
 408static bool is_executable_pte(u64 spte)
 409{
 410        return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
 411}
 412
 413static kvm_pfn_t spte_to_pfn(u64 pte)
 414{
 415        return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
 416}
 417
 418static gfn_t pse36_gfn_delta(u32 gpte)
 419{
 420        int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
 421
 422        return (gpte & PT32_DIR_PSE36_MASK) << shift;
 423}
 424
 425#ifdef CONFIG_X86_64
 426static void __set_spte(u64 *sptep, u64 spte)
 427{
 428        WRITE_ONCE(*sptep, spte);
 429}
 430
 431static void __update_clear_spte_fast(u64 *sptep, u64 spte)
 432{
 433        WRITE_ONCE(*sptep, spte);
 434}
 435
 436static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
 437{
 438        return xchg(sptep, spte);
 439}
 440
 441static u64 __get_spte_lockless(u64 *sptep)
 442{
 443        return ACCESS_ONCE(*sptep);
 444}
 445#else
 446union split_spte {
 447        struct {
 448                u32 spte_low;
 449                u32 spte_high;
 450        };
 451        u64 spte;
 452};
 453
 454static void count_spte_clear(u64 *sptep, u64 spte)
 455{
 456        struct kvm_mmu_page *sp =  page_header(__pa(sptep));
 457
 458        if (is_shadow_present_pte(spte))
 459                return;
 460
 461        /* Ensure the spte is completely set before we increase the count */
 462        smp_wmb();
 463        sp->clear_spte_count++;
 464}
 465
 466static void __set_spte(u64 *sptep, u64 spte)
 467{
 468        union split_spte *ssptep, sspte;
 469
 470        ssptep = (union split_spte *)sptep;
 471        sspte = (union split_spte)spte;
 472
 473        ssptep->spte_high = sspte.spte_high;
 474
 475        /*
 476         * If we map the spte from nonpresent to present, We should store
 477         * the high bits firstly, then set present bit, so cpu can not
 478         * fetch this spte while we are setting the spte.
 479         */
 480        smp_wmb();
 481
 482        WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
 483}
 484
 485static void __update_clear_spte_fast(u64 *sptep, u64 spte)
 486{
 487        union split_spte *ssptep, sspte;
 488
 489        ssptep = (union split_spte *)sptep;
 490        sspte = (union split_spte)spte;
 491
 492        WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
 493
 494        /*
 495         * If we map the spte from present to nonpresent, we should clear
 496         * present bit firstly to avoid vcpu fetch the old high bits.
 497         */
 498        smp_wmb();
 499
 500        ssptep->spte_high = sspte.spte_high;
 501        count_spte_clear(sptep, spte);
 502}
 503
 504static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
 505{
 506        union split_spte *ssptep, sspte, orig;
 507
 508        ssptep = (union split_spte *)sptep;
 509        sspte = (union split_spte)spte;
 510
 511        /* xchg acts as a barrier before the setting of the high bits */
 512        orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
 513        orig.spte_high = ssptep->spte_high;
 514        ssptep->spte_high = sspte.spte_high;
 515        count_spte_clear(sptep, spte);
 516
 517        return orig.spte;
 518}
 519
 520/*
 521 * The idea using the light way get the spte on x86_32 guest is from
 522 * gup_get_pte(arch/x86/mm/gup.c).
 523 *
 524 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
 525 * coalesces them and we are running out of the MMU lock.  Therefore
 526 * we need to protect against in-progress updates of the spte.
 527 *
 528 * Reading the spte while an update is in progress may get the old value
 529 * for the high part of the spte.  The race is fine for a present->non-present
 530 * change (because the high part of the spte is ignored for non-present spte),
 531 * but for a present->present change we must reread the spte.
 532 *
 533 * All such changes are done in two steps (present->non-present and
 534 * non-present->present), hence it is enough to count the number of
 535 * present->non-present updates: if it changed while reading the spte,
 536 * we might have hit the race.  This is done using clear_spte_count.
 537 */
 538static u64 __get_spte_lockless(u64 *sptep)
 539{
 540        struct kvm_mmu_page *sp =  page_header(__pa(sptep));
 541        union split_spte spte, *orig = (union split_spte *)sptep;
 542        int count;
 543
 544retry:
 545        count = sp->clear_spte_count;
 546        smp_rmb();
 547
 548        spte.spte_low = orig->spte_low;
 549        smp_rmb();
 550
 551        spte.spte_high = orig->spte_high;
 552        smp_rmb();
 553
 554        if (unlikely(spte.spte_low != orig->spte_low ||
 555              count != sp->clear_spte_count))
 556                goto retry;
 557
 558        return spte.spte;
 559}
 560#endif
 561
 562static bool spte_can_locklessly_be_made_writable(u64 spte)
 563{
 564        return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
 565                (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
 566}
 567
 568static bool spte_has_volatile_bits(u64 spte)
 569{
 570        if (!is_shadow_present_pte(spte))
 571                return false;
 572
 573        /*
 574         * Always atomicly update spte if it can be updated
 575         * out of mmu-lock, it can ensure dirty bit is not lost,
 576         * also, it can help us to get a stable is_writable_pte()
 577         * to ensure tlb flush is not missed.
 578         */
 579        if (spte_can_locklessly_be_made_writable(spte) ||
 580            is_access_track_spte(spte))
 581                return true;
 582
 583        if (spte_ad_enabled(spte)) {
 584                if ((spte & shadow_accessed_mask) == 0 ||
 585                    (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
 586                        return true;
 587        }
 588
 589        return false;
 590}
 591
 592static bool is_accessed_spte(u64 spte)
 593{
 594        u64 accessed_mask = spte_shadow_accessed_mask(spte);
 595
 596        return accessed_mask ? spte & accessed_mask
 597                             : !is_access_track_spte(spte);
 598}
 599
 600static bool is_dirty_spte(u64 spte)
 601{
 602        u64 dirty_mask = spte_shadow_dirty_mask(spte);
 603
 604        return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
 605}
 606
 607/* Rules for using mmu_spte_set:
 608 * Set the sptep from nonpresent to present.
 609 * Note: the sptep being assigned *must* be either not present
 610 * or in a state where the hardware will not attempt to update
 611 * the spte.
 612 */
 613static void mmu_spte_set(u64 *sptep, u64 new_spte)
 614{
 615        WARN_ON(is_shadow_present_pte(*sptep));
 616        __set_spte(sptep, new_spte);
 617}
 618
 619/*
 620 * Update the SPTE (excluding the PFN), but do not track changes in its
 621 * accessed/dirty status.
 622 */
 623static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
 624{
 625        u64 old_spte = *sptep;
 626
 627        WARN_ON(!is_shadow_present_pte(new_spte));
 628
 629        if (!is_shadow_present_pte(old_spte)) {
 630                mmu_spte_set(sptep, new_spte);
 631                return old_spte;
 632        }
 633
 634        if (!spte_has_volatile_bits(old_spte))
 635                __update_clear_spte_fast(sptep, new_spte);
 636        else
 637                old_spte = __update_clear_spte_slow(sptep, new_spte);
 638
 639        WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
 640
 641        return old_spte;
 642}
 643
 644/* Rules for using mmu_spte_update:
 645 * Update the state bits, it means the mapped pfn is not changed.
 646 *
 647 * Whenever we overwrite a writable spte with a read-only one we
 648 * should flush remote TLBs. Otherwise rmap_write_protect
 649 * will find a read-only spte, even though the writable spte
 650 * might be cached on a CPU's TLB, the return value indicates this
 651 * case.
 652 *
 653 * Returns true if the TLB needs to be flushed
 654 */
 655static bool mmu_spte_update(u64 *sptep, u64 new_spte)
 656{
 657        bool flush = false;
 658        u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
 659
 660        if (!is_shadow_present_pte(old_spte))
 661                return false;
 662
 663        /*
 664         * For the spte updated out of mmu-lock is safe, since
 665         * we always atomicly update it, see the comments in
 666         * spte_has_volatile_bits().
 667         */
 668        if (spte_can_locklessly_be_made_writable(old_spte) &&
 669              !is_writable_pte(new_spte))
 670                flush = true;
 671
 672        /*
 673         * Flush TLB when accessed/dirty states are changed in the page tables,
 674         * to guarantee consistency between TLB and page tables.
 675         */
 676
 677        if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
 678                flush = true;
 679                kvm_set_pfn_accessed(spte_to_pfn(old_spte));
 680        }
 681
 682        if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
 683                flush = true;
 684                kvm_set_pfn_dirty(spte_to_pfn(old_spte));
 685        }
 686
 687        return flush;
 688}
 689
 690/*
 691 * Rules for using mmu_spte_clear_track_bits:
 692 * It sets the sptep from present to nonpresent, and track the
 693 * state bits, it is used to clear the last level sptep.
 694 * Returns non-zero if the PTE was previously valid.
 695 */
 696static int mmu_spte_clear_track_bits(u64 *sptep)
 697{
 698        kvm_pfn_t pfn;
 699        u64 old_spte = *sptep;
 700
 701        if (!spte_has_volatile_bits(old_spte))
 702                __update_clear_spte_fast(sptep, 0ull);
 703        else
 704                old_spte = __update_clear_spte_slow(sptep, 0ull);
 705
 706        if (!is_shadow_present_pte(old_spte))
 707                return 0;
 708
 709        pfn = spte_to_pfn(old_spte);
 710
 711        /*
 712         * KVM does not hold the refcount of the page used by
 713         * kvm mmu, before reclaiming the page, we should
 714         * unmap it from mmu first.
 715         */
 716        WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
 717
 718        if (is_accessed_spte(old_spte))
 719                kvm_set_pfn_accessed(pfn);
 720
 721        if (is_dirty_spte(old_spte))
 722                kvm_set_pfn_dirty(pfn);
 723
 724        return 1;
 725}
 726
 727/*
 728 * Rules for using mmu_spte_clear_no_track:
 729 * Directly clear spte without caring the state bits of sptep,
 730 * it is used to set the upper level spte.
 731 */
 732static void mmu_spte_clear_no_track(u64 *sptep)
 733{
 734        __update_clear_spte_fast(sptep, 0ull);
 735}
 736
 737static u64 mmu_spte_get_lockless(u64 *sptep)
 738{
 739        return __get_spte_lockless(sptep);
 740}
 741
 742static u64 mark_spte_for_access_track(u64 spte)
 743{
 744        if (spte_ad_enabled(spte))
 745                return spte & ~shadow_accessed_mask;
 746
 747        if (is_access_track_spte(spte))
 748                return spte;
 749
 750        /*
 751         * Making an Access Tracking PTE will result in removal of write access
 752         * from the PTE. So, verify that we will be able to restore the write
 753         * access in the fast page fault path later on.
 754         */
 755        WARN_ONCE((spte & PT_WRITABLE_MASK) &&
 756                  !spte_can_locklessly_be_made_writable(spte),
 757                  "kvm: Writable SPTE is not locklessly dirty-trackable\n");
 758
 759        WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
 760                          shadow_acc_track_saved_bits_shift),
 761                  "kvm: Access Tracking saved bit locations are not zero\n");
 762
 763        spte |= (spte & shadow_acc_track_saved_bits_mask) <<
 764                shadow_acc_track_saved_bits_shift;
 765        spte &= ~shadow_acc_track_mask;
 766
 767        return spte;
 768}
 769
 770/* Restore an acc-track PTE back to a regular PTE */
 771static u64 restore_acc_track_spte(u64 spte)
 772{
 773        u64 new_spte = spte;
 774        u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
 775                         & shadow_acc_track_saved_bits_mask;
 776
 777        WARN_ON_ONCE(spte_ad_enabled(spte));
 778        WARN_ON_ONCE(!is_access_track_spte(spte));
 779
 780        new_spte &= ~shadow_acc_track_mask;
 781        new_spte &= ~(shadow_acc_track_saved_bits_mask <<
 782                      shadow_acc_track_saved_bits_shift);
 783        new_spte |= saved_bits;
 784
 785        return new_spte;
 786}
 787
 788/* Returns the Accessed status of the PTE and resets it at the same time. */
 789static bool mmu_spte_age(u64 *sptep)
 790{
 791        u64 spte = mmu_spte_get_lockless(sptep);
 792
 793        if (!is_accessed_spte(spte))
 794                return false;
 795
 796        if (spte_ad_enabled(spte)) {
 797                clear_bit((ffs(shadow_accessed_mask) - 1),
 798                          (unsigned long *)sptep);
 799        } else {
 800                /*
 801                 * Capture the dirty status of the page, so that it doesn't get
 802                 * lost when the SPTE is marked for access tracking.
 803                 */
 804                if (is_writable_pte(spte))
 805                        kvm_set_pfn_dirty(spte_to_pfn(spte));
 806
 807                spte = mark_spte_for_access_track(spte);
 808                mmu_spte_update_no_track(sptep, spte);
 809        }
 810
 811        return true;
 812}
 813
 814static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
 815{
 816        /*
 817         * Prevent page table teardown by making any free-er wait during
 818         * kvm_flush_remote_tlbs() IPI to all active vcpus.
 819         */
 820        local_irq_disable();
 821        vcpu->mode = READING_SHADOW_PAGE_TABLES;
 822        /*
 823         * Make sure a following spte read is not reordered ahead of the write
 824         * to vcpu->mode.
 825         */
 826        smp_mb();
 827}
 828
 829static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
 830{
 831        /*
 832         * Make sure the write to vcpu->mode is not reordered in front of
 833         * reads to sptes.  If it does, kvm_commit_zap_page() can see us
 834         * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
 835         */
 836        smp_mb();
 837        vcpu->mode = OUTSIDE_GUEST_MODE;
 838        local_irq_enable();
 839}
 840
 841static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
 842                                  struct kmem_cache *base_cache, int min)
 843{
 844        void *obj;
 845
 846        if (cache->nobjs >= min)
 847                return 0;
 848        while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
 849                obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
 850                if (!obj)
 851                        return -ENOMEM;
 852                cache->objects[cache->nobjs++] = obj;
 853        }
 854        return 0;
 855}
 856
 857static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
 858{
 859        return cache->nobjs;
 860}
 861
 862static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
 863                                  struct kmem_cache *cache)
 864{
 865        while (mc->nobjs)
 866                kmem_cache_free(cache, mc->objects[--mc->nobjs]);
 867}
 868
 869static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
 870                                       int min)
 871{
 872        void *page;
 873
 874        if (cache->nobjs >= min)
 875                return 0;
 876        while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
 877                page = (void *)__get_free_page(GFP_KERNEL);
 878                if (!page)
 879                        return -ENOMEM;
 880                cache->objects[cache->nobjs++] = page;
 881        }
 882        return 0;
 883}
 884
 885static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
 886{
 887        while (mc->nobjs)
 888                free_page((unsigned long)mc->objects[--mc->nobjs]);
 889}
 890
 891static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
 892{
 893        int r;
 894
 895        r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
 896                                   pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
 897        if (r)
 898                goto out;
 899        r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
 900        if (r)
 901                goto out;
 902        r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
 903                                   mmu_page_header_cache, 4);
 904out:
 905        return r;
 906}
 907
 908static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
 909{
 910        mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
 911                                pte_list_desc_cache);
 912        mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
 913        mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
 914                                mmu_page_header_cache);
 915}
 916
 917static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
 918{
 919        void *p;
 920
 921        BUG_ON(!mc->nobjs);
 922        p = mc->objects[--mc->nobjs];
 923        return p;
 924}
 925
 926static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
 927{
 928        return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
 929}
 930
 931static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
 932{
 933        kmem_cache_free(pte_list_desc_cache, pte_list_desc);
 934}
 935
 936static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
 937{
 938        if (!sp->role.direct)
 939                return sp->gfns[index];
 940
 941        return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
 942}
 943
 944static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
 945{
 946        if (sp->role.direct)
 947                BUG_ON(gfn != kvm_mmu_page_get_gfn(sp, index));
 948        else
 949                sp->gfns[index] = gfn;
 950}
 951
 952/*
 953 * Return the pointer to the large page information for a given gfn,
 954 * handling slots that are not large page aligned.
 955 */
 956static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
 957                                              struct kvm_memory_slot *slot,
 958                                              int level)
 959{
 960        unsigned long idx;
 961
 962        idx = gfn_to_index(gfn, slot->base_gfn, level);
 963        return &slot->arch.lpage_info[level - 2][idx];
 964}
 965
 966static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
 967                                            gfn_t gfn, int count)
 968{
 969        struct kvm_lpage_info *linfo;
 970        int i;
 971
 972        for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
 973                linfo = lpage_info_slot(gfn, slot, i);
 974                linfo->disallow_lpage += count;
 975                WARN_ON(linfo->disallow_lpage < 0);
 976        }
 977}
 978
 979void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
 980{
 981        update_gfn_disallow_lpage_count(slot, gfn, 1);
 982}
 983
 984void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
 985{
 986        update_gfn_disallow_lpage_count(slot, gfn, -1);
 987}
 988
 989static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
 990{
 991        struct kvm_memslots *slots;
 992        struct kvm_memory_slot *slot;
 993        gfn_t gfn;
 994
 995        kvm->arch.indirect_shadow_pages++;
 996        gfn = sp->gfn;
 997        slots = kvm_memslots_for_spte_role(kvm, sp->role);
 998        slot = __gfn_to_memslot(slots, gfn);
 999
1000        /* the non-leaf shadow pages are keeping readonly. */
1001        if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1002                return kvm_slot_page_track_add_page(kvm, slot, gfn,
1003                                                    KVM_PAGE_TRACK_WRITE);
1004
1005        kvm_mmu_gfn_disallow_lpage(slot, gfn);
1006}
1007
1008static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1009{
1010        struct kvm_memslots *slots;
1011        struct kvm_memory_slot *slot;
1012        gfn_t gfn;
1013
1014        kvm->arch.indirect_shadow_pages--;
1015        gfn = sp->gfn;
1016        slots = kvm_memslots_for_spte_role(kvm, sp->role);
1017        slot = __gfn_to_memslot(slots, gfn);
1018        if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1019                return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1020                                                       KVM_PAGE_TRACK_WRITE);
1021
1022        kvm_mmu_gfn_allow_lpage(slot, gfn);
1023}
1024
1025static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1026                                          struct kvm_memory_slot *slot)
1027{
1028        struct kvm_lpage_info *linfo;
1029
1030        if (slot) {
1031                linfo = lpage_info_slot(gfn, slot, level);
1032                return !!linfo->disallow_lpage;
1033        }
1034
1035        return true;
1036}
1037
1038static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1039                                        int level)
1040{
1041        struct kvm_memory_slot *slot;
1042
1043        slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1044        return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1045}
1046
1047static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
1048{
1049        unsigned long page_size;
1050        int i, ret = 0;
1051
1052        page_size = kvm_host_page_size(kvm, gfn);
1053
1054        for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1055                if (page_size >= KVM_HPAGE_SIZE(i))
1056                        ret = i;
1057                else
1058                        break;
1059        }
1060
1061        return ret;
1062}
1063
1064static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1065                                          bool no_dirty_log)
1066{
1067        if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1068                return false;
1069        if (no_dirty_log && slot->dirty_bitmap)
1070                return false;
1071
1072        return true;
1073}
1074
1075static struct kvm_memory_slot *
1076gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1077                            bool no_dirty_log)
1078{
1079        struct kvm_memory_slot *slot;
1080
1081        slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1082        if (!memslot_valid_for_gpte(slot, no_dirty_log))
1083                slot = NULL;
1084
1085        return slot;
1086}
1087
1088static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1089                         bool *force_pt_level)
1090{
1091        int host_level, level, max_level;
1092        struct kvm_memory_slot *slot;
1093
1094        slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1095
1096        if (likely(!*force_pt_level))
1097                *force_pt_level = !memslot_valid_for_gpte(slot, true);
1098        if (unlikely(*force_pt_level))
1099                return PT_PAGE_TABLE_LEVEL;
1100
1101        host_level = host_mapping_level(vcpu->kvm, large_gfn);
1102
1103        if (host_level == PT_PAGE_TABLE_LEVEL)
1104                return host_level;
1105
1106        max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1107
1108        for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1109                if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1110                        break;
1111
1112        return level - 1;
1113}
1114
1115/*
1116 * About rmap_head encoding:
1117 *
1118 * If the bit zero of rmap_head->val is clear, then it points to the only spte
1119 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1120 * pte_list_desc containing more mappings.
1121 */
1122
1123/*
1124 * Returns the number of pointers in the rmap chain, not counting the new one.
1125 */
1126static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1127                        struct kvm_rmap_head *rmap_head)
1128{
1129        struct pte_list_desc *desc;
1130        int i, count = 0;
1131
1132        if (!rmap_head->val) {
1133                rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1134                rmap_head->val = (unsigned long)spte;
1135        } else if (!(rmap_head->val & 1)) {
1136                rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1137                desc = mmu_alloc_pte_list_desc(vcpu);
1138                desc->sptes[0] = (u64 *)rmap_head->val;
1139                desc->sptes[1] = spte;
1140                rmap_head->val = (unsigned long)desc | 1;
1141                ++count;
1142        } else {
1143                rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1144                desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1145                while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1146                        desc = desc->more;
1147                        count += PTE_LIST_EXT;
1148                }
1149                if (desc->sptes[PTE_LIST_EXT-1]) {
1150                        desc->more = mmu_alloc_pte_list_desc(vcpu);
1151                        desc = desc->more;
1152                }
1153                for (i = 0; desc->sptes[i]; ++i)
1154                        ++count;
1155                desc->sptes[i] = spte;
1156        }
1157        return count;
1158}
1159
1160static void
1161pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1162                           struct pte_list_desc *desc, int i,
1163                           struct pte_list_desc *prev_desc)
1164{
1165        int j;
1166
1167        for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1168                ;
1169        desc->sptes[i] = desc->sptes[j];
1170        desc->sptes[j] = NULL;
1171        if (j != 0)
1172                return;
1173        if (!prev_desc && !desc->more)
1174                rmap_head->val = (unsigned long)desc->sptes[0];
1175        else
1176                if (prev_desc)
1177                        prev_desc->more = desc->more;
1178                else
1179                        rmap_head->val = (unsigned long)desc->more | 1;
1180        mmu_free_pte_list_desc(desc);
1181}
1182
1183static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1184{
1185        struct pte_list_desc *desc;
1186        struct pte_list_desc *prev_desc;
1187        int i;
1188
1189        if (!rmap_head->val) {
1190                printk(KERN_ERR "pte_list_remove: %p 0->BUG\n", spte);
1191                BUG();
1192        } else if (!(rmap_head->val & 1)) {
1193                rmap_printk("pte_list_remove:  %p 1->0\n", spte);
1194                if ((u64 *)rmap_head->val != spte) {
1195                        printk(KERN_ERR "pte_list_remove:  %p 1->BUG\n", spte);
1196                        BUG();
1197                }
1198                rmap_head->val = 0;
1199        } else {
1200                rmap_printk("pte_list_remove:  %p many->many\n", spte);
1201                desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1202                prev_desc = NULL;
1203                while (desc) {
1204                        for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1205                                if (desc->sptes[i] == spte) {
1206                                        pte_list_desc_remove_entry(rmap_head,
1207                                                        desc, i, prev_desc);
1208                                        return;
1209                                }
1210                        }
1211                        prev_desc = desc;
1212                        desc = desc->more;
1213                }
1214                pr_err("pte_list_remove: %p many->many\n", spte);
1215                BUG();
1216        }
1217}
1218
1219typedef void (*pte_list_walk_fn) (u64 *spte);
1220static void pte_list_walk(struct kvm_rmap_head *rmap_head, pte_list_walk_fn fn)
1221{
1222        struct pte_list_desc *desc;
1223        int i;
1224
1225        if (!rmap_head->val)
1226                return;
1227
1228        if (!(rmap_head->val & 1))
1229                return fn((u64 *)rmap_head->val);
1230
1231        desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1232        while (desc) {
1233                for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i)
1234                        fn(desc->sptes[i]);
1235                desc = desc->more;
1236        }
1237}
1238
1239static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1240                                           struct kvm_memory_slot *slot)
1241{
1242        unsigned long idx;
1243
1244        idx = gfn_to_index(gfn, slot->base_gfn, level);
1245        return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1246}
1247
1248static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1249                                         struct kvm_mmu_page *sp)
1250{
1251        struct kvm_memslots *slots;
1252        struct kvm_memory_slot *slot;
1253
1254        slots = kvm_memslots_for_spte_role(kvm, sp->role);
1255        slot = __gfn_to_memslot(slots, gfn);
1256        return __gfn_to_rmap(gfn, sp->role.level, slot);
1257}
1258
1259static bool rmap_can_add(struct kvm_vcpu *vcpu)
1260{
1261        struct kvm_mmu_memory_cache *cache;
1262
1263        cache = &vcpu->arch.mmu_pte_list_desc_cache;
1264        return mmu_memory_cache_free_objects(cache);
1265}
1266
1267static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1268{
1269        struct kvm_mmu_page *sp;
1270        struct kvm_rmap_head *rmap_head;
1271
1272        sp = page_header(__pa(spte));
1273        kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1274        rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1275        return pte_list_add(vcpu, spte, rmap_head);
1276}
1277
1278static void rmap_remove(struct kvm *kvm, u64 *spte)
1279{
1280        struct kvm_mmu_page *sp;
1281        gfn_t gfn;
1282        struct kvm_rmap_head *rmap_head;
1283
1284        sp = page_header(__pa(spte));
1285        gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1286        rmap_head = gfn_to_rmap(kvm, gfn, sp);
1287        pte_list_remove(spte, rmap_head);
1288}
1289
1290/*
1291 * Used by the following functions to iterate through the sptes linked by a
1292 * rmap.  All fields are private and not assumed to be used outside.
1293 */
1294struct rmap_iterator {
1295        /* private fields */
1296        struct pte_list_desc *desc;     /* holds the sptep if not NULL */
1297        int pos;                        /* index of the sptep */
1298};
1299
1300/*
1301 * Iteration must be started by this function.  This should also be used after
1302 * removing/dropping sptes from the rmap link because in such cases the
1303 * information in the itererator may not be valid.
1304 *
1305 * Returns sptep if found, NULL otherwise.
1306 */
1307static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1308                           struct rmap_iterator *iter)
1309{
1310        u64 *sptep;
1311
1312        if (!rmap_head->val)
1313                return NULL;
1314
1315        if (!(rmap_head->val & 1)) {
1316                iter->desc = NULL;
1317                sptep = (u64 *)rmap_head->val;
1318                goto out;
1319        }
1320
1321        iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1322        iter->pos = 0;
1323        sptep = iter->desc->sptes[iter->pos];
1324out:
1325        BUG_ON(!is_shadow_present_pte(*sptep));
1326        return sptep;
1327}
1328
1329/*
1330 * Must be used with a valid iterator: e.g. after rmap_get_first().
1331 *
1332 * Returns sptep if found, NULL otherwise.
1333 */
1334static u64 *rmap_get_next(struct rmap_iterator *iter)
1335{
1336        u64 *sptep;
1337
1338        if (iter->desc) {
1339                if (iter->pos < PTE_LIST_EXT - 1) {
1340                        ++iter->pos;
1341                        sptep = iter->desc->sptes[iter->pos];
1342                        if (sptep)
1343                                goto out;
1344                }
1345
1346                iter->desc = iter->desc->more;
1347
1348                if (iter->desc) {
1349                        iter->pos = 0;
1350                        /* desc->sptes[0] cannot be NULL */
1351                        sptep = iter->desc->sptes[iter->pos];
1352                        goto out;
1353                }
1354        }
1355
1356        return NULL;
1357out:
1358        BUG_ON(!is_shadow_present_pte(*sptep));
1359        return sptep;
1360}
1361
1362#define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)                 \
1363        for (_spte_ = rmap_get_first(_rmap_head_, _iter_);              \
1364             _spte_; _spte_ = rmap_get_next(_iter_))
1365
1366static void drop_spte(struct kvm *kvm, u64 *sptep)
1367{
1368        if (mmu_spte_clear_track_bits(sptep))
1369                rmap_remove(kvm, sptep);
1370}
1371
1372
1373static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1374{
1375        if (is_large_pte(*sptep)) {
1376                WARN_ON(page_header(__pa(sptep))->role.level ==
1377                        PT_PAGE_TABLE_LEVEL);
1378                drop_spte(kvm, sptep);
1379                --kvm->stat.lpages;
1380                return true;
1381        }
1382
1383        return false;
1384}
1385
1386static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1387{
1388        if (__drop_large_spte(vcpu->kvm, sptep))
1389                kvm_flush_remote_tlbs(vcpu->kvm);
1390}
1391
1392/*
1393 * Write-protect on the specified @sptep, @pt_protect indicates whether
1394 * spte write-protection is caused by protecting shadow page table.
1395 *
1396 * Note: write protection is difference between dirty logging and spte
1397 * protection:
1398 * - for dirty logging, the spte can be set to writable at anytime if
1399 *   its dirty bitmap is properly set.
1400 * - for spte protection, the spte can be writable only after unsync-ing
1401 *   shadow page.
1402 *
1403 * Return true if tlb need be flushed.
1404 */
1405static bool spte_write_protect(u64 *sptep, bool pt_protect)
1406{
1407        u64 spte = *sptep;
1408
1409        if (!is_writable_pte(spte) &&
1410              !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1411                return false;
1412
1413        rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1414
1415        if (pt_protect)
1416                spte &= ~SPTE_MMU_WRITEABLE;
1417        spte = spte & ~PT_WRITABLE_MASK;
1418
1419        return mmu_spte_update(sptep, spte);
1420}
1421
1422static bool __rmap_write_protect(struct kvm *kvm,
1423                                 struct kvm_rmap_head *rmap_head,
1424                                 bool pt_protect)
1425{
1426        u64 *sptep;
1427        struct rmap_iterator iter;
1428        bool flush = false;
1429
1430        for_each_rmap_spte(rmap_head, &iter, sptep)
1431                flush |= spte_write_protect(sptep, pt_protect);
1432
1433        return flush;
1434}
1435
1436static bool spte_clear_dirty(u64 *sptep)
1437{
1438        u64 spte = *sptep;
1439
1440        rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1441
1442        spte &= ~shadow_dirty_mask;
1443
1444        return mmu_spte_update(sptep, spte);
1445}
1446
1447static bool wrprot_ad_disabled_spte(u64 *sptep)
1448{
1449        bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1450                                               (unsigned long *)sptep);
1451        if (was_writable)
1452                kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1453
1454        return was_writable;
1455}
1456
1457/*
1458 * Gets the GFN ready for another round of dirty logging by clearing the
1459 *      - D bit on ad-enabled SPTEs, and
1460 *      - W bit on ad-disabled SPTEs.
1461 * Returns true iff any D or W bits were cleared.
1462 */
1463static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1464{
1465        u64 *sptep;
1466        struct rmap_iterator iter;
1467        bool flush = false;
1468
1469        for_each_rmap_spte(rmap_head, &iter, sptep)
1470                if (spte_ad_enabled(*sptep))
1471                        flush |= spte_clear_dirty(sptep);
1472                else
1473                        flush |= wrprot_ad_disabled_spte(sptep);
1474
1475        return flush;
1476}
1477
1478static bool spte_set_dirty(u64 *sptep)
1479{
1480        u64 spte = *sptep;
1481
1482        rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1483
1484        spte |= shadow_dirty_mask;
1485
1486        return mmu_spte_update(sptep, spte);
1487}
1488
1489static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1490{
1491        u64 *sptep;
1492        struct rmap_iterator iter;
1493        bool flush = false;
1494
1495        for_each_rmap_spte(rmap_head, &iter, sptep)
1496                if (spte_ad_enabled(*sptep))
1497                        flush |= spte_set_dirty(sptep);
1498
1499        return flush;
1500}
1501
1502/**
1503 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1504 * @kvm: kvm instance
1505 * @slot: slot to protect
1506 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1507 * @mask: indicates which pages we should protect
1508 *
1509 * Used when we do not need to care about huge page mappings: e.g. during dirty
1510 * logging we do not have any such mappings.
1511 */
1512static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1513                                     struct kvm_memory_slot *slot,
1514                                     gfn_t gfn_offset, unsigned long mask)
1515{
1516        struct kvm_rmap_head *rmap_head;
1517
1518        while (mask) {
1519                rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1520                                          PT_PAGE_TABLE_LEVEL, slot);
1521                __rmap_write_protect(kvm, rmap_head, false);
1522
1523                /* clear the first set bit */
1524                mask &= mask - 1;
1525        }
1526}
1527
1528/**
1529 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1530 * protect the page if the D-bit isn't supported.
1531 * @kvm: kvm instance
1532 * @slot: slot to clear D-bit
1533 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1534 * @mask: indicates which pages we should clear D-bit
1535 *
1536 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1537 */
1538void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1539                                     struct kvm_memory_slot *slot,
1540                                     gfn_t gfn_offset, unsigned long mask)
1541{
1542        struct kvm_rmap_head *rmap_head;
1543
1544        while (mask) {
1545                rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1546                                          PT_PAGE_TABLE_LEVEL, slot);
1547                __rmap_clear_dirty(kvm, rmap_head);
1548
1549                /* clear the first set bit */
1550                mask &= mask - 1;
1551        }
1552}
1553EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1554
1555/**
1556 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1557 * PT level pages.
1558 *
1559 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1560 * enable dirty logging for them.
1561 *
1562 * Used when we do not need to care about huge page mappings: e.g. during dirty
1563 * logging we do not have any such mappings.
1564 */
1565void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1566                                struct kvm_memory_slot *slot,
1567                                gfn_t gfn_offset, unsigned long mask)
1568{
1569        if (kvm_x86_ops->enable_log_dirty_pt_masked)
1570                kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1571                                mask);
1572        else
1573                kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1574}
1575
1576/**
1577 * kvm_arch_write_log_dirty - emulate dirty page logging
1578 * @vcpu: Guest mode vcpu
1579 *
1580 * Emulate arch specific page modification logging for the
1581 * nested hypervisor
1582 */
1583int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu)
1584{
1585        if (kvm_x86_ops->write_log_dirty)
1586                return kvm_x86_ops->write_log_dirty(vcpu);
1587
1588        return 0;
1589}
1590
1591bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1592                                    struct kvm_memory_slot *slot, u64 gfn)
1593{
1594        struct kvm_rmap_head *rmap_head;
1595        int i;
1596        bool write_protected = false;
1597
1598        for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1599                rmap_head = __gfn_to_rmap(gfn, i, slot);
1600                write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1601        }
1602
1603        return write_protected;
1604}
1605
1606static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1607{
1608        struct kvm_memory_slot *slot;
1609
1610        slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1611        return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1612}
1613
1614static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1615{
1616        u64 *sptep;
1617        struct rmap_iterator iter;
1618        bool flush = false;
1619
1620        while ((sptep = rmap_get_first(rmap_head, &iter))) {
1621                rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1622
1623                drop_spte(kvm, sptep);
1624                flush = true;
1625        }
1626
1627        return flush;
1628}
1629
1630static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1631                           struct kvm_memory_slot *slot, gfn_t gfn, int level,
1632                           unsigned long data)
1633{
1634        return kvm_zap_rmapp(kvm, rmap_head);
1635}
1636
1637static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1638                             struct kvm_memory_slot *slot, gfn_t gfn, int level,
1639                             unsigned long data)
1640{
1641        u64 *sptep;
1642        struct rmap_iterator iter;
1643        int need_flush = 0;
1644        u64 new_spte;
1645        pte_t *ptep = (pte_t *)data;
1646        kvm_pfn_t new_pfn;
1647
1648        WARN_ON(pte_huge(*ptep));
1649        new_pfn = pte_pfn(*ptep);
1650
1651restart:
1652        for_each_rmap_spte(rmap_head, &iter, sptep) {
1653                rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1654                            sptep, *sptep, gfn, level);
1655
1656                need_flush = 1;
1657
1658                if (pte_write(*ptep)) {
1659                        drop_spte(kvm, sptep);
1660                        goto restart;
1661                } else {
1662                        new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1663                        new_spte |= (u64)new_pfn << PAGE_SHIFT;
1664
1665                        new_spte &= ~PT_WRITABLE_MASK;
1666                        new_spte &= ~SPTE_HOST_WRITEABLE;
1667
1668                        new_spte = mark_spte_for_access_track(new_spte);
1669
1670                        mmu_spte_clear_track_bits(sptep);
1671                        mmu_spte_set(sptep, new_spte);
1672                }
1673        }
1674
1675        if (need_flush)
1676                kvm_flush_remote_tlbs(kvm);
1677
1678        return 0;
1679}
1680
1681struct slot_rmap_walk_iterator {
1682        /* input fields. */
1683        struct kvm_memory_slot *slot;
1684        gfn_t start_gfn;
1685        gfn_t end_gfn;
1686        int start_level;
1687        int end_level;
1688
1689        /* output fields. */
1690        gfn_t gfn;
1691        struct kvm_rmap_head *rmap;
1692        int level;
1693
1694        /* private field. */
1695        struct kvm_rmap_head *end_rmap;
1696};
1697
1698static void
1699rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1700{
1701        iterator->level = level;
1702        iterator->gfn = iterator->start_gfn;
1703        iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1704        iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1705                                           iterator->slot);
1706}
1707
1708static void
1709slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1710                    struct kvm_memory_slot *slot, int start_level,
1711                    int end_level, gfn_t start_gfn, gfn_t end_gfn)
1712{
1713        iterator->slot = slot;
1714        iterator->start_level = start_level;
1715        iterator->end_level = end_level;
1716        iterator->start_gfn = start_gfn;
1717        iterator->end_gfn = end_gfn;
1718
1719        rmap_walk_init_level(iterator, iterator->start_level);
1720}
1721
1722static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1723{
1724        return !!iterator->rmap;
1725}
1726
1727static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1728{
1729        if (++iterator->rmap <= iterator->end_rmap) {
1730                iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1731                return;
1732        }
1733
1734        if (++iterator->level > iterator->end_level) {
1735                iterator->rmap = NULL;
1736                return;
1737        }
1738
1739        rmap_walk_init_level(iterator, iterator->level);
1740}
1741
1742#define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,    \
1743           _start_gfn, _end_gfn, _iter_)                                \
1744        for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,         \
1745                                 _end_level_, _start_gfn, _end_gfn);    \
1746             slot_rmap_walk_okay(_iter_);                               \
1747             slot_rmap_walk_next(_iter_))
1748
1749static int kvm_handle_hva_range(struct kvm *kvm,
1750                                unsigned long start,
1751                                unsigned long end,
1752                                unsigned long data,
1753                                int (*handler)(struct kvm *kvm,
1754                                               struct kvm_rmap_head *rmap_head,
1755                                               struct kvm_memory_slot *slot,
1756                                               gfn_t gfn,
1757                                               int level,
1758                                               unsigned long data))
1759{
1760        struct kvm_memslots *slots;
1761        struct kvm_memory_slot *memslot;
1762        struct slot_rmap_walk_iterator iterator;
1763        int ret = 0;
1764        int i;
1765
1766        for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1767                slots = __kvm_memslots(kvm, i);
1768                kvm_for_each_memslot(memslot, slots) {
1769                        unsigned long hva_start, hva_end;
1770                        gfn_t gfn_start, gfn_end;
1771
1772                        hva_start = max(start, memslot->userspace_addr);
1773                        hva_end = min(end, memslot->userspace_addr +
1774                                      (memslot->npages << PAGE_SHIFT));
1775                        if (hva_start >= hva_end)
1776                                continue;
1777                        /*
1778                         * {gfn(page) | page intersects with [hva_start, hva_end)} =
1779                         * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1780                         */
1781                        gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1782                        gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1783
1784                        for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1785                                                 PT_MAX_HUGEPAGE_LEVEL,
1786                                                 gfn_start, gfn_end - 1,
1787                                                 &iterator)
1788                                ret |= handler(kvm, iterator.rmap, memslot,
1789                                               iterator.gfn, iterator.level, data);
1790                }
1791        }
1792
1793        return ret;
1794}
1795
1796static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1797                          unsigned long data,
1798                          int (*handler)(struct kvm *kvm,
1799                                         struct kvm_rmap_head *rmap_head,
1800                                         struct kvm_memory_slot *slot,
1801                                         gfn_t gfn, int level,
1802                                         unsigned long data))
1803{
1804        return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1805}
1806
1807int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
1808{
1809        return kvm_handle_hva(kvm, hva, 0, kvm_unmap_rmapp);
1810}
1811
1812int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
1813{
1814        return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1815}
1816
1817void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1818{
1819        kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1820}
1821
1822static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1823                         struct kvm_memory_slot *slot, gfn_t gfn, int level,
1824                         unsigned long data)
1825{
1826        u64 *sptep;
1827        struct rmap_iterator uninitialized_var(iter);
1828        int young = 0;
1829
1830        for_each_rmap_spte(rmap_head, &iter, sptep)
1831                young |= mmu_spte_age(sptep);
1832
1833        trace_kvm_age_page(gfn, level, slot, young);
1834        return young;
1835}
1836
1837static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1838                              struct kvm_memory_slot *slot, gfn_t gfn,
1839                              int level, unsigned long data)
1840{
1841        u64 *sptep;
1842        struct rmap_iterator iter;
1843
1844        for_each_rmap_spte(rmap_head, &iter, sptep)
1845                if (is_accessed_spte(*sptep))
1846                        return 1;
1847        return 0;
1848}
1849
1850#define RMAP_RECYCLE_THRESHOLD 1000
1851
1852static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1853{
1854        struct kvm_rmap_head *rmap_head;
1855        struct kvm_mmu_page *sp;
1856
1857        sp = page_header(__pa(spte));
1858
1859        rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1860
1861        kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
1862        kvm_flush_remote_tlbs(vcpu->kvm);
1863}
1864
1865int kvm_age_hva(struct kvm *kvm, unsigned long hva)
1866{
1867        return kvm_handle_hva_range(kvm, hva, hva + PAGE_SIZE, 0, kvm_age_rmapp);
1868}
1869
1870int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1871{
1872        return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
1873}
1874
1875#ifdef MMU_DEBUG
1876static int is_empty_shadow_page(u64 *spt)
1877{
1878        u64 *pos;
1879        u64 *end;
1880
1881        for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1882                if (is_shadow_present_pte(*pos)) {
1883                        printk(KERN_ERR "%s: %p %llx\n", __func__,
1884                               pos, *pos);
1885                        return 0;
1886                }
1887        return 1;
1888}
1889#endif
1890
1891/*
1892 * This value is the sum of all of the kvm instances's
1893 * kvm->arch.n_used_mmu_pages values.  We need a global,
1894 * aggregate version in order to make the slab shrinker
1895 * faster
1896 */
1897static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, int nr)
1898{
1899        kvm->arch.n_used_mmu_pages += nr;
1900        percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1901}
1902
1903static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
1904{
1905        MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
1906        hlist_del(&sp->hash_link);
1907        list_del(&sp->link);
1908        free_page((unsigned long)sp->spt);
1909        if (!sp->role.direct)
1910                free_page((unsigned long)sp->gfns);
1911        kmem_cache_free(mmu_page_header_cache, sp);
1912}
1913
1914static unsigned kvm_page_table_hashfn(gfn_t gfn)
1915{
1916        return gfn & ((1 << KVM_MMU_HASH_SHIFT) - 1);
1917}
1918
1919static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
1920                                    struct kvm_mmu_page *sp, u64 *parent_pte)
1921{
1922        if (!parent_pte)
1923                return;
1924
1925        pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
1926}
1927
1928static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1929                                       u64 *parent_pte)
1930{
1931        pte_list_remove(parent_pte, &sp->parent_ptes);
1932}
1933
1934static void drop_parent_pte(struct kvm_mmu_page *sp,
1935                            u64 *parent_pte)
1936{
1937        mmu_page_remove_parent_pte(sp, parent_pte);
1938        mmu_spte_clear_no_track(parent_pte);
1939}
1940
1941static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu,
1942                                               u64 *parent_pte, int direct)
1943{
1944        struct kvm_mmu_page *sp;
1945
1946        sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
1947        sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
1948        if (!direct)
1949                sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
1950        set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
1951
1952        /*
1953         * The active_mmu_pages list is the FIFO list, do not move the
1954         * page until it is zapped. kvm_zap_obsolete_pages depends on
1955         * this feature. See the comments in kvm_zap_obsolete_pages().
1956         */
1957        list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
1958        sp->parent_ptes.val = 0;
1959        mmu_page_add_parent_pte(vcpu, sp, parent_pte);
1960        kvm_mod_used_mmu_pages(vcpu->kvm, +1);
1961        return sp;
1962}
1963
1964static void mark_unsync(u64 *spte);
1965static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1966{
1967        pte_list_walk(&sp->parent_ptes, mark_unsync);
1968}
1969
1970static void mark_unsync(u64 *spte)
1971{
1972        struct kvm_mmu_page *sp;
1973        unsigned int index;
1974
1975        sp = page_header(__pa(spte));
1976        index = spte - sp->spt;
1977        if (__test_and_set_bit(index, sp->unsync_child_bitmap))
1978                return;
1979        if (sp->unsync_children++)
1980                return;
1981        kvm_mmu_mark_parents_unsync(sp);
1982}
1983
1984static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
1985                               struct kvm_mmu_page *sp)
1986{
1987        return 1;
1988}
1989
1990static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
1991{
1992}
1993
1994static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
1995                                 struct kvm_mmu_page *sp, u64 *spte,
1996                                 const void *pte)
1997{
1998        WARN_ON(1);
1999}
2000
2001#define KVM_PAGE_ARRAY_NR 16
2002
2003struct kvm_mmu_pages {
2004        struct mmu_page_and_offset {
2005                struct kvm_mmu_page *sp;
2006                unsigned int idx;
2007        } page[KVM_PAGE_ARRAY_NR];
2008        unsigned int nr;
2009};
2010
2011static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2012                         int idx)
2013{
2014        int i;
2015
2016        if (sp->unsync)
2017                for (i=0; i < pvec->nr; i++)
2018                        if (pvec->page[i].sp == sp)
2019                                return 0;
2020
2021        pvec->page[pvec->nr].sp = sp;
2022        pvec->page[pvec->nr].idx = idx;
2023        pvec->nr++;
2024        return (pvec->nr == KVM_PAGE_ARRAY_NR);
2025}
2026
2027static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2028                           struct kvm_mmu_pages *pvec)
2029{
2030        int i, ret, nr_unsync_leaf = 0;
2031
2032        for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2033                struct kvm_mmu_page *child;
2034                u64 ent = sp->spt[i];
2035
2036                if (!is_shadow_present_pte(ent) || is_large_pte(ent))
2037                        goto clear_child_bitmap;
2038
2039                child = page_header(ent & PT64_BASE_ADDR_MASK);
2040
2041                if (child->unsync_children) {
2042                        if (mmu_pages_add(pvec, child, i))
2043                                return -ENOSPC;
2044
2045                        ret = __mmu_unsync_walk(child, pvec);
2046                        if (!ret)
2047                                goto clear_child_bitmap;
2048                        else if (ret > 0)
2049                                nr_unsync_leaf += ret;
2050                        else
2051                                return ret;
2052                } else if (child->unsync) {
2053                        nr_unsync_leaf++;
2054                        if (mmu_pages_add(pvec, child, i))
2055                                return -ENOSPC;
2056                } else
2057                         goto clear_child_bitmap;
2058
2059                continue;
2060
2061clear_child_bitmap:
2062                __clear_bit(i, sp->unsync_child_bitmap);
2063                sp->unsync_children--;
2064                WARN_ON((int)sp->unsync_children < 0);
2065        }
2066
2067
2068        return nr_unsync_leaf;
2069}
2070
2071static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2072                           struct kvm_mmu_pages *pvec)
2073{
2074        if (!sp->unsync_children)
2075                return 0;
2076
2077        mmu_pages_add(pvec, sp, 0);
2078        return __mmu_unsync_walk(sp, pvec);
2079}
2080
2081static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2082{
2083        WARN_ON(!sp->unsync);
2084        trace_kvm_mmu_sync_page(sp);
2085        sp->unsync = 0;
2086        --kvm->stat.mmu_unsync;
2087}
2088
2089static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2090                                    struct list_head *invalid_list);
2091static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2092                                    struct list_head *invalid_list);
2093
2094/*
2095 * NOTE: we should pay more attention on the zapped-obsolete page
2096 * (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk
2097 * since it has been deleted from active_mmu_pages but still can be found
2098 * at hast list.
2099 *
2100 * for_each_gfn_indirect_valid_sp has skipped that kind of page and
2101 * kvm_mmu_get_page(), the only user of for_each_gfn_sp(), has skipped
2102 * all the obsolete pages.
2103 */
2104#define for_each_gfn_sp(_kvm, _sp, _gfn)                                \
2105        hlist_for_each_entry(_sp,                                       \
2106          &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2107                if ((_sp)->gfn != (_gfn)) {} else
2108
2109#define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn)                 \
2110        for_each_gfn_sp(_kvm, _sp, _gfn)                                \
2111                if ((_sp)->role.direct || (_sp)->role.invalid) {} else
2112
2113/* @sp->gfn should be write-protected at the call site */
2114static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2115                           struct list_head *invalid_list, bool clear_unsync)
2116{
2117        if (sp->role.cr4_pae != !!is_pae(vcpu)) {
2118                kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2119                return 1;
2120        }
2121
2122        if (clear_unsync)
2123                kvm_unlink_unsync_page(vcpu->kvm, sp);
2124
2125        if (vcpu->arch.mmu.sync_page(vcpu, sp)) {
2126                kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2127                return 1;
2128        }
2129
2130        kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2131        return 0;
2132}
2133
2134static int kvm_sync_page_transient(struct kvm_vcpu *vcpu,
2135                                   struct kvm_mmu_page *sp)
2136{
2137        LIST_HEAD(invalid_list);
2138        int ret;
2139
2140        ret = __kvm_sync_page(vcpu, sp, &invalid_list, false);
2141        if (ret)
2142                kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
2143
2144        return ret;
2145}
2146
2147#ifdef CONFIG_KVM_MMU_AUDIT
2148#include "mmu_audit.c"
2149#else
2150static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2151static void mmu_audit_disable(void) { }
2152#endif
2153
2154static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2155                         struct list_head *invalid_list)
2156{
2157        return __kvm_sync_page(vcpu, sp, invalid_list, true);
2158}
2159
2160/* @gfn should be write-protected at the call site */
2161static void kvm_sync_pages(struct kvm_vcpu *vcpu,  gfn_t gfn)
2162{
2163        struct kvm_mmu_page *s;
2164        LIST_HEAD(invalid_list);
2165        bool flush = false;
2166
2167        for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2168                if (!s->unsync)
2169                        continue;
2170
2171                WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2172                kvm_unlink_unsync_page(vcpu->kvm, s);
2173                if ((s->role.cr4_pae != !!is_pae(vcpu)) ||
2174                        (vcpu->arch.mmu.sync_page(vcpu, s))) {
2175                        kvm_mmu_prepare_zap_page(vcpu->kvm, s, &invalid_list);
2176                        continue;
2177                }
2178                flush = true;
2179        }
2180
2181        kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
2182        if (flush)
2183                kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2184}
2185
2186struct mmu_page_path {
2187        struct kvm_mmu_page *parent[PT64_ROOT_LEVEL-1];
2188        unsigned int idx[PT64_ROOT_LEVEL-1];
2189};
2190
2191#define for_each_sp(pvec, sp, parents, i)                       \
2192                for (i = mmu_pages_next(&pvec, &parents, -1),   \
2193                        sp = pvec.page[i].sp;                   \
2194                        i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});   \
2195                        i = mmu_pages_next(&pvec, &parents, i))
2196
2197static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2198                          struct mmu_page_path *parents,
2199                          int i)
2200{
2201        int n;
2202
2203        for (n = i+1; n < pvec->nr; n++) {
2204                struct kvm_mmu_page *sp = pvec->page[n].sp;
2205
2206                if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
2207                        parents->idx[0] = pvec->page[n].idx;
2208                        return n;
2209                }
2210
2211                parents->parent[sp->role.level-2] = sp;
2212                parents->idx[sp->role.level-1] = pvec->page[n].idx;
2213        }
2214
2215        return n;
2216}
2217
2218static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2219{
2220        struct kvm_mmu_page *sp;
2221        unsigned int level = 0;
2222
2223        do {
2224                unsigned int idx = parents->idx[level];
2225
2226                sp = parents->parent[level];
2227                if (!sp)
2228                        return;
2229
2230                --sp->unsync_children;
2231                WARN_ON((int)sp->unsync_children < 0);
2232                __clear_bit(idx, sp->unsync_child_bitmap);
2233                level++;
2234        } while (level < PT64_ROOT_LEVEL-1 && !sp->unsync_children);
2235}
2236
2237static void kvm_mmu_pages_init(struct kvm_mmu_page *parent,
2238                               struct mmu_page_path *parents,
2239                               struct kvm_mmu_pages *pvec)
2240{
2241        parents->parent[parent->role.level-1] = NULL;
2242        pvec->nr = 0;
2243}
2244
2245static void mmu_sync_children(struct kvm_vcpu *vcpu,
2246                              struct kvm_mmu_page *parent)
2247{
2248        int i;
2249        struct kvm_mmu_page *sp;
2250        struct mmu_page_path parents;
2251        struct kvm_mmu_pages pages;
2252        LIST_HEAD(invalid_list);
2253
2254        kvm_mmu_pages_init(parent, &parents, &pages);
2255        while (mmu_unsync_walk(parent, &pages)) {
2256                bool protected = false;
2257
2258                for_each_sp(pages, sp, parents, i)
2259                        protected |= rmap_write_protect(vcpu, sp->gfn);
2260
2261                if (protected)
2262                        kvm_flush_remote_tlbs(vcpu->kvm);
2263
2264                for_each_sp(pages, sp, parents, i) {
2265                        kvm_sync_page(vcpu, sp, &invalid_list);
2266                        mmu_pages_clear_parents(&parents);
2267                }
2268                kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
2269                cond_resched_lock(&vcpu->kvm->mmu_lock);
2270                kvm_mmu_pages_init(parent, &parents, &pages);
2271        }
2272}
2273
2274static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2275{
2276        atomic_set(&sp->write_flooding_count,  0);
2277}
2278
2279static void clear_sp_write_flooding_count(u64 *spte)
2280{
2281        struct kvm_mmu_page *sp =  page_header(__pa(spte));
2282
2283        __clear_sp_write_flooding_count(sp);
2284}
2285
2286static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2287{
2288        return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2289}
2290
2291static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2292                                             gfn_t gfn,
2293                                             gva_t gaddr,
2294                                             unsigned level,
2295                                             int direct,
2296                                             unsigned access,
2297                                             u64 *parent_pte)
2298{
2299        union kvm_mmu_page_role role;
2300        unsigned quadrant;
2301        struct kvm_mmu_page *sp;
2302        bool need_sync = false;
2303
2304        role = vcpu->arch.mmu.base_role;
2305        role.level = level;
2306        role.direct = direct;
2307        if (role.direct)
2308                role.cr4_pae = 0;
2309        role.access = access;
2310        if (!vcpu->arch.mmu.direct_map
2311            && vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
2312                quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2313                quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2314                role.quadrant = quadrant;
2315        }
2316        for_each_gfn_sp(vcpu->kvm, sp, gfn) {
2317                if (is_obsolete_sp(vcpu->kvm, sp))
2318                        continue;
2319
2320                if (!need_sync && sp->unsync)
2321                        need_sync = true;
2322
2323                if (sp->role.word != role.word)
2324                        continue;
2325
2326                if (sp->unsync && kvm_sync_page_transient(vcpu, sp))
2327                        break;
2328
2329                mmu_page_add_parent_pte(vcpu, sp, parent_pte);
2330                if (sp->unsync_children) {
2331                        kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2332                        kvm_mmu_mark_parents_unsync(sp);
2333                } else if (sp->unsync)
2334                        kvm_mmu_mark_parents_unsync(sp);
2335
2336                __clear_sp_write_flooding_count(sp);
2337                trace_kvm_mmu_get_page(sp, false);
2338                return sp;
2339        }
2340        ++vcpu->kvm->stat.mmu_cache_miss;
2341        sp = kvm_mmu_alloc_page(vcpu, parent_pte, direct);
2342        if (!sp)
2343                return sp;
2344        sp->gfn = gfn;
2345        sp->role = role;
2346        hlist_add_head(&sp->hash_link,
2347                &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2348        if (!direct) {
2349                /*
2350                 * we should do write protection before syncing pages
2351                 * otherwise the content of the synced shadow page may
2352                 * be inconsistent with guest page table.
2353                 */
2354                account_shadowed(vcpu->kvm, sp);
2355                if (level == PT_PAGE_TABLE_LEVEL &&
2356                      rmap_write_protect(vcpu, gfn))
2357                        kvm_flush_remote_tlbs(vcpu->kvm);
2358
2359                if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2360                        kvm_sync_pages(vcpu, gfn);
2361        }
2362        sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2363        clear_page(sp->spt);
2364        trace_kvm_mmu_get_page(sp, true);
2365        return sp;
2366}
2367
2368static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2369                             struct kvm_vcpu *vcpu, u64 addr)
2370{
2371        iterator->addr = addr;
2372        iterator->shadow_addr = vcpu->arch.mmu.root_hpa;
2373        iterator->level = vcpu->arch.mmu.shadow_root_level;
2374
2375        if (iterator->level == PT64_ROOT_LEVEL &&
2376            vcpu->arch.mmu.root_level < PT64_ROOT_LEVEL &&
2377            !vcpu->arch.mmu.direct_map)
2378                --iterator->level;
2379
2380        if (iterator->level == PT32E_ROOT_LEVEL) {
2381                iterator->shadow_addr
2382                        = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
2383                iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2384                --iterator->level;
2385                if (!iterator->shadow_addr)
2386                        iterator->level = 0;
2387        }
2388}
2389
2390static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2391{
2392        if (iterator->level < PT_PAGE_TABLE_LEVEL)
2393                return false;
2394
2395        iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2396        iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2397        return true;
2398}
2399
2400static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2401                               u64 spte)
2402{
2403        if (is_last_spte(spte, iterator->level)) {
2404                iterator->level = 0;
2405                return;
2406        }
2407
2408        iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2409        --iterator->level;
2410}
2411
2412static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2413{
2414        return __shadow_walk_next(iterator, *iterator->sptep);
2415}
2416
2417static void link_shadow_page(u64 *sptep, struct kvm_mmu_page *sp)
2418{
2419        u64 spte;
2420
2421        BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2422
2423        spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2424               shadow_user_mask | shadow_x_mask | shadow_me_mask;
2425
2426        if (sp_ad_disabled(sp))
2427                spte |= shadow_acc_track_value;
2428        else
2429                spte |= shadow_accessed_mask;
2430
2431        mmu_spte_set(sptep, spte);
2432}
2433
2434static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2435                                   unsigned direct_access)
2436{
2437        if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2438                struct kvm_mmu_page *child;
2439
2440                /*
2441                 * For the direct sp, if the guest pte's dirty bit
2442                 * changed form clean to dirty, it will corrupt the
2443                 * sp's access: allow writable in the read-only sp,
2444                 * so we should update the spte at this point to get
2445                 * a new sp with the correct access.
2446                 */
2447                child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2448                if (child->role.access == direct_access)
2449                        return;
2450
2451                drop_parent_pte(child, sptep);
2452                kvm_flush_remote_tlbs(vcpu->kvm);
2453        }
2454}
2455
2456static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2457                             u64 *spte)
2458{
2459        u64 pte;
2460        struct kvm_mmu_page *child;
2461
2462        pte = *spte;
2463        if (is_shadow_present_pte(pte)) {
2464                if (is_last_spte(pte, sp->role.level)) {
2465                        drop_spte(kvm, spte);
2466                        if (is_large_pte(pte))
2467                                --kvm->stat.lpages;
2468                } else {
2469                        child = page_header(pte & PT64_BASE_ADDR_MASK);
2470                        drop_parent_pte(child, spte);
2471                }
2472                return true;
2473        }
2474
2475        if (is_mmio_spte(pte))
2476                mmu_spte_clear_no_track(spte);
2477
2478        return false;
2479}
2480
2481static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2482                                         struct kvm_mmu_page *sp)
2483{
2484        unsigned i;
2485
2486        for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2487                mmu_page_zap_pte(kvm, sp, sp->spt + i);
2488}
2489
2490static void kvm_mmu_put_page(struct kvm_mmu_page *sp, u64 *parent_pte)
2491{
2492        mmu_page_remove_parent_pte(sp, parent_pte);
2493}
2494
2495static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2496{
2497        u64 *sptep;
2498        struct rmap_iterator iter;
2499
2500        while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2501                drop_parent_pte(sp, sptep);
2502}
2503
2504static int mmu_zap_unsync_children(struct kvm *kvm,
2505                                   struct kvm_mmu_page *parent,
2506                                   struct list_head *invalid_list)
2507{
2508        int i, zapped = 0;
2509        struct mmu_page_path parents;
2510        struct kvm_mmu_pages pages;
2511
2512        if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2513                return 0;
2514
2515        kvm_mmu_pages_init(parent, &parents, &pages);
2516        while (mmu_unsync_walk(parent, &pages)) {
2517                struct kvm_mmu_page *sp;
2518
2519                for_each_sp(pages, sp, parents, i) {
2520                        kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2521                        mmu_pages_clear_parents(&parents);
2522                        zapped++;
2523                }
2524                kvm_mmu_pages_init(parent, &parents, &pages);
2525        }
2526
2527        return zapped;
2528}
2529
2530static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2531                                    struct list_head *invalid_list)
2532{
2533        int ret;
2534
2535        trace_kvm_mmu_prepare_zap_page(sp);
2536        ++kvm->stat.mmu_shadow_zapped;
2537        ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
2538        kvm_mmu_page_unlink_children(kvm, sp);
2539        kvm_mmu_unlink_parents(kvm, sp);
2540
2541        if (!sp->role.invalid && !sp->role.direct)
2542                unaccount_shadowed(kvm, sp);
2543
2544        if (sp->unsync)
2545                kvm_unlink_unsync_page(kvm, sp);
2546        if (!sp->root_count) {
2547                /* Count self */
2548                ret++;
2549                list_move(&sp->link, invalid_list);
2550                kvm_mod_used_mmu_pages(kvm, -1);
2551        } else {
2552                list_move(&sp->link, &kvm->arch.active_mmu_pages);
2553
2554                /*
2555                 * The obsolete pages can not be used on any vcpus.
2556                 * See the comments in kvm_mmu_invalidate_zap_all_pages().
2557                 */
2558                if (!sp->role.invalid && !is_obsolete_sp(kvm, sp))
2559                        kvm_reload_remote_mmus(kvm);
2560        }
2561
2562        sp->role.invalid = 1;
2563        return ret;
2564}
2565
2566static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2567                                    struct list_head *invalid_list)
2568{
2569        struct kvm_mmu_page *sp, *nsp;
2570
2571        if (list_empty(invalid_list))
2572                return;
2573
2574        /*
2575         * wmb: make sure everyone sees our modifications to the page tables
2576         * rmb: make sure we see changes to vcpu->mode
2577         */
2578        smp_mb();
2579
2580        /*
2581         * Wait for all vcpus to exit guest mode and/or lockless shadow
2582         * page table walks.
2583         */
2584        kvm_flush_remote_tlbs(kvm);
2585
2586        list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2587                WARN_ON(!sp->role.invalid || sp->root_count);
2588                kvm_mmu_free_page(sp);
2589        }
2590}
2591
2592static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2593                                        struct list_head *invalid_list)
2594{
2595        struct kvm_mmu_page *sp;
2596
2597        if (list_empty(&kvm->arch.active_mmu_pages))
2598                return false;
2599
2600        sp = list_last_entry(&kvm->arch.active_mmu_pages,
2601                             struct kvm_mmu_page, link);
2602        return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2603}
2604
2605/*
2606 * Changing the number of mmu pages allocated to the vm
2607 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2608 */
2609void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int goal_nr_mmu_pages)
2610{
2611        LIST_HEAD(invalid_list);
2612
2613        spin_lock(&kvm->mmu_lock);
2614
2615        if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2616                /* Need to free some mmu pages to achieve the goal. */
2617                while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2618                        if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2619                                break;
2620
2621                kvm_mmu_commit_zap_page(kvm, &invalid_list);
2622                goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2623        }
2624
2625        kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2626
2627        spin_unlock(&kvm->mmu_lock);
2628}
2629
2630int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2631{
2632        struct kvm_mmu_page *sp;
2633        LIST_HEAD(invalid_list);
2634        int r;
2635
2636        pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2637        r = 0;
2638        spin_lock(&kvm->mmu_lock);
2639        for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2640                pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2641                         sp->role.word);
2642                r = 1;
2643                kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2644        }
2645        kvm_mmu_commit_zap_page(kvm, &invalid_list);
2646        spin_unlock(&kvm->mmu_lock);
2647
2648        return r;
2649}
2650EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2651
2652static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2653{
2654        trace_kvm_mmu_unsync_page(sp);
2655        ++vcpu->kvm->stat.mmu_unsync;
2656        sp->unsync = 1;
2657
2658        kvm_mmu_mark_parents_unsync(sp);
2659}
2660
2661static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2662                                   bool can_unsync)
2663{
2664        struct kvm_mmu_page *sp;
2665
2666        if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2667                return true;
2668
2669        for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2670                if (!can_unsync)
2671                        return true;
2672
2673                if (sp->unsync)
2674                        continue;
2675
2676                WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2677                kvm_unsync_page(vcpu, sp);
2678        }
2679
2680        return false;
2681}
2682
2683static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2684{
2685        if (pfn_valid(pfn))
2686                return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn));
2687
2688        return true;
2689}
2690
2691static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2692                    unsigned pte_access, int level,
2693                    gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2694                    bool can_unsync, bool host_writable)
2695{
2696        u64 spte = 0;
2697        int ret = 0;
2698        struct kvm_mmu_page *sp;
2699
2700        if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2701                return 0;
2702
2703        sp = page_header(__pa(sptep));
2704        if (sp_ad_disabled(sp))
2705                spte |= shadow_acc_track_value;
2706
2707        /*
2708         * For the EPT case, shadow_present_mask is 0 if hardware
2709         * supports exec-only page table entries.  In that case,
2710         * ACC_USER_MASK and shadow_user_mask are used to represent
2711         * read access.  See FNAME(gpte_access) in paging_tmpl.h.
2712         */
2713        spte |= shadow_present_mask;
2714        if (!speculative)
2715                spte |= spte_shadow_accessed_mask(spte);
2716
2717        if (pte_access & ACC_EXEC_MASK)
2718                spte |= shadow_x_mask;
2719        else
2720                spte |= shadow_nx_mask;
2721
2722        if (pte_access & ACC_USER_MASK)
2723                spte |= shadow_user_mask;
2724
2725        if (level > PT_PAGE_TABLE_LEVEL)
2726                spte |= PT_PAGE_SIZE_MASK;
2727        if (tdp_enabled)
2728                spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2729                        kvm_is_mmio_pfn(pfn));
2730
2731        if (host_writable)
2732                spte |= SPTE_HOST_WRITEABLE;
2733        else
2734                pte_access &= ~ACC_WRITE_MASK;
2735
2736        spte |= (u64)pfn << PAGE_SHIFT;
2737        spte |= shadow_me_mask;
2738
2739        if (pte_access & ACC_WRITE_MASK) {
2740
2741                /*
2742                 * Other vcpu creates new sp in the window between
2743                 * mapping_level() and acquiring mmu-lock. We can
2744                 * allow guest to retry the access, the mapping can
2745                 * be fixed if guest refault.
2746                 */
2747                if (level > PT_PAGE_TABLE_LEVEL &&
2748                    mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
2749                        goto done;
2750
2751                spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
2752
2753                /*
2754                 * Optimization: for pte sync, if spte was writable the hash
2755                 * lookup is unnecessary (and expensive). Write protection
2756                 * is responsibility of mmu_get_page / kvm_sync_page.
2757                 * Same reasoning can be applied to dirty page accounting.
2758                 */
2759                if (!can_unsync && is_writable_pte(*sptep))
2760                        goto set_pte;
2761
2762                if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
2763                        pgprintk("%s: found shadow page for %llx, marking ro\n",
2764                                 __func__, gfn);
2765                        ret = 1;
2766                        pte_access &= ~ACC_WRITE_MASK;
2767                        spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
2768                }
2769        }
2770
2771        if (pte_access & ACC_WRITE_MASK) {
2772                kvm_vcpu_mark_page_dirty(vcpu, gfn);
2773                spte |= spte_shadow_dirty_mask(spte);
2774        }
2775
2776        if (speculative)
2777                spte = mark_spte_for_access_track(spte);
2778
2779set_pte:
2780        if (mmu_spte_update(sptep, spte))
2781                kvm_flush_remote_tlbs(vcpu->kvm);
2782done:
2783        return ret;
2784}
2785
2786static void mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2787                         unsigned pte_access, int write_fault, int *emulate,
2788                         int level, gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2789                         bool host_writable)
2790{
2791        int was_rmapped = 0;
2792        int rmap_count;
2793
2794        pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2795                 *sptep, write_fault, gfn);
2796
2797        if (is_shadow_present_pte(*sptep)) {
2798                /*
2799                 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2800                 * the parent of the now unreachable PTE.
2801                 */
2802                if (level > PT_PAGE_TABLE_LEVEL &&
2803                    !is_large_pte(*sptep)) {
2804                        struct kvm_mmu_page *child;
2805                        u64 pte = *sptep;
2806
2807                        child = page_header(pte & PT64_BASE_ADDR_MASK);
2808                        drop_parent_pte(child, sptep);
2809                        kvm_flush_remote_tlbs(vcpu->kvm);
2810                } else if (pfn != spte_to_pfn(*sptep)) {
2811                        pgprintk("hfn old %llx new %llx\n",
2812                                 spte_to_pfn(*sptep), pfn);
2813                        drop_spte(vcpu->kvm, sptep);
2814                        kvm_flush_remote_tlbs(vcpu->kvm);
2815                } else
2816                        was_rmapped = 1;
2817        }
2818
2819        if (set_spte(vcpu, sptep, pte_access, level, gfn, pfn, speculative,
2820              true, host_writable)) {
2821                if (write_fault)
2822                        *emulate = 1;
2823                kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2824        }
2825
2826        if (unlikely(is_mmio_spte(*sptep) && emulate))
2827                *emulate = 1;
2828
2829        pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2830        pgprintk("instantiating %s PTE (%s) at %llx (%llx) addr %p\n",
2831                 is_large_pte(*sptep)? "2MB" : "4kB",
2832                 *sptep & PT_WRITABLE_MASK ? "RW" : "R", gfn,
2833                 *sptep, sptep);
2834        if (!was_rmapped && is_large_pte(*sptep))
2835                ++vcpu->kvm->stat.lpages;
2836
2837        if (is_shadow_present_pte(*sptep)) {
2838                if (!was_rmapped) {
2839                        rmap_count = rmap_add(vcpu, sptep, gfn);
2840                        if (rmap_count > RMAP_RECYCLE_THRESHOLD)
2841                                rmap_recycle(vcpu, sptep, gfn);
2842                }
2843        }
2844
2845        kvm_release_pfn_clean(pfn);
2846}
2847
2848static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
2849                                         bool no_dirty_log)
2850{
2851        struct kvm_memory_slot *slot;
2852
2853        slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
2854        if (!slot)
2855                return KVM_PFN_ERR_FAULT;
2856
2857        return gfn_to_pfn_memslot_atomic(slot, gfn);
2858}
2859
2860static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2861                                    struct kvm_mmu_page *sp,
2862                                    u64 *start, u64 *end)
2863{
2864        struct page *pages[PTE_PREFETCH_NUM];
2865        struct kvm_memory_slot *slot;
2866        unsigned access = sp->role.access;
2867        int i, ret;
2868        gfn_t gfn;
2869
2870        gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
2871        slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2872        if (!slot)
2873                return -1;
2874
2875        ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2876        if (ret <= 0)
2877                return -1;
2878
2879        for (i = 0; i < ret; i++, gfn++, start++)
2880                mmu_set_spte(vcpu, start, access, 0, NULL,
2881                             sp->role.level, gfn, page_to_pfn(pages[i]),
2882                             true, true);
2883
2884        return 0;
2885}
2886
2887static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2888                                  struct kvm_mmu_page *sp, u64 *sptep)
2889{
2890        u64 *spte, *start = NULL;
2891        int i;
2892
2893        WARN_ON(!sp->role.direct);
2894
2895        i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
2896        spte = sp->spt + i;
2897
2898        for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
2899                if (is_shadow_present_pte(*spte) || spte == sptep) {
2900                        if (!start)
2901                                continue;
2902                        if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2903                                break;
2904                        start = NULL;
2905                } else if (!start)
2906                        start = spte;
2907        }
2908}
2909
2910static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2911{
2912        struct kvm_mmu_page *sp;
2913
2914        sp = page_header(__pa(sptep));
2915
2916        /*
2917         * Without accessed bits, there's no way to distinguish between
2918         * actually accessed translations and prefetched, so disable pte
2919         * prefetch if accessed bits aren't available.
2920         */
2921        if (sp_ad_disabled(sp))
2922                return;
2923
2924        if (sp->role.level > PT_PAGE_TABLE_LEVEL)
2925                return;
2926
2927        __direct_pte_prefetch(vcpu, sp, sptep);
2928}
2929
2930static int __direct_map(struct kvm_vcpu *vcpu, gpa_t v, int write,
2931                        int map_writable, int level, gfn_t gfn, kvm_pfn_t pfn,
2932                        bool prefault)
2933{
2934        struct kvm_shadow_walk_iterator iterator;
2935        struct kvm_mmu_page *sp;
2936        int emulate = 0;
2937        gfn_t pseudo_gfn;
2938
2939        if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2940                return 0;
2941
2942        for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
2943                if (iterator.level == level) {
2944                        mmu_set_spte(vcpu, iterator.sptep, ACC_ALL,
2945                                     write, &emulate, level, gfn, pfn,
2946                                     prefault, map_writable);
2947                        direct_pte_prefetch(vcpu, iterator.sptep);
2948                        ++vcpu->stat.pf_fixed;
2949                        break;
2950                }
2951
2952                drop_large_spte(vcpu, iterator.sptep);
2953                if (!is_shadow_present_pte(*iterator.sptep)) {
2954                        u64 base_addr = iterator.addr;
2955
2956                        base_addr &= PT64_LVL_ADDR_MASK(iterator.level);
2957                        pseudo_gfn = base_addr >> PAGE_SHIFT;
2958                        sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr,
2959                                              iterator.level - 1,
2960                                              1, ACC_ALL, iterator.sptep);
2961
2962                        link_shadow_page(iterator.sptep, sp);
2963                }
2964        }
2965        return emulate;
2966}
2967
2968static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
2969{
2970        siginfo_t info;
2971
2972        info.si_signo   = SIGBUS;
2973        info.si_errno   = 0;
2974        info.si_code    = BUS_MCEERR_AR;
2975        info.si_addr    = (void __user *)address;
2976        info.si_addr_lsb = PAGE_SHIFT;
2977
2978        send_sig_info(SIGBUS, &info, tsk);
2979}
2980
2981static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
2982{
2983        /*
2984         * Do not cache the mmio info caused by writing the readonly gfn
2985         * into the spte otherwise read access on readonly gfn also can
2986         * caused mmio page fault and treat it as mmio access.
2987         * Return 1 to tell kvm to emulate it.
2988         */
2989        if (pfn == KVM_PFN_ERR_RO_FAULT)
2990                return 1;
2991
2992        if (pfn == KVM_PFN_ERR_HWPOISON) {
2993                kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
2994                return 0;
2995        }
2996
2997        return -EFAULT;
2998}
2999
3000static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3001                                        gfn_t *gfnp, kvm_pfn_t *pfnp,
3002                                        int *levelp)
3003{
3004        kvm_pfn_t pfn = *pfnp;
3005        gfn_t gfn = *gfnp;
3006        int level = *levelp;
3007
3008        /*
3009         * Check if it's a transparent hugepage. If this would be an
3010         * hugetlbfs page, level wouldn't be set to
3011         * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3012         * here.
3013         */
3014        if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3015            level == PT_PAGE_TABLE_LEVEL &&
3016            PageTransCompound(pfn_to_page(pfn)) &&
3017            !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3018                unsigned long mask;
3019                /*
3020                 * mmu_notifier_retry was successful and we hold the
3021                 * mmu_lock here, so the pmd can't become splitting
3022                 * from under us, and in turn
3023                 * __split_huge_page_refcount() can't run from under
3024                 * us and we can safely transfer the refcount from
3025                 * PG_tail to PG_head as we switch the pfn to tail to
3026                 * head.
3027                 */
3028                *levelp = level = PT_DIRECTORY_LEVEL;
3029                mask = KVM_PAGES_PER_HPAGE(level) - 1;
3030                VM_BUG_ON((gfn & mask) != (pfn & mask));
3031                if (pfn & mask) {
3032                        gfn &= ~mask;
3033                        *gfnp = gfn;
3034                        kvm_release_pfn_clean(pfn);
3035                        pfn &= ~mask;
3036                        kvm_get_pfn(pfn);
3037                        *pfnp = pfn;
3038                }
3039        }
3040}
3041
3042static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3043                                kvm_pfn_t pfn, unsigned access, int *ret_val)
3044{
3045        bool ret = true;
3046
3047        /* The pfn is invalid, report the error! */
3048        if (unlikely(is_error_pfn(pfn))) {
3049                *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3050                goto exit;
3051        }
3052
3053        if (unlikely(is_noslot_pfn(pfn)))
3054                vcpu_cache_mmio_info(vcpu, gva, gfn, access);
3055
3056        ret = false;
3057exit:
3058        return ret;
3059}
3060
3061static bool page_fault_can_be_fast(u32 error_code)
3062{
3063        /*
3064         * Do not fix the mmio spte with invalid generation number which
3065         * need to be updated by slow page fault path.
3066         */
3067        if (unlikely(error_code & PFERR_RSVD_MASK))
3068                return false;
3069
3070        /* See if the page fault is due to an NX violation */
3071        if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3072                      == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3073                return false;
3074
3075        /*
3076         * #PF can be fast if:
3077         * 1. The shadow page table entry is not present, which could mean that
3078         *    the fault is potentially caused by access tracking (if enabled).
3079         * 2. The shadow page table entry is present and the fault
3080         *    is caused by write-protect, that means we just need change the W
3081         *    bit of the spte which can be done out of mmu-lock.
3082         *
3083         * However, if access tracking is disabled we know that a non-present
3084         * page must be a genuine page fault where we have to create a new SPTE.
3085         * So, if access tracking is disabled, we return true only for write
3086         * accesses to a present page.
3087         */
3088
3089        return shadow_acc_track_mask != 0 ||
3090               ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3091                == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3092}
3093
3094/*
3095 * Returns true if the SPTE was fixed successfully. Otherwise,
3096 * someone else modified the SPTE from its original value.
3097 */
3098static bool
3099fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3100                        u64 *sptep, u64 old_spte, u64 new_spte)
3101{
3102        gfn_t gfn;
3103
3104        WARN_ON(!sp->role.direct);
3105
3106        /*
3107         * Theoretically we could also set dirty bit (and flush TLB) here in
3108         * order to eliminate unnecessary PML logging. See comments in
3109         * set_spte. But fast_page_fault is very unlikely to happen with PML
3110         * enabled, so we do not do this. This might result in the same GPA
3111         * to be logged in PML buffer again when the write really happens, and
3112         * eventually to be called by mark_page_dirty twice. But it's also no
3113         * harm. This also avoids the TLB flush needed after setting dirty bit
3114         * so non-PML cases won't be impacted.
3115         *
3116         * Compare with set_spte where instead shadow_dirty_mask is set.
3117         */
3118        if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3119                return false;
3120
3121        if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3122                /*
3123                 * The gfn of direct spte is stable since it is
3124                 * calculated by sp->gfn.
3125                 */
3126                gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3127                kvm_vcpu_mark_page_dirty(vcpu, gfn);
3128        }
3129
3130        return true;
3131}
3132
3133static bool is_access_allowed(u32 fault_err_code, u64 spte)
3134{
3135        if (fault_err_code & PFERR_FETCH_MASK)
3136                return is_executable_pte(spte);
3137
3138        if (fault_err_code & PFERR_WRITE_MASK)
3139                return is_writable_pte(spte);
3140
3141        /* Fault was on Read access */
3142        return spte & PT_PRESENT_MASK;
3143}
3144
3145/*
3146 * Return value:
3147 * - true: let the vcpu to access on the same address again.
3148 * - false: let the real page fault path to fix it.
3149 */
3150static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
3151                            u32 error_code)
3152{
3153        struct kvm_shadow_walk_iterator iterator;
3154        struct kvm_mmu_page *sp;
3155        bool fault_handled = false;
3156        u64 spte = 0ull;
3157        uint retry_count = 0;
3158
3159        if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3160                return false;
3161
3162        if (!page_fault_can_be_fast(error_code))
3163                return false;
3164
3165        walk_shadow_page_lockless_begin(vcpu);
3166
3167        do {
3168                u64 new_spte;
3169
3170                for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
3171                        if (!is_shadow_present_pte(spte) ||
3172                            iterator.level < level)
3173                                break;
3174
3175                sp = page_header(__pa(iterator.sptep));
3176                if (!is_last_spte(spte, sp->role.level))
3177                        break;
3178
3179                /*
3180                 * Check whether the memory access that caused the fault would
3181                 * still cause it if it were to be performed right now. If not,
3182                 * then this is a spurious fault caused by TLB lazily flushed,
3183                 * or some other CPU has already fixed the PTE after the
3184                 * current CPU took the fault.
3185                 *
3186                 * Need not check the access of upper level table entries since
3187                 * they are always ACC_ALL.
3188                 */
3189                if (is_access_allowed(error_code, spte)) {
3190                        fault_handled = true;
3191                        break;
3192                }
3193
3194                new_spte = spte;
3195
3196                if (is_access_track_spte(spte))
3197                        new_spte = restore_acc_track_spte(new_spte);
3198
3199                /*
3200                 * Currently, to simplify the code, write-protection can
3201                 * be removed in the fast path only if the SPTE was
3202                 * write-protected for dirty-logging or access tracking.
3203                 */
3204                if ((error_code & PFERR_WRITE_MASK) &&
3205                    spte_can_locklessly_be_made_writable(spte))
3206                {
3207                        new_spte |= PT_WRITABLE_MASK;
3208
3209                        /*
3210                         * Do not fix write-permission on the large spte.  Since
3211                         * we only dirty the first page into the dirty-bitmap in
3212                         * fast_pf_fix_direct_spte(), other pages are missed
3213                         * if its slot has dirty logging enabled.
3214                         *
3215                         * Instead, we let the slow page fault path create a
3216                         * normal spte to fix the access.
3217                         *
3218                         * See the comments in kvm_arch_commit_memory_region().
3219                         */
3220                        if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3221                                break;
3222                }
3223
3224                /* Verify that the fault can be handled in the fast path */
3225                if (new_spte == spte ||
3226                    !is_access_allowed(error_code, new_spte))
3227                        break;
3228
3229                /*
3230                 * Currently, fast page fault only works for direct mapping
3231                 * since the gfn is not stable for indirect shadow page. See
3232                 * Documentation/virtual/kvm/locking.txt to get more detail.
3233                 */
3234                fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3235                                                        iterator.sptep, spte,
3236                                                        new_spte);
3237                if (fault_handled)
3238                        break;
3239
3240                if (++retry_count > 4) {
3241                        printk_once(KERN_WARNING
3242                                "kvm: Fast #PF retrying more than 4 times.\n");
3243                        break;
3244                }
3245
3246        } while (true);
3247
3248        trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
3249                              spte, fault_handled);
3250        walk_shadow_page_lockless_end(vcpu);
3251
3252        return fault_handled;
3253}
3254
3255static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3256                         gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3257static void make_mmu_pages_available(struct kvm_vcpu *vcpu);
3258
3259static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3260                         gfn_t gfn, bool prefault)
3261{
3262        int r;
3263        int level;
3264        bool force_pt_level = false;
3265        kvm_pfn_t pfn;
3266        unsigned long mmu_seq;
3267        bool map_writable, write = error_code & PFERR_WRITE_MASK;
3268
3269        level = mapping_level(vcpu, gfn, &force_pt_level);
3270        if (likely(!force_pt_level)) {
3271                /*
3272                 * This path builds a PAE pagetable - so we can map
3273                 * 2mb pages at maximum. Therefore check if the level
3274                 * is larger than that.
3275                 */
3276                if (level > PT_DIRECTORY_LEVEL)
3277                        level = PT_DIRECTORY_LEVEL;
3278
3279                gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3280        }
3281
3282        if (fast_page_fault(vcpu, v, level, error_code))
3283                return 0;
3284
3285        mmu_seq = vcpu->kvm->mmu_notifier_seq;
3286        smp_rmb();
3287
3288        if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3289                return 0;
3290
3291        if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3292                return r;
3293
3294        spin_lock(&vcpu->kvm->mmu_lock);
3295        if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3296                goto out_unlock;
3297        make_mmu_pages_available(vcpu);
3298        if (likely(!force_pt_level))
3299                transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
3300        r = __direct_map(vcpu, v, write, map_writable, level, gfn, pfn,
3301                         prefault);
3302        spin_unlock(&vcpu->kvm->mmu_lock);
3303
3304
3305        return r;
3306
3307out_unlock:
3308        spin_unlock(&vcpu->kvm->mmu_lock);
3309        kvm_release_pfn_clean(pfn);
3310        return 0;
3311}
3312
3313
3314static void mmu_free_roots(struct kvm_vcpu *vcpu)
3315{
3316        int i;
3317        struct kvm_mmu_page *sp;
3318        LIST_HEAD(invalid_list);
3319
3320        if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3321                return;
3322
3323        if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL &&
3324            (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL ||
3325             vcpu->arch.mmu.direct_map)) {
3326                hpa_t root = vcpu->arch.mmu.root_hpa;
3327
3328                spin_lock(&vcpu->kvm->mmu_lock);
3329                sp = page_header(root);
3330                --sp->root_count;
3331                if (!sp->root_count && sp->role.invalid) {
3332                        kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
3333                        kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3334                }
3335                spin_unlock(&vcpu->kvm->mmu_lock);
3336                vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3337                return;
3338        }
3339
3340        spin_lock(&vcpu->kvm->mmu_lock);
3341        for (i = 0; i < 4; ++i) {
3342                hpa_t root = vcpu->arch.mmu.pae_root[i];
3343
3344                if (root) {
3345                        root &= PT64_BASE_ADDR_MASK;
3346                        sp = page_header(root);
3347                        --sp->root_count;
3348                        if (!sp->root_count && sp->role.invalid)
3349                                kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
3350                                                         &invalid_list);
3351                }
3352                vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
3353        }
3354        kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3355        spin_unlock(&vcpu->kvm->mmu_lock);
3356        vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3357}
3358
3359static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3360{
3361        int ret = 0;
3362
3363        if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3364                kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3365                ret = 1;
3366        }
3367
3368        return ret;
3369}
3370
3371static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3372{
3373        struct kvm_mmu_page *sp;
3374        unsigned i;
3375
3376        if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
3377                spin_lock(&vcpu->kvm->mmu_lock);
3378                make_mmu_pages_available(vcpu);
3379                sp = kvm_mmu_get_page(vcpu, 0, 0, PT64_ROOT_LEVEL,
3380                                      1, ACC_ALL, NULL);
3381                ++sp->root_count;
3382                spin_unlock(&vcpu->kvm->mmu_lock);
3383                vcpu->arch.mmu.root_hpa = __pa(sp->spt);
3384        } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
3385                for (i = 0; i < 4; ++i) {
3386                        hpa_t root = vcpu->arch.mmu.pae_root[i];
3387
3388                        MMU_WARN_ON(VALID_PAGE(root));
3389                        spin_lock(&vcpu->kvm->mmu_lock);
3390                        make_mmu_pages_available(vcpu);
3391                        sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3392                                              i << 30,
3393                                              PT32_ROOT_LEVEL, 1, ACC_ALL,
3394                                              NULL);
3395                        root = __pa(sp->spt);
3396                        ++sp->root_count;
3397                        spin_unlock(&vcpu->kvm->mmu_lock);
3398                        vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
3399                }
3400                vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3401        } else
3402                BUG();
3403
3404        return 0;
3405}
3406
3407static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3408{
3409        struct kvm_mmu_page *sp;
3410        u64 pdptr, pm_mask;
3411        gfn_t root_gfn;
3412        int i;
3413
3414        root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
3415
3416        if (mmu_check_root(vcpu, root_gfn))
3417                return 1;
3418
3419        /*
3420         * Do we shadow a long mode page table? If so we need to
3421         * write-protect the guests page table root.
3422         */
3423        if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) {
3424                hpa_t root = vcpu->arch.mmu.root_hpa;
3425
3426                MMU_WARN_ON(VALID_PAGE(root));
3427
3428                spin_lock(&vcpu->kvm->mmu_lock);
3429                make_mmu_pages_available(vcpu);
3430                sp = kvm_mmu_get_page(vcpu, root_gfn, 0, PT64_ROOT_LEVEL,
3431                                      0, ACC_ALL, NULL);
3432                root = __pa(sp->spt);
3433                ++sp->root_count;
3434                spin_unlock(&vcpu->kvm->mmu_lock);
3435                vcpu->arch.mmu.root_hpa = root;
3436                return 0;
3437        }
3438
3439        /*
3440         * We shadow a 32 bit page table. This may be a legacy 2-level
3441         * or a PAE 3-level page table. In either case we need to be aware that
3442         * the shadow page table may be a PAE or a long mode page table.
3443         */
3444        pm_mask = PT_PRESENT_MASK;
3445        if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL)
3446                pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3447
3448        for (i = 0; i < 4; ++i) {
3449                hpa_t root = vcpu->arch.mmu.pae_root[i];
3450
3451                MMU_WARN_ON(VALID_PAGE(root));
3452                if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
3453                        pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
3454                        if (!(pdptr & PT_PRESENT_MASK)) {
3455                                vcpu->arch.mmu.pae_root[i] = 0;
3456                                continue;
3457                        }
3458                        root_gfn = pdptr >> PAGE_SHIFT;
3459                        if (mmu_check_root(vcpu, root_gfn))
3460                                return 1;
3461                }
3462                spin_lock(&vcpu->kvm->mmu_lock);
3463                make_mmu_pages_available(vcpu);
3464                sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30,
3465                                      PT32_ROOT_LEVEL, 0,
3466                                      ACC_ALL, NULL);
3467                root = __pa(sp->spt);
3468                ++sp->root_count;
3469                spin_unlock(&vcpu->kvm->mmu_lock);
3470
3471                vcpu->arch.mmu.pae_root[i] = root | pm_mask;
3472        }
3473        vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3474
3475        /*
3476         * If we shadow a 32 bit page table with a long mode page
3477         * table we enter this path.
3478         */
3479        if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
3480                if (vcpu->arch.mmu.lm_root == NULL) {
3481                        /*
3482                         * The additional page necessary for this is only
3483                         * allocated on demand.
3484                         */
3485
3486                        u64 *lm_root;
3487
3488                        lm_root = (void*)get_zeroed_page(GFP_KERNEL);
3489                        if (lm_root == NULL)
3490                                return 1;
3491
3492                        lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
3493
3494                        vcpu->arch.mmu.lm_root = lm_root;
3495                }
3496
3497                vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
3498        }
3499
3500        return 0;
3501}
3502
3503static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3504{
3505        if (vcpu->arch.mmu.direct_map)
3506                return mmu_alloc_direct_roots(vcpu);
3507        else
3508                return mmu_alloc_shadow_roots(vcpu);
3509}
3510
3511static void mmu_sync_roots(struct kvm_vcpu *vcpu)
3512{
3513        int i;
3514        struct kvm_mmu_page *sp;
3515
3516        if (vcpu->arch.mmu.direct_map)
3517                return;
3518
3519        if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3520                return;
3521
3522        vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3523        kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3524        if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) {
3525                hpa_t root = vcpu->arch.mmu.root_hpa;
3526                sp = page_header(root);
3527                mmu_sync_children(vcpu, sp);
3528                kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3529                return;
3530        }
3531        for (i = 0; i < 4; ++i) {
3532                hpa_t root = vcpu->arch.mmu.pae_root[i];
3533
3534                if (root && VALID_PAGE(root)) {
3535                        root &= PT64_BASE_ADDR_MASK;
3536                        sp = page_header(root);
3537                        mmu_sync_children(vcpu, sp);
3538                }
3539        }
3540        kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3541}
3542
3543void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3544{
3545        spin_lock(&vcpu->kvm->mmu_lock);
3546        mmu_sync_roots(vcpu);
3547        spin_unlock(&vcpu->kvm->mmu_lock);
3548}
3549EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3550
3551static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3552                                  u32 access, struct x86_exception *exception)
3553{
3554        if (exception)
3555                exception->error_code = 0;
3556        return vaddr;
3557}
3558
3559static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3560                                         u32 access,
3561                                         struct x86_exception *exception)
3562{
3563        if (exception)
3564                exception->error_code = 0;
3565        return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3566}
3567
3568static bool
3569__is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3570{
3571        int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3572
3573        return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3574                ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3575}
3576
3577static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3578{
3579        return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3580}
3581
3582static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3583{
3584        return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3585}
3586
3587static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3588{
3589        if (direct)
3590                return vcpu_match_mmio_gpa(vcpu, addr);
3591
3592        return vcpu_match_mmio_gva(vcpu, addr);
3593}
3594
3595/* return true if reserved bit is detected on spte. */
3596static bool
3597walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3598{
3599        struct kvm_shadow_walk_iterator iterator;
3600        u64 sptes[PT64_ROOT_LEVEL], spte = 0ull;
3601        int root, leaf;
3602        bool reserved = false;
3603
3604        if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3605                goto exit;
3606
3607        walk_shadow_page_lockless_begin(vcpu);
3608
3609        for (shadow_walk_init(&iterator, vcpu, addr),
3610                 leaf = root = iterator.level;
3611             shadow_walk_okay(&iterator);
3612             __shadow_walk_next(&iterator, spte)) {
3613                spte = mmu_spte_get_lockless(iterator.sptep);
3614
3615                sptes[leaf - 1] = spte;
3616                leaf--;
3617
3618                if (!is_shadow_present_pte(spte))
3619                        break;
3620
3621                reserved |= is_shadow_zero_bits_set(&vcpu->arch.mmu, spte,
3622                                                    iterator.level);
3623        }
3624
3625        walk_shadow_page_lockless_end(vcpu);
3626
3627        if (reserved) {
3628                pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3629                       __func__, addr);
3630                while (root > leaf) {
3631                        pr_err("------ spte 0x%llx level %d.\n",
3632                               sptes[root - 1], root);
3633                        root--;
3634                }
3635        }
3636exit:
3637        *sptep = spte;
3638        return reserved;
3639}
3640
3641int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3642{
3643        u64 spte;
3644        bool reserved;
3645
3646        if (mmio_info_in_cache(vcpu, addr, direct))
3647                return RET_MMIO_PF_EMULATE;
3648
3649        reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3650        if (WARN_ON(reserved))
3651                return RET_MMIO_PF_BUG;
3652
3653        if (is_mmio_spte(spte)) {
3654                gfn_t gfn = get_mmio_spte_gfn(spte);
3655                unsigned access = get_mmio_spte_access(spte);
3656
3657                if (!check_mmio_spte(vcpu, spte))
3658                        return RET_MMIO_PF_INVALID;
3659
3660                if (direct)
3661                        addr = 0;
3662
3663                trace_handle_mmio_page_fault(addr, gfn, access);
3664                vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3665                return RET_MMIO_PF_EMULATE;
3666        }
3667
3668        /*
3669         * If the page table is zapped by other cpus, let CPU fault again on
3670         * the address.
3671         */
3672        return RET_MMIO_PF_RETRY;
3673}
3674EXPORT_SYMBOL_GPL(handle_mmio_page_fault);
3675
3676static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3677                                         u32 error_code, gfn_t gfn)
3678{
3679        if (unlikely(error_code & PFERR_RSVD_MASK))
3680                return false;
3681
3682        if (!(error_code & PFERR_PRESENT_MASK) ||
3683              !(error_code & PFERR_WRITE_MASK))
3684                return false;
3685
3686        /*
3687         * guest is writing the page which is write tracked which can
3688         * not be fixed by page fault handler.
3689         */
3690        if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
3691                return true;
3692
3693        return false;
3694}
3695
3696static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3697{
3698        struct kvm_shadow_walk_iterator iterator;
3699        u64 spte;
3700
3701        if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3702                return;
3703
3704        walk_shadow_page_lockless_begin(vcpu);
3705        for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
3706                clear_sp_write_flooding_count(iterator.sptep);
3707                if (!is_shadow_present_pte(spte))
3708                        break;
3709        }
3710        walk_shadow_page_lockless_end(vcpu);
3711}
3712
3713static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
3714                                u32 error_code, bool prefault)
3715{
3716        gfn_t gfn = gva >> PAGE_SHIFT;
3717        int r;
3718
3719        pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
3720
3721        if (page_fault_handle_page_track(vcpu, error_code, gfn))
3722                return 1;
3723
3724        r = mmu_topup_memory_caches(vcpu);
3725        if (r)
3726                return r;
3727
3728        MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
3729
3730
3731        return nonpaging_map(vcpu, gva & PAGE_MASK,
3732                             error_code, gfn, prefault);
3733}
3734
3735static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
3736{
3737        struct kvm_arch_async_pf arch;
3738
3739        arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
3740        arch.gfn = gfn;
3741        arch.direct_map = vcpu->arch.mmu.direct_map;
3742        arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
3743
3744        return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
3745}
3746
3747bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
3748{
3749        if (unlikely(!lapic_in_kernel(vcpu) ||
3750                     kvm_event_needs_reinjection(vcpu)))
3751                return false;
3752
3753        if (is_guest_mode(vcpu))
3754                return false;
3755
3756        return kvm_x86_ops->interrupt_allowed(vcpu);
3757}
3758
3759static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3760                         gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
3761{
3762        struct kvm_memory_slot *slot;
3763        bool async;
3764
3765        slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3766        async = false;
3767        *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
3768        if (!async)
3769                return false; /* *pfn has correct page already */
3770
3771        if (!prefault && kvm_can_do_async_pf(vcpu)) {
3772                trace_kvm_try_async_get_page(gva, gfn);
3773                if (kvm_find_async_pf_gfn(vcpu, gfn)) {
3774                        trace_kvm_async_pf_doublefault(gva, gfn);
3775                        kvm_make_request(KVM_REQ_APF_HALT, vcpu);
3776                        return true;
3777                } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
3778                        return true;
3779        }
3780
3781        *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
3782        return false;
3783}
3784
3785static bool
3786check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
3787{
3788        int page_num = KVM_PAGES_PER_HPAGE(level);
3789
3790        gfn &= ~(page_num - 1);
3791
3792        return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
3793}
3794
3795static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
3796                          bool prefault)
3797{
3798        kvm_pfn_t pfn;
3799        int r;
3800        int level;
3801        bool force_pt_level;
3802        gfn_t gfn = gpa >> PAGE_SHIFT;
3803        unsigned long mmu_seq;
3804        int write = error_code & PFERR_WRITE_MASK;
3805        bool map_writable;
3806
3807        MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
3808
3809        if (page_fault_handle_page_track(vcpu, error_code, gfn))
3810                return 1;
3811
3812        r = mmu_topup_memory_caches(vcpu);
3813        if (r)
3814                return r;
3815
3816        force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
3817                                                           PT_DIRECTORY_LEVEL);
3818        level = mapping_level(vcpu, gfn, &force_pt_level);
3819        if (likely(!force_pt_level)) {
3820                if (level > PT_DIRECTORY_LEVEL &&
3821                    !check_hugepage_cache_consistency(vcpu, gfn, level))
3822                        level = PT_DIRECTORY_LEVEL;
3823                gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3824        }
3825
3826        if (fast_page_fault(vcpu, gpa, level, error_code))
3827                return 0;
3828
3829        mmu_seq = vcpu->kvm->mmu_notifier_seq;
3830        smp_rmb();
3831
3832        if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
3833                return 0;
3834
3835        if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
3836                return r;
3837
3838        spin_lock(&vcpu->kvm->mmu_lock);
3839        if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3840                goto out_unlock;
3841        make_mmu_pages_available(vcpu);
3842        if (likely(!force_pt_level))
3843                transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
3844        r = __direct_map(vcpu, gpa, write, map_writable,
3845                         level, gfn, pfn, prefault);
3846        spin_unlock(&vcpu->kvm->mmu_lock);
3847
3848        return r;
3849
3850out_unlock:
3851        spin_unlock(&vcpu->kvm->mmu_lock);
3852        kvm_release_pfn_clean(pfn);
3853        return 0;
3854}
3855
3856static void nonpaging_init_context(struct kvm_vcpu *vcpu,
3857                                   struct kvm_mmu *context)
3858{
3859        context->page_fault = nonpaging_page_fault;
3860        context->gva_to_gpa = nonpaging_gva_to_gpa;
3861        context->sync_page = nonpaging_sync_page;
3862        context->invlpg = nonpaging_invlpg;
3863        context->update_pte = nonpaging_update_pte;
3864        context->root_level = 0;
3865        context->shadow_root_level = PT32E_ROOT_LEVEL;
3866        context->root_hpa = INVALID_PAGE;
3867        context->direct_map = true;
3868        context->nx = false;
3869}
3870
3871void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu)
3872{
3873        mmu_free_roots(vcpu);
3874}
3875
3876static unsigned long get_cr3(struct kvm_vcpu *vcpu)
3877{
3878        return kvm_read_cr3(vcpu);
3879}
3880
3881static void inject_page_fault(struct kvm_vcpu *vcpu,
3882                              struct x86_exception *fault)
3883{
3884        vcpu->arch.mmu.inject_page_fault(vcpu, fault);
3885}
3886
3887static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
3888                           unsigned access, int *nr_present)
3889{
3890        if (unlikely(is_mmio_spte(*sptep))) {
3891                if (gfn != get_mmio_spte_gfn(*sptep)) {
3892                        mmu_spte_clear_no_track(sptep);
3893                        return true;
3894                }
3895
3896                (*nr_present)++;
3897                mark_mmio_spte(vcpu, sptep, gfn, access);
3898                return true;
3899        }
3900
3901        return false;
3902}
3903
3904static inline bool is_last_gpte(struct kvm_mmu *mmu,
3905                                unsigned level, unsigned gpte)
3906{
3907        /*
3908         * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
3909         * If it is clear, there are no large pages at this level, so clear
3910         * PT_PAGE_SIZE_MASK in gpte if that is the case.
3911         */
3912        gpte &= level - mmu->last_nonleaf_level;
3913
3914        /*
3915         * PT_PAGE_TABLE_LEVEL always terminates.  The RHS has bit 7 set
3916         * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
3917         * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
3918         */
3919        gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
3920
3921        return gpte & PT_PAGE_SIZE_MASK;
3922}
3923
3924#define PTTYPE_EPT 18 /* arbitrary */
3925#define PTTYPE PTTYPE_EPT
3926#include "paging_tmpl.h"
3927#undef PTTYPE
3928
3929#define PTTYPE 64
3930#include "paging_tmpl.h"
3931#undef PTTYPE
3932
3933#define PTTYPE 32
3934#include "paging_tmpl.h"
3935#undef PTTYPE
3936
3937static void
3938__reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
3939                        struct rsvd_bits_validate *rsvd_check,
3940                        int maxphyaddr, int level, bool nx, bool gbpages,
3941                        bool pse, bool amd)
3942{
3943        u64 exb_bit_rsvd = 0;
3944        u64 gbpages_bit_rsvd = 0;
3945        u64 nonleaf_bit8_rsvd = 0;
3946
3947        rsvd_check->bad_mt_xwr = 0;
3948
3949        if (!nx)
3950                exb_bit_rsvd = rsvd_bits(63, 63);
3951        if (!gbpages)
3952                gbpages_bit_rsvd = rsvd_bits(7, 7);
3953
3954        /*
3955         * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
3956         * leaf entries) on AMD CPUs only.
3957         */
3958        if (amd)
3959                nonleaf_bit8_rsvd = rsvd_bits(8, 8);
3960
3961        switch (level) {
3962        case PT32_ROOT_LEVEL:
3963                /* no rsvd bits for 2 level 4K page table entries */
3964                rsvd_check->rsvd_bits_mask[0][1] = 0;
3965                rsvd_check->rsvd_bits_mask[0][0] = 0;
3966                rsvd_check->rsvd_bits_mask[1][0] =
3967                        rsvd_check->rsvd_bits_mask[0][0];
3968
3969                if (!pse) {
3970                        rsvd_check->rsvd_bits_mask[1][1] = 0;
3971                        break;
3972                }
3973
3974                if (is_cpuid_PSE36())
3975                        /* 36bits PSE 4MB page */
3976                        rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
3977                else
3978                        /* 32 bits PSE 4MB page */
3979                        rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
3980                break;
3981        case PT32E_ROOT_LEVEL:
3982                rsvd_check->rsvd_bits_mask[0][2] =
3983                        rsvd_bits(maxphyaddr, 63) |
3984                        rsvd_bits(5, 8) | rsvd_bits(1, 2);      /* PDPTE */
3985                rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
3986                        rsvd_bits(maxphyaddr, 62);      /* PDE */
3987                rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
3988                        rsvd_bits(maxphyaddr, 62);      /* PTE */
3989                rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
3990                        rsvd_bits(maxphyaddr, 62) |
3991                        rsvd_bits(13, 20);              /* large page */
3992                rsvd_check->rsvd_bits_mask[1][0] =
3993                        rsvd_check->rsvd_bits_mask[0][0];
3994                break;
3995        case PT64_ROOT_LEVEL:
3996                rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
3997                        nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
3998                        rsvd_bits(maxphyaddr, 51);
3999                rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4000                        nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4001                        rsvd_bits(maxphyaddr, 51);
4002                rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4003                        rsvd_bits(maxphyaddr, 51);
4004                rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4005                        rsvd_bits(maxphyaddr, 51);
4006                rsvd_check->rsvd_bits_mask[1][3] =
4007                        rsvd_check->rsvd_bits_mask[0][3];
4008                rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4009                        gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4010                        rsvd_bits(13, 29);
4011                rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4012                        rsvd_bits(maxphyaddr, 51) |
4013                        rsvd_bits(13, 20);              /* large page */
4014                rsvd_check->rsvd_bits_mask[1][0] =
4015                        rsvd_check->rsvd_bits_mask[0][0];
4016                break;
4017        }
4018}
4019
4020static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4021                                  struct kvm_mmu *context)
4022{
4023        __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4024                                cpuid_maxphyaddr(vcpu), context->root_level,
4025                                context->nx,
4026                                guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4027                                is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4028}
4029
4030static void
4031__reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4032                            int maxphyaddr, bool execonly)
4033{
4034        u64 bad_mt_xwr;
4035
4036        rsvd_check->rsvd_bits_mask[0][3] =
4037                rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4038        rsvd_check->rsvd_bits_mask[0][2] =
4039                rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4040        rsvd_check->rsvd_bits_mask[0][1] =
4041                rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4042        rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4043
4044        /* large page */
4045        rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4046        rsvd_check->rsvd_bits_mask[1][2] =
4047                rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4048        rsvd_check->rsvd_bits_mask[1][1] =
4049                rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4050        rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4051
4052        bad_mt_xwr = 0xFFull << (2 * 8);        /* bits 3..5 must not be 2 */
4053        bad_mt_xwr |= 0xFFull << (3 * 8);       /* bits 3..5 must not be 3 */
4054        bad_mt_xwr |= 0xFFull << (7 * 8);       /* bits 3..5 must not be 7 */
4055        bad_mt_xwr |= REPEAT_BYTE(1ull << 2);   /* bits 0..2 must not be 010 */
4056        bad_mt_xwr |= REPEAT_BYTE(1ull << 6);   /* bits 0..2 must not be 110 */
4057        if (!execonly) {
4058                /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4059                bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4060        }
4061        rsvd_check->bad_mt_xwr = bad_mt_xwr;
4062}
4063
4064static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4065                struct kvm_mmu *context, bool execonly)
4066{
4067        __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4068                                    cpuid_maxphyaddr(vcpu), execonly);
4069}
4070
4071/*
4072 * the page table on host is the shadow page table for the page
4073 * table in guest or amd nested guest, its mmu features completely
4074 * follow the features in guest.
4075 */
4076void
4077reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4078{
4079        bool uses_nx = context->nx || context->base_role.smep_andnot_wp;
4080        struct rsvd_bits_validate *shadow_zero_check;
4081        int i;
4082
4083        /*
4084         * Passing "true" to the last argument is okay; it adds a check
4085         * on bit 8 of the SPTEs which KVM doesn't use anyway.
4086         */
4087        shadow_zero_check = &context->shadow_zero_check;
4088        __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4089                                boot_cpu_data.x86_phys_bits,
4090                                context->shadow_root_level, uses_nx,
4091                                guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4092                                is_pse(vcpu), true);
4093
4094        if (!shadow_me_mask)
4095                return;
4096
4097        for (i = context->shadow_root_level; --i >= 0;) {
4098                shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4099                shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4100        }
4101
4102}
4103EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4104
4105static inline bool boot_cpu_is_amd(void)
4106{
4107        WARN_ON_ONCE(!tdp_enabled);
4108        return shadow_x_mask == 0;
4109}
4110
4111/*
4112 * the direct page table on host, use as much mmu features as
4113 * possible, however, kvm currently does not do execution-protection.
4114 */
4115static void
4116reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4117                                struct kvm_mmu *context)
4118{
4119        struct rsvd_bits_validate *shadow_zero_check;
4120        int i;
4121
4122        shadow_zero_check = &context->shadow_zero_check;
4123
4124        if (boot_cpu_is_amd())
4125                __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4126                                        boot_cpu_data.x86_phys_bits,
4127                                        context->shadow_root_level, false,
4128                                        cpu_has_gbpages, true, true);
4129        else
4130                __reset_rsvds_bits_mask_ept(shadow_zero_check,
4131                                            boot_cpu_data.x86_phys_bits,
4132                                            false);
4133
4134        if (!shadow_me_mask)
4135                return;
4136
4137        for (i = context->shadow_root_level; --i >= 0;) {
4138                shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4139                shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4140        }
4141}
4142
4143/*
4144 * as the comments in reset_shadow_zero_bits_mask() except it
4145 * is the shadow page table for intel nested guest.
4146 */
4147static void
4148reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4149                                struct kvm_mmu *context, bool execonly)
4150{
4151        __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4152                                    boot_cpu_data.x86_phys_bits, execonly);
4153}
4154
4155#define BYTE_MASK(access) \
4156        ((1 & (access) ? 2 : 0) | \
4157         (2 & (access) ? 4 : 0) | \
4158         (3 & (access) ? 8 : 0) | \
4159         (4 & (access) ? 16 : 0) | \
4160         (5 & (access) ? 32 : 0) | \
4161         (6 & (access) ? 64 : 0) | \
4162         (7 & (access) ? 128 : 0))
4163
4164
4165static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4166                                      struct kvm_mmu *mmu, bool ept)
4167{
4168        unsigned byte;
4169
4170        const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4171        const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4172        const u8 u = BYTE_MASK(ACC_USER_MASK);
4173
4174        bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4175        bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4176        bool cr0_wp = is_write_protection(vcpu);
4177
4178        for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4179                unsigned pfec = byte << 1;
4180
4181                /*
4182                 * Each "*f" variable has a 1 bit for each UWX value
4183                 * that causes a fault with the given PFEC.
4184                 */
4185
4186                /* Faults from writes to non-writable pages */
4187                u8 wf = (pfec & PFERR_WRITE_MASK) ? ~w : 0;
4188                /* Faults from user mode accesses to supervisor pages */
4189                u8 uf = (pfec & PFERR_USER_MASK) ? ~u : 0;
4190                /* Faults from fetches of non-executable pages*/
4191                u8 ff = (pfec & PFERR_FETCH_MASK) ? ~x : 0;
4192                /* Faults from kernel mode fetches of user pages */
4193                u8 smepf = 0;
4194                /* Faults from kernel mode accesses of user pages */
4195                u8 smapf = 0;
4196
4197                if (!ept) {
4198                        /* Faults from kernel mode accesses to user pages */
4199                        u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4200
4201                        /* Not really needed: !nx will cause pte.nx to fault */
4202                        if (!mmu->nx)
4203                                ff = 0;
4204
4205                        /* Allow supervisor writes if !cr0.wp */
4206                        if (!cr0_wp)
4207                                wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4208
4209                        /* Disallow supervisor fetches of user code if cr4.smep */
4210                        if (cr4_smep)
4211                                smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4212
4213                        /*
4214                         * SMAP:kernel-mode data accesses from user-mode
4215                         * mappings should fault. A fault is considered
4216                         * as a SMAP violation if all of the following
4217                         * conditions are ture:
4218                         *   - X86_CR4_SMAP is set in CR4
4219                         *   - A user page is accessed
4220                         *   - The access is not a fetch
4221                         *   - Page fault in kernel mode
4222                         *   - if CPL = 3 or X86_EFLAGS_AC is clear
4223                         *
4224                         * Here, we cover the first three conditions.
4225                         * The fourth is computed dynamically in permission_fault();
4226                         * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4227                         * *not* subject to SMAP restrictions.
4228                         */
4229                        if (cr4_smap)
4230                                smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4231                }
4232
4233                mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4234        }
4235}
4236
4237/*
4238* PKU is an additional mechanism by which the paging controls access to
4239* user-mode addresses based on the value in the PKRU register.  Protection
4240* key violations are reported through a bit in the page fault error code.
4241* Unlike other bits of the error code, the PK bit is not known at the
4242* call site of e.g. gva_to_gpa; it must be computed directly in
4243* permission_fault based on two bits of PKRU, on some machine state (CR4,
4244* CR0, EFER, CPL), and on other bits of the error code and the page tables.
4245*
4246* In particular the following conditions come from the error code, the
4247* page tables and the machine state:
4248* - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4249* - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4250* - PK is always zero if U=0 in the page tables
4251* - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4252*
4253* The PKRU bitmask caches the result of these four conditions.  The error
4254* code (minus the P bit) and the page table's U bit form an index into the
4255* PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
4256* with the two bits of the PKRU register corresponding to the protection key.
4257* For the first three conditions above the bits will be 00, thus masking
4258* away both AD and WD.  For all reads or if the last condition holds, WD
4259* only will be masked away.
4260*/
4261static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4262                                bool ept)
4263{
4264        unsigned bit;
4265        bool wp;
4266
4267        if (ept) {
4268                mmu->pkru_mask = 0;
4269                return;
4270        }
4271
4272        /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4273        if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4274                mmu->pkru_mask = 0;
4275                return;
4276        }
4277
4278        wp = is_write_protection(vcpu);
4279
4280        for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4281                unsigned pfec, pkey_bits;
4282                bool check_pkey, check_write, ff, uf, wf, pte_user;
4283
4284                pfec = bit << 1;
4285                ff = pfec & PFERR_FETCH_MASK;
4286                uf = pfec & PFERR_USER_MASK;
4287                wf = pfec & PFERR_WRITE_MASK;
4288
4289                /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4290                pte_user = pfec & PFERR_RSVD_MASK;
4291
4292                /*
4293                 * Only need to check the access which is not an
4294                 * instruction fetch and is to a user page.
4295                 */
4296                check_pkey = (!ff && pte_user);
4297                /*
4298                 * write access is controlled by PKRU if it is a
4299                 * user access or CR0.WP = 1.
4300                 */
4301                check_write = check_pkey && wf && (uf || wp);
4302
4303                /* PKRU.AD stops both read and write access. */
4304                pkey_bits = !!check_pkey;
4305                /* PKRU.WD stops write access. */
4306                pkey_bits |= (!!check_write) << 1;
4307
4308                mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4309        }
4310}
4311
4312static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4313{
4314        unsigned root_level = mmu->root_level;
4315
4316        mmu->last_nonleaf_level = root_level;
4317        if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4318                mmu->last_nonleaf_level++;
4319}
4320
4321static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4322                                         struct kvm_mmu *context,
4323                                         int level)
4324{
4325        context->nx = is_nx(vcpu);
4326        context->root_level = level;
4327
4328        reset_rsvds_bits_mask(vcpu, context);
4329        update_permission_bitmask(vcpu, context, false);
4330        update_pkru_bitmask(vcpu, context, false);
4331        update_last_nonleaf_level(vcpu, context);
4332
4333        MMU_WARN_ON(!is_pae(vcpu));
4334        context->page_fault = paging64_page_fault;
4335        context->gva_to_gpa = paging64_gva_to_gpa;
4336        context->sync_page = paging64_sync_page;
4337        context->invlpg = paging64_invlpg;
4338        context->update_pte = paging64_update_pte;
4339        context->shadow_root_level = level;
4340        context->root_hpa = INVALID_PAGE;
4341        context->direct_map = false;
4342}
4343
4344static void paging64_init_context(struct kvm_vcpu *vcpu,
4345                                  struct kvm_mmu *context)
4346{
4347        paging64_init_context_common(vcpu, context, PT64_ROOT_LEVEL);
4348}
4349
4350static void paging32_init_context(struct kvm_vcpu *vcpu,
4351                                  struct kvm_mmu *context)
4352{
4353        context->nx = false;
4354        context->root_level = PT32_ROOT_LEVEL;
4355
4356        reset_rsvds_bits_mask(vcpu, context);
4357        update_permission_bitmask(vcpu, context, false);
4358        update_pkru_bitmask(vcpu, context, false);
4359        update_last_nonleaf_level(vcpu, context);
4360
4361        context->page_fault = paging32_page_fault;
4362        context->gva_to_gpa = paging32_gva_to_gpa;
4363        context->sync_page = paging32_sync_page;
4364        context->invlpg = paging32_invlpg;
4365        context->update_pte = paging32_update_pte;
4366        context->shadow_root_level = PT32E_ROOT_LEVEL;
4367        context->root_hpa = INVALID_PAGE;
4368        context->direct_map = false;
4369}
4370
4371static void paging32E_init_context(struct kvm_vcpu *vcpu,
4372                                   struct kvm_mmu *context)
4373{
4374        paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4375}
4376
4377static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4378{
4379        struct kvm_mmu *context = &vcpu->arch.mmu;
4380
4381        context->base_role.word = 0;
4382        context->base_role.smm = is_smm(vcpu);
4383        context->base_role.ad_disabled = (shadow_accessed_mask == 0);
4384        context->page_fault = tdp_page_fault;
4385        context->sync_page = nonpaging_sync_page;
4386        context->invlpg = nonpaging_invlpg;
4387        context->update_pte = nonpaging_update_pte;
4388        context->shadow_root_level = kvm_x86_ops->get_tdp_level();
4389        context->root_hpa = INVALID_PAGE;
4390        context->direct_map = true;
4391        context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4392        context->get_cr3 = get_cr3;
4393        context->get_pdptr = kvm_pdptr_read;
4394        context->inject_page_fault = kvm_inject_page_fault;
4395
4396        if (!is_paging(vcpu)) {
4397                context->nx = false;
4398                context->gva_to_gpa = nonpaging_gva_to_gpa;
4399                context->root_level = 0;
4400        } else if (is_long_mode(vcpu)) {
4401                context->nx = is_nx(vcpu);
4402                context->root_level = PT64_ROOT_LEVEL;
4403                reset_rsvds_bits_mask(vcpu, context);
4404                context->gva_to_gpa = paging64_gva_to_gpa;
4405        } else if (is_pae(vcpu)) {
4406                context->nx = is_nx(vcpu);
4407                context->root_level = PT32E_ROOT_LEVEL;
4408                reset_rsvds_bits_mask(vcpu, context);
4409                context->gva_to_gpa = paging64_gva_to_gpa;
4410        } else {
4411                context->nx = false;
4412                context->root_level = PT32_ROOT_LEVEL;
4413                reset_rsvds_bits_mask(vcpu, context);
4414                context->gva_to_gpa = paging32_gva_to_gpa;
4415        }
4416
4417        update_permission_bitmask(vcpu, context, false);
4418        update_pkru_bitmask(vcpu, context, false);
4419        update_last_nonleaf_level(vcpu, context);
4420        reset_tdp_shadow_zero_bits_mask(vcpu, context);
4421}
4422
4423void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4424{
4425        bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4426        bool smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4427        struct kvm_mmu *context = &vcpu->arch.mmu;
4428
4429        MMU_WARN_ON(VALID_PAGE(context->root_hpa));
4430
4431        if (!is_paging(vcpu))
4432                nonpaging_init_context(vcpu, context);
4433        else if (is_long_mode(vcpu))
4434                paging64_init_context(vcpu, context);
4435        else if (is_pae(vcpu))
4436                paging32E_init_context(vcpu, context);
4437        else
4438                paging32_init_context(vcpu, context);
4439
4440        context->base_role.nxe = is_nx(vcpu);
4441        context->base_role.cr4_pae = !!is_pae(vcpu);
4442        context->base_role.cr0_wp  = is_write_protection(vcpu);
4443        context->base_role.smep_andnot_wp
4444                = smep && !is_write_protection(vcpu);
4445        context->base_role.smap_andnot_wp
4446                = smap && !is_write_protection(vcpu);
4447        context->base_role.smm = is_smm(vcpu);
4448        reset_shadow_zero_bits_mask(vcpu, context);
4449}
4450EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4451
4452void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4453                             bool accessed_dirty)
4454{
4455        struct kvm_mmu *context = &vcpu->arch.mmu;
4456
4457        MMU_WARN_ON(VALID_PAGE(context->root_hpa));
4458
4459        context->shadow_root_level = kvm_x86_ops->get_tdp_level();
4460
4461        context->nx = true;
4462        context->ept_ad = accessed_dirty;
4463        context->page_fault = ept_page_fault;
4464        context->gva_to_gpa = ept_gva_to_gpa;
4465        context->sync_page = ept_sync_page;
4466        context->invlpg = ept_invlpg;
4467        context->update_pte = ept_update_pte;
4468        context->root_level = context->shadow_root_level;
4469        context->root_hpa = INVALID_PAGE;
4470        context->direct_map = false;
4471        context->base_role.ad_disabled = !accessed_dirty;
4472
4473        update_permission_bitmask(vcpu, context, true);
4474        update_pkru_bitmask(vcpu, context, true);
4475        update_last_nonleaf_level(vcpu, context);
4476        reset_rsvds_bits_mask_ept(vcpu, context, execonly);
4477        reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
4478}
4479EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4480
4481static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
4482{
4483        struct kvm_mmu *context = &vcpu->arch.mmu;
4484
4485        kvm_init_shadow_mmu(vcpu);
4486        context->set_cr3           = kvm_x86_ops->set_cr3;
4487        context->get_cr3           = get_cr3;
4488        context->get_pdptr         = kvm_pdptr_read;
4489        context->inject_page_fault = kvm_inject_page_fault;
4490}
4491
4492static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
4493{
4494        struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4495
4496        g_context->get_cr3           = get_cr3;
4497        g_context->get_pdptr         = kvm_pdptr_read;
4498        g_context->inject_page_fault = kvm_inject_page_fault;
4499
4500        /*
4501         * Note that arch.mmu.gva_to_gpa translates l2_gva to l1_gpa. The
4502         * translation of l2_gpa to l1_gpa addresses is done using the
4503         * arch.nested_mmu.gva_to_gpa function. Basically the gva_to_gpa
4504         * functions between mmu and nested_mmu are swapped.
4505         */
4506        if (!is_paging(vcpu)) {
4507                g_context->nx = false;
4508                g_context->root_level = 0;
4509                g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
4510        } else if (is_long_mode(vcpu)) {
4511                g_context->nx = is_nx(vcpu);
4512                g_context->root_level = PT64_ROOT_LEVEL;
4513                reset_rsvds_bits_mask(vcpu, g_context);
4514                g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4515        } else if (is_pae(vcpu)) {
4516                g_context->nx = is_nx(vcpu);
4517                g_context->root_level = PT32E_ROOT_LEVEL;
4518                reset_rsvds_bits_mask(vcpu, g_context);
4519                g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4520        } else {
4521                g_context->nx = false;
4522                g_context->root_level = PT32_ROOT_LEVEL;
4523                reset_rsvds_bits_mask(vcpu, g_context);
4524                g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
4525        }
4526
4527        update_permission_bitmask(vcpu, g_context, false);
4528        update_pkru_bitmask(vcpu, g_context, false);
4529        update_last_nonleaf_level(vcpu, g_context);
4530}
4531
4532static void init_kvm_mmu(struct kvm_vcpu *vcpu)
4533{
4534        if (mmu_is_nested(vcpu))
4535                init_kvm_nested_mmu(vcpu);
4536        else if (tdp_enabled)
4537                init_kvm_tdp_mmu(vcpu);
4538        else
4539                init_kvm_softmmu(vcpu);
4540}
4541
4542void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
4543{
4544        kvm_mmu_unload(vcpu);
4545        init_kvm_mmu(vcpu);
4546}
4547EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
4548
4549int kvm_mmu_load(struct kvm_vcpu *vcpu)
4550{
4551        int r;
4552
4553        r = mmu_topup_memory_caches(vcpu);
4554        if (r)
4555                goto out;
4556        r = mmu_alloc_roots(vcpu);
4557        kvm_mmu_sync_roots(vcpu);
4558        if (r)
4559                goto out;
4560        /* set_cr3() should ensure TLB has been flushed */
4561        vcpu->arch.mmu.set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
4562out:
4563        return r;
4564}
4565EXPORT_SYMBOL_GPL(kvm_mmu_load);
4566
4567void kvm_mmu_unload(struct kvm_vcpu *vcpu)
4568{
4569        mmu_free_roots(vcpu);
4570        WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
4571}
4572EXPORT_SYMBOL_GPL(kvm_mmu_unload);
4573
4574static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
4575                                  struct kvm_mmu_page *sp, u64 *spte,
4576                                  const void *new)
4577{
4578        if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
4579                ++vcpu->kvm->stat.mmu_pde_zapped;
4580                return;
4581        }
4582
4583        ++vcpu->kvm->stat.mmu_pte_updated;
4584        vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
4585}
4586
4587static bool need_remote_flush(u64 old, u64 new)
4588{
4589        if (!is_shadow_present_pte(old))
4590                return false;
4591        if (!is_shadow_present_pte(new))
4592                return true;
4593        if ((old ^ new) & PT64_BASE_ADDR_MASK)
4594                return true;
4595        old ^= shadow_nx_mask;
4596        new ^= shadow_nx_mask;
4597        return (old & ~new & PT64_PERM_MASK) != 0;
4598}
4599
4600static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, bool zap_page,
4601                                    bool remote_flush, bool local_flush)
4602{
4603        if (zap_page)
4604                return;
4605
4606        if (remote_flush)
4607                kvm_flush_remote_tlbs(vcpu->kvm);
4608        else if (local_flush)
4609                kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
4610}
4611
4612static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
4613                                    const u8 *new, int *bytes)
4614{
4615        u64 gentry;
4616        int r;
4617
4618        /*
4619         * Assume that the pte write on a page table of the same type
4620         * as the current vcpu paging mode since we update the sptes only
4621         * when they have the same mode.
4622         */
4623        if (is_pae(vcpu) && *bytes == 4) {
4624                /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
4625                *gpa &= ~(gpa_t)7;
4626                *bytes = 8;
4627                r = kvm_vcpu_read_guest(vcpu, *gpa, &gentry, 8);
4628                if (r)
4629                        gentry = 0;
4630                new = (const u8 *)&gentry;
4631        }
4632
4633        switch (*bytes) {
4634        case 4:
4635                gentry = *(const u32 *)new;
4636                break;
4637        case 8:
4638                gentry = *(const u64 *)new;
4639                break;
4640        default:
4641                gentry = 0;
4642                break;
4643        }
4644
4645        return gentry;
4646}
4647
4648/*
4649 * If we're seeing too many writes to a page, it may no longer be a page table,
4650 * or we may be forking, in which case it is better to unmap the page.
4651 */
4652static bool detect_write_flooding(struct kvm_mmu_page *sp)
4653{
4654        /*
4655         * Skip write-flooding detected for the sp whose level is 1, because
4656         * it can become unsync, then the guest page is not write-protected.
4657         */
4658        if (sp->role.level == PT_PAGE_TABLE_LEVEL)
4659                return false;
4660
4661        atomic_inc(&sp->write_flooding_count);
4662        return atomic_read(&sp->write_flooding_count) >= 3;
4663}
4664
4665/*
4666 * Misaligned accesses are too much trouble to fix up; also, they usually
4667 * indicate a page is not used as a page table.
4668 */
4669static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
4670                                    int bytes)
4671{
4672        unsigned offset, pte_size, misaligned;
4673
4674        pgprintk("misaligned: gpa %llx bytes %d role %x\n",
4675                 gpa, bytes, sp->role.word);
4676
4677        offset = offset_in_page(gpa);
4678        pte_size = sp->role.cr4_pae ? 8 : 4;
4679
4680        /*
4681         * Sometimes, the OS only writes the last one bytes to update status
4682         * bits, for example, in linux, andb instruction is used in clear_bit().
4683         */
4684        if (!(offset & (pte_size - 1)) && bytes == 1)
4685                return false;
4686
4687        misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
4688        misaligned |= bytes < 4;
4689
4690        return misaligned;
4691}
4692
4693static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
4694{
4695        unsigned page_offset, quadrant;
4696        u64 *spte;
4697        int level;
4698
4699        page_offset = offset_in_page(gpa);
4700        level = sp->role.level;
4701        *nspte = 1;
4702        if (!sp->role.cr4_pae) {
4703                page_offset <<= 1;      /* 32->64 */
4704                /*
4705                 * A 32-bit pde maps 4MB while the shadow pdes map
4706                 * only 2MB.  So we need to double the offset again
4707                 * and zap two pdes instead of one.
4708                 */
4709                if (level == PT32_ROOT_LEVEL) {
4710                        page_offset &= ~7; /* kill rounding error */
4711                        page_offset <<= 1;
4712                        *nspte = 2;
4713                }
4714                quadrant = page_offset >> PAGE_SHIFT;
4715                page_offset &= ~PAGE_MASK;
4716                if (quadrant != sp->role.quadrant)
4717                        return NULL;
4718        }
4719
4720        spte = &sp->spt[page_offset / sizeof(*spte)];
4721        return spte;
4722}
4723
4724static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
4725                              const u8 *new, int bytes,
4726                              struct kvm_page_track_notifier_node *node)
4727{
4728        gfn_t gfn = gpa >> PAGE_SHIFT;
4729        struct kvm_mmu_page *sp;
4730        LIST_HEAD(invalid_list);
4731        u64 entry, gentry, *spte;
4732        int npte;
4733        bool remote_flush, local_flush, zap_page;
4734        union kvm_mmu_page_role mask = { };
4735
4736        mask.cr0_wp = 1;
4737        mask.cr4_pae = 1;
4738        mask.nxe = 1;
4739        mask.smep_andnot_wp = 1;
4740        mask.smap_andnot_wp = 1;
4741        mask.smm = 1;
4742        mask.ad_disabled = 1;
4743
4744        /*
4745         * If we don't have indirect shadow pages, it means no page is
4746         * write-protected, so we can exit simply.
4747         */
4748        if (!ACCESS_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
4749                return;
4750
4751        zap_page = remote_flush = local_flush = false;
4752
4753        pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
4754
4755        gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, new, &bytes);
4756
4757        /*
4758         * No need to care whether allocation memory is successful
4759         * or not since pte prefetch is skiped if it does not have
4760         * enough objects in the cache.
4761         */
4762        mmu_topup_memory_caches(vcpu);
4763
4764        spin_lock(&vcpu->kvm->mmu_lock);
4765        ++vcpu->kvm->stat.mmu_pte_write;
4766        kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
4767
4768        for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
4769                if (detect_write_misaligned(sp, gpa, bytes) ||
4770                      detect_write_flooding(sp)) {
4771                        zap_page |= !!kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
4772                                                     &invalid_list);
4773                        ++vcpu->kvm->stat.mmu_flooded;
4774                        continue;
4775                }
4776
4777                spte = get_written_sptes(sp, gpa, &npte);
4778                if (!spte)
4779                        continue;
4780
4781                local_flush = true;
4782                while (npte--) {
4783                        entry = *spte;
4784                        mmu_page_zap_pte(vcpu->kvm, sp, spte);
4785                        if (gentry &&
4786                              !((sp->role.word ^ vcpu->arch.mmu.base_role.word)
4787                              & mask.word) && rmap_can_add(vcpu))
4788                                mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
4789                        if (need_remote_flush(entry, *spte))
4790                                remote_flush = true;
4791                        ++spte;
4792                }
4793        }
4794        mmu_pte_write_flush_tlb(vcpu, zap_page, remote_flush, local_flush);
4795        kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
4796        kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
4797        spin_unlock(&vcpu->kvm->mmu_lock);
4798}
4799
4800int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
4801{
4802        gpa_t gpa;
4803        int r;
4804
4805        if (vcpu->arch.mmu.direct_map)
4806                return 0;
4807
4808        gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
4809
4810        r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4811
4812        return r;
4813}
4814EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
4815
4816static void make_mmu_pages_available(struct kvm_vcpu *vcpu)
4817{
4818        LIST_HEAD(invalid_list);
4819
4820        if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
4821                return;
4822
4823        while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
4824                if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
4825                        break;
4826
4827                ++vcpu->kvm->stat.mmu_recycled;
4828        }
4829        kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
4830}
4831
4832int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code,
4833                       void *insn, int insn_len)
4834{
4835        int r, emulation_type = EMULTYPE_RETRY;
4836        enum emulation_result er;
4837        bool direct = vcpu->arch.mmu.direct_map || mmu_is_nested(vcpu);
4838
4839        if (unlikely(error_code & PFERR_RSVD_MASK)) {
4840                r = handle_mmio_page_fault(vcpu, cr2, direct);
4841                if (r == RET_MMIO_PF_EMULATE) {
4842                        emulation_type = 0;
4843                        goto emulate;
4844                }
4845                if (r == RET_MMIO_PF_RETRY)
4846                        return 1;
4847                if (r < 0)
4848                        return r;
4849        }
4850
4851        r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code, false);
4852        if (r < 0)
4853                return r;
4854        if (!r)
4855                return 1;
4856
4857        if (mmio_info_in_cache(vcpu, cr2, direct))
4858                emulation_type = 0;
4859emulate:
4860        er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
4861
4862        switch (er) {
4863        case EMULATE_DONE:
4864                return 1;
4865        case EMULATE_USER_EXIT:
4866                ++vcpu->stat.mmio_exits;
4867                /* fall through */
4868        case EMULATE_FAIL:
4869                return 0;
4870        default:
4871                BUG();
4872        }
4873}
4874EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
4875
4876void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
4877{
4878        vcpu->arch.mmu.invlpg(vcpu, gva);
4879        kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
4880        ++vcpu->stat.invlpg;
4881}
4882EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
4883
4884void kvm_enable_tdp(void)
4885{
4886        tdp_enabled = true;
4887}
4888EXPORT_SYMBOL_GPL(kvm_enable_tdp);
4889
4890void kvm_disable_tdp(void)
4891{
4892        tdp_enabled = false;
4893}
4894EXPORT_SYMBOL_GPL(kvm_disable_tdp);
4895
4896static void free_mmu_pages(struct kvm_vcpu *vcpu)
4897{
4898        free_page((unsigned long)vcpu->arch.mmu.pae_root);
4899        if (vcpu->arch.mmu.lm_root != NULL)
4900                free_page((unsigned long)vcpu->arch.mmu.lm_root);
4901}
4902
4903static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
4904{
4905        struct page *page;
4906        int i;
4907
4908        /*
4909         * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
4910         * Therefore we need to allocate shadow page tables in the first
4911         * 4GB of memory, which happens to fit the DMA32 zone.
4912         */
4913        page = alloc_page(GFP_KERNEL | __GFP_DMA32);
4914        if (!page)
4915                return -ENOMEM;
4916
4917        vcpu->arch.mmu.pae_root = page_address(page);
4918        for (i = 0; i < 4; ++i)
4919                vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
4920
4921        return 0;
4922}
4923
4924int kvm_mmu_create(struct kvm_vcpu *vcpu)
4925{
4926        vcpu->arch.walk_mmu = &vcpu->arch.mmu;
4927        vcpu->arch.mmu.root_hpa = INVALID_PAGE;
4928        vcpu->arch.mmu.translate_gpa = translate_gpa;
4929        vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
4930
4931        return alloc_mmu_pages(vcpu);
4932}
4933
4934void kvm_mmu_setup(struct kvm_vcpu *vcpu)
4935{
4936        MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
4937
4938        init_kvm_mmu(vcpu);
4939}
4940
4941static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
4942                        struct kvm_memory_slot *slot,
4943                        struct kvm_page_track_notifier_node *node)
4944{
4945        kvm_mmu_invalidate_zap_all_pages(kvm);
4946}
4947
4948void kvm_mmu_init_vm(struct kvm *kvm)
4949{
4950        struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
4951
4952        node->track_write = kvm_mmu_pte_write;
4953        node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
4954        kvm_page_track_register_notifier(kvm, node);
4955}
4956
4957void kvm_mmu_uninit_vm(struct kvm *kvm)
4958{
4959        struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
4960
4961        kvm_page_track_unregister_notifier(kvm, node);
4962}
4963
4964/* The return value indicates if tlb flush on all vcpus is needed. */
4965typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
4966
4967/* The caller should hold mmu-lock before calling this function. */
4968static bool
4969slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
4970                        slot_level_handler fn, int start_level, int end_level,
4971                        gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
4972{
4973        struct slot_rmap_walk_iterator iterator;
4974        bool flush = false;
4975
4976        for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
4977                        end_gfn, &iterator) {
4978                if (iterator.rmap)
4979                        flush |= fn(kvm, iterator.rmap);
4980
4981                if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
4982                        if (flush && lock_flush_tlb) {
4983                                kvm_flush_remote_tlbs(kvm);
4984                                flush = false;
4985                        }
4986                        cond_resched_lock(&kvm->mmu_lock);
4987                }
4988        }
4989
4990        if (flush && lock_flush_tlb) {
4991                kvm_flush_remote_tlbs(kvm);
4992                flush = false;
4993        }
4994
4995        return flush;
4996}
4997
4998static bool
4999slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5000                  slot_level_handler fn, int start_level, int end_level,
5001                  bool lock_flush_tlb)
5002{
5003        return slot_handle_level_range(kvm, memslot, fn, start_level,
5004                        end_level, memslot->base_gfn,
5005                        memslot->base_gfn + memslot->npages - 1,
5006                        lock_flush_tlb);
5007}
5008
5009static bool
5010slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5011                      slot_level_handler fn, bool lock_flush_tlb)
5012{
5013        return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5014                                 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5015}
5016
5017static bool
5018slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5019                        slot_level_handler fn, bool lock_flush_tlb)
5020{
5021        return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5022                                 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5023}
5024
5025static bool
5026slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5027                 slot_level_handler fn, bool lock_flush_tlb)
5028{
5029        return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5030                                 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5031}
5032
5033void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5034{
5035        struct kvm_memslots *slots;
5036        struct kvm_memory_slot *memslot;
5037        int i;
5038
5039        spin_lock(&kvm->mmu_lock);
5040        for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5041                slots = __kvm_memslots(kvm, i);
5042                kvm_for_each_memslot(memslot, slots) {
5043                        gfn_t start, end;
5044
5045                        start = max(gfn_start, memslot->base_gfn);
5046                        end = min(gfn_end, memslot->base_gfn + memslot->npages);
5047                        if (start >= end)
5048                                continue;
5049
5050                        slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5051                                                PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5052                                                start, end - 1, true);
5053                }
5054        }
5055
5056        spin_unlock(&kvm->mmu_lock);
5057}
5058
5059static bool slot_rmap_write_protect(struct kvm *kvm,
5060                                    struct kvm_rmap_head *rmap_head)
5061{
5062        return __rmap_write_protect(kvm, rmap_head, false);
5063}
5064
5065void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5066                                      struct kvm_memory_slot *memslot)
5067{
5068        bool flush;
5069
5070        spin_lock(&kvm->mmu_lock);
5071        flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5072                                      false);
5073        spin_unlock(&kvm->mmu_lock);
5074
5075        /*
5076         * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5077         * which do tlb flush out of mmu-lock should be serialized by
5078         * kvm->slots_lock otherwise tlb flush would be missed.
5079         */
5080        lockdep_assert_held(&kvm->slots_lock);
5081
5082        /*
5083         * We can flush all the TLBs out of the mmu lock without TLB
5084         * corruption since we just change the spte from writable to
5085         * readonly so that we only need to care the case of changing
5086         * spte from present to present (changing the spte from present
5087         * to nonpresent will flush all the TLBs immediately), in other
5088         * words, the only case we care is mmu_spte_update() where we
5089         * haved checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5090         * instead of PT_WRITABLE_MASK, that means it does not depend
5091         * on PT_WRITABLE_MASK anymore.
5092         */
5093        if (flush)
5094                kvm_flush_remote_tlbs(kvm);
5095}
5096
5097static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5098                                         struct kvm_rmap_head *rmap_head)
5099{
5100        u64 *sptep;
5101        struct rmap_iterator iter;
5102        int need_tlb_flush = 0;
5103        kvm_pfn_t pfn;
5104        struct kvm_mmu_page *sp;
5105
5106restart:
5107        for_each_rmap_spte(rmap_head, &iter, sptep) {
5108                sp = page_header(__pa(sptep));
5109                pfn = spte_to_pfn(*sptep);
5110
5111                /*
5112                 * We cannot do huge page mapping for indirect shadow pages,
5113                 * which are found on the last rmap (level = 1) when not using
5114                 * tdp; such shadow pages are synced with the page table in
5115                 * the guest, and the guest page table is using 4K page size
5116                 * mapping if the indirect sp has level = 1.
5117                 */
5118                if (sp->role.direct &&
5119                        !kvm_is_reserved_pfn(pfn) &&
5120                        PageTransCompound(pfn_to_page(pfn))) {
5121                        drop_spte(kvm, sptep);
5122                        need_tlb_flush = 1;
5123                        goto restart;
5124                }
5125        }
5126
5127        return need_tlb_flush;
5128}
5129
5130void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5131                                   const struct kvm_memory_slot *memslot)
5132{
5133        /* FIXME: const-ify all uses of struct kvm_memory_slot.  */
5134        spin_lock(&kvm->mmu_lock);
5135        slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5136                         kvm_mmu_zap_collapsible_spte, true);
5137        spin_unlock(&kvm->mmu_lock);
5138}
5139
5140void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5141                                   struct kvm_memory_slot *memslot)
5142{
5143        bool flush;
5144
5145        spin_lock(&kvm->mmu_lock);
5146        flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5147        spin_unlock(&kvm->mmu_lock);
5148
5149        lockdep_assert_held(&kvm->slots_lock);
5150
5151        /*
5152         * It's also safe to flush TLBs out of mmu lock here as currently this
5153         * function is only used for dirty logging, in which case flushing TLB
5154         * out of mmu lock also guarantees no dirty pages will be lost in
5155         * dirty_bitmap.
5156         */
5157        if (flush)
5158                kvm_flush_remote_tlbs(kvm);
5159}
5160EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5161
5162void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5163                                        struct kvm_memory_slot *memslot)
5164{
5165        bool flush;
5166
5167        spin_lock(&kvm->mmu_lock);
5168        flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5169                                        false);
5170        spin_unlock(&kvm->mmu_lock);
5171
5172        /* see kvm_mmu_slot_remove_write_access */
5173        lockdep_assert_held(&kvm->slots_lock);
5174
5175        if (flush)
5176                kvm_flush_remote_tlbs(kvm);
5177}
5178EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5179
5180void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5181                            struct kvm_memory_slot *memslot)
5182{
5183        bool flush;
5184
5185        spin_lock(&kvm->mmu_lock);
5186        flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5187        spin_unlock(&kvm->mmu_lock);
5188
5189        lockdep_assert_held(&kvm->slots_lock);
5190
5191        /* see kvm_mmu_slot_leaf_clear_dirty */
5192        if (flush)
5193                kvm_flush_remote_tlbs(kvm);
5194}
5195EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5196
5197#define BATCH_ZAP_PAGES 10
5198static void kvm_zap_obsolete_pages(struct kvm *kvm)
5199{
5200        struct kvm_mmu_page *sp, *node;
5201        int batch = 0;
5202
5203restart:
5204        list_for_each_entry_safe_reverse(sp, node,
5205              &kvm->arch.active_mmu_pages, link) {
5206                int ret;
5207
5208                /*
5209                 * No obsolete page exists before new created page since
5210                 * active_mmu_pages is the FIFO list.
5211                 */
5212                if (!is_obsolete_sp(kvm, sp))
5213                        break;
5214
5215                /*
5216                 * Since we are reversely walking the list and the invalid
5217                 * list will be moved to the head, skip the invalid page
5218                 * can help us to avoid the infinity list walking.
5219                 */
5220                if (sp->role.invalid)
5221                        continue;
5222
5223                /*
5224                 * Need not flush tlb since we only zap the sp with invalid
5225                 * generation number.
5226                 */
5227                if (batch >= BATCH_ZAP_PAGES &&
5228                      cond_resched_lock(&kvm->mmu_lock)) {
5229                        batch = 0;
5230                        goto restart;
5231                }
5232
5233                ret = kvm_mmu_prepare_zap_page(kvm, sp,
5234                                &kvm->arch.zapped_obsolete_pages);
5235                batch += ret;
5236
5237                if (ret)
5238                        goto restart;
5239        }
5240
5241        /*
5242         * Should flush tlb before free page tables since lockless-walking
5243         * may use the pages.
5244         */
5245        kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5246}
5247
5248/*
5249 * Fast invalidate all shadow pages and use lock-break technique
5250 * to zap obsolete pages.
5251 *
5252 * It's required when memslot is being deleted or VM is being
5253 * destroyed, in these cases, we should ensure that KVM MMU does
5254 * not use any resource of the being-deleted slot or all slots
5255 * after calling the function.
5256 */
5257void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
5258{
5259        spin_lock(&kvm->mmu_lock);
5260        trace_kvm_mmu_invalidate_zap_all_pages(kvm);
5261        kvm->arch.mmu_valid_gen++;
5262
5263        /*
5264         * Notify all vcpus to reload its shadow page table
5265         * and flush TLB. Then all vcpus will switch to new
5266         * shadow page table with the new mmu_valid_gen.
5267         *
5268         * Note: we should do this under the protection of
5269         * mmu-lock, otherwise, vcpu would purge shadow page
5270         * but miss tlb flush.
5271         */
5272        kvm_reload_remote_mmus(kvm);
5273
5274        kvm_zap_obsolete_pages(kvm);
5275        spin_unlock(&kvm->mmu_lock);
5276}
5277
5278static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5279{
5280        return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5281}
5282
5283void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, struct kvm_memslots *slots)
5284{
5285        /*
5286         * The very rare case: if the generation-number is round,
5287         * zap all shadow pages.
5288         */
5289        if (unlikely((slots->generation & MMIO_GEN_MASK) == 0)) {
5290                kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5291                kvm_mmu_invalidate_zap_all_pages(kvm);
5292        }
5293}
5294
5295static int mmu_shrink(struct shrinker *shrink, struct shrink_control *sc)
5296{
5297        struct kvm *kvm;
5298        int nr_to_scan = sc->nr_to_scan;
5299
5300        if (nr_to_scan == 0)
5301                goto out;
5302
5303        spin_lock(&kvm_lock);
5304
5305        list_for_each_entry(kvm, &vm_list, vm_list) {
5306                int idx;
5307                LIST_HEAD(invalid_list);
5308
5309                /*
5310                 * Never scan more than sc->nr_to_scan VM instances.
5311                 * Will not hit this condition practically since we do not try
5312                 * to shrink more than one VM and it is very unlikely to see
5313                 * !n_used_mmu_pages so many times.
5314                 */
5315                if (!nr_to_scan--)
5316                        break;
5317                /*
5318                 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5319                 * here. We may skip a VM instance errorneosly, but we do not
5320                 * want to shrink a VM that only started to populate its MMU
5321                 * anyway.
5322                 */
5323                if (!kvm->arch.n_used_mmu_pages &&
5324                      !kvm_has_zapped_obsolete_pages(kvm))
5325                        continue;
5326
5327                idx = srcu_read_lock(&kvm->srcu);
5328                spin_lock(&kvm->mmu_lock);
5329
5330                if (kvm_has_zapped_obsolete_pages(kvm)) {
5331                        kvm_mmu_commit_zap_page(kvm,
5332                              &kvm->arch.zapped_obsolete_pages);
5333                        goto unlock;
5334                }
5335
5336                prepare_zap_oldest_mmu_page(kvm, &invalid_list);
5337                kvm_mmu_commit_zap_page(kvm, &invalid_list);
5338
5339unlock:
5340                spin_unlock(&kvm->mmu_lock);
5341                srcu_read_unlock(&kvm->srcu, idx);
5342
5343                list_move_tail(&kvm->vm_list, &vm_list);
5344                break;
5345        }
5346
5347        spin_unlock(&kvm_lock);
5348
5349out:
5350        return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
5351}
5352
5353static struct shrinker mmu_shrinker = {
5354        .shrink = mmu_shrink,
5355        .seeks = DEFAULT_SEEKS * 10,
5356};
5357
5358static void mmu_destroy_caches(void)
5359{
5360        if (pte_list_desc_cache)
5361                kmem_cache_destroy(pte_list_desc_cache);
5362        if (mmu_page_header_cache)
5363                kmem_cache_destroy(mmu_page_header_cache);
5364}
5365
5366int kvm_mmu_module_init(void)
5367{
5368        kvm_mmu_clear_all_pte_masks();
5369
5370        pte_list_desc_cache = kmem_cache_create("pte_list_desc",
5371                                            sizeof(struct pte_list_desc),
5372                                            0, 0, NULL);
5373        if (!pte_list_desc_cache)
5374                goto nomem;
5375
5376        mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
5377                                                  sizeof(struct kvm_mmu_page),
5378                                                  0, 0, NULL);
5379        if (!mmu_page_header_cache)
5380                goto nomem;
5381
5382        if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
5383                goto nomem;
5384
5385        register_shrinker(&mmu_shrinker);
5386
5387        return 0;
5388
5389nomem:
5390        mmu_destroy_caches();
5391        return -ENOMEM;
5392}
5393
5394/*
5395 * Caculate mmu pages needed for kvm.
5396 */
5397unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
5398{
5399        unsigned int nr_mmu_pages;
5400        unsigned int  nr_pages = 0;
5401        struct kvm_memslots *slots;
5402        struct kvm_memory_slot *memslot;
5403        int i;
5404
5405        for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5406                slots = __kvm_memslots(kvm, i);
5407
5408                kvm_for_each_memslot(memslot, slots)
5409                        nr_pages += memslot->npages;
5410        }
5411
5412        nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
5413        nr_mmu_pages = max(nr_mmu_pages,
5414                           (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
5415
5416        return nr_mmu_pages;
5417}
5418
5419void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
5420{
5421        kvm_mmu_unload(vcpu);
5422        free_mmu_pages(vcpu);
5423        mmu_free_memory_caches(vcpu);
5424}
5425
5426void kvm_mmu_module_exit(void)
5427{
5428        mmu_destroy_caches();
5429        percpu_counter_destroy(&kvm_total_used_mmu_pages);
5430        unregister_shrinker(&mmu_shrinker);
5431        mmu_audit_disable();
5432}
5433