8f12ec52ad8601ed4b657f5f6858e27f2f40fc09
[sfrench/cifs-2.6.git] / arch / x86 / kvm / mmu.c
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  *
11  * Authors:
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *   Avi Kivity   <avi@qumranet.com>
14  *
15  * This work is licensed under the terms of the GNU GPL, version 2.  See
16  * the COPYING file in the top-level directory.
17  *
18  */
19
20 #include "vmx.h"
21 #include "mmu.h"
22
23 #include <linux/kvm_host.h>
24 #include <linux/types.h>
25 #include <linux/string.h>
26 #include <linux/mm.h>
27 #include <linux/highmem.h>
28 #include <linux/module.h>
29 #include <linux/swap.h>
30
31 #include <asm/page.h>
32 #include <asm/cmpxchg.h>
33 #include <asm/io.h>
34
35 #undef MMU_DEBUG
36
37 #undef AUDIT
38
39 #ifdef AUDIT
40 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg);
41 #else
42 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg) {}
43 #endif
44
45 #ifdef MMU_DEBUG
46
47 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
48 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
49
50 #else
51
52 #define pgprintk(x...) do { } while (0)
53 #define rmap_printk(x...) do { } while (0)
54
55 #endif
56
57 #if defined(MMU_DEBUG) || defined(AUDIT)
58 static int dbg = 1;
59 #endif
60
61 #ifndef MMU_DEBUG
62 #define ASSERT(x) do { } while (0)
63 #else
64 #define ASSERT(x)                                                       \
65         if (!(x)) {                                                     \
66                 printk(KERN_WARNING "assertion failed %s:%d: %s\n",     \
67                        __FILE__, __LINE__, #x);                         \
68         }
69 #endif
70
71 #define PT64_PT_BITS 9
72 #define PT64_ENT_PER_PAGE (1 << PT64_PT_BITS)
73 #define PT32_PT_BITS 10
74 #define PT32_ENT_PER_PAGE (1 << PT32_PT_BITS)
75
76 #define PT_WRITABLE_SHIFT 1
77
78 #define PT_PRESENT_MASK (1ULL << 0)
79 #define PT_WRITABLE_MASK (1ULL << PT_WRITABLE_SHIFT)
80 #define PT_USER_MASK (1ULL << 2)
81 #define PT_PWT_MASK (1ULL << 3)
82 #define PT_PCD_MASK (1ULL << 4)
83 #define PT_ACCESSED_MASK (1ULL << 5)
84 #define PT_DIRTY_MASK (1ULL << 6)
85 #define PT_PAGE_SIZE_MASK (1ULL << 7)
86 #define PT_PAT_MASK (1ULL << 7)
87 #define PT_GLOBAL_MASK (1ULL << 8)
88 #define PT64_NX_SHIFT 63
89 #define PT64_NX_MASK (1ULL << PT64_NX_SHIFT)
90
91 #define PT_PAT_SHIFT 7
92 #define PT_DIR_PAT_SHIFT 12
93 #define PT_DIR_PAT_MASK (1ULL << PT_DIR_PAT_SHIFT)
94
95 #define PT32_DIR_PSE36_SIZE 4
96 #define PT32_DIR_PSE36_SHIFT 13
97 #define PT32_DIR_PSE36_MASK \
98         (((1ULL << PT32_DIR_PSE36_SIZE) - 1) << PT32_DIR_PSE36_SHIFT)
99
100
101 #define PT_FIRST_AVAIL_BITS_SHIFT 9
102 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
103
104 #define PT_SHADOW_IO_MARK (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
105
106 #define VALID_PAGE(x) ((x) != INVALID_PAGE)
107
108 #define PT64_LEVEL_BITS 9
109
110 #define PT64_LEVEL_SHIFT(level) \
111                 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
112
113 #define PT64_LEVEL_MASK(level) \
114                 (((1ULL << PT64_LEVEL_BITS) - 1) << PT64_LEVEL_SHIFT(level))
115
116 #define PT64_INDEX(address, level)\
117         (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
118
119
120 #define PT32_LEVEL_BITS 10
121
122 #define PT32_LEVEL_SHIFT(level) \
123                 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
124
125 #define PT32_LEVEL_MASK(level) \
126                 (((1ULL << PT32_LEVEL_BITS) - 1) << PT32_LEVEL_SHIFT(level))
127
128 #define PT32_INDEX(address, level)\
129         (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
130
131
132 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
133 #define PT64_DIR_BASE_ADDR_MASK \
134         (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
135
136 #define PT32_BASE_ADDR_MASK PAGE_MASK
137 #define PT32_DIR_BASE_ADDR_MASK \
138         (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
139
140 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK \
141                         | PT64_NX_MASK)
142
143 #define PFERR_PRESENT_MASK (1U << 0)
144 #define PFERR_WRITE_MASK (1U << 1)
145 #define PFERR_USER_MASK (1U << 2)
146 #define PFERR_FETCH_MASK (1U << 4)
147
148 #define PT64_ROOT_LEVEL 4
149 #define PT32_ROOT_LEVEL 2
150 #define PT32E_ROOT_LEVEL 3
151
152 #define PT_DIRECTORY_LEVEL 2
153 #define PT_PAGE_TABLE_LEVEL 1
154
155 #define RMAP_EXT 4
156
157 #define ACC_EXEC_MASK    1
158 #define ACC_WRITE_MASK   PT_WRITABLE_MASK
159 #define ACC_USER_MASK    PT_USER_MASK
160 #define ACC_ALL          (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
161
162 struct kvm_rmap_desc {
163         u64 *shadow_ptes[RMAP_EXT];
164         struct kvm_rmap_desc *more;
165 };
166
167 static struct kmem_cache *pte_chain_cache;
168 static struct kmem_cache *rmap_desc_cache;
169 static struct kmem_cache *mmu_page_header_cache;
170
171 static u64 __read_mostly shadow_trap_nonpresent_pte;
172 static u64 __read_mostly shadow_notrap_nonpresent_pte;
173
174 void kvm_mmu_set_nonpresent_ptes(u64 trap_pte, u64 notrap_pte)
175 {
176         shadow_trap_nonpresent_pte = trap_pte;
177         shadow_notrap_nonpresent_pte = notrap_pte;
178 }
179 EXPORT_SYMBOL_GPL(kvm_mmu_set_nonpresent_ptes);
180
181 static int is_write_protection(struct kvm_vcpu *vcpu)
182 {
183         return vcpu->arch.cr0 & X86_CR0_WP;
184 }
185
186 static int is_cpuid_PSE36(void)
187 {
188         return 1;
189 }
190
191 static int is_nx(struct kvm_vcpu *vcpu)
192 {
193         return vcpu->arch.shadow_efer & EFER_NX;
194 }
195
196 static int is_present_pte(unsigned long pte)
197 {
198         return pte & PT_PRESENT_MASK;
199 }
200
201 static int is_shadow_present_pte(u64 pte)
202 {
203         pte &= ~PT_SHADOW_IO_MARK;
204         return pte != shadow_trap_nonpresent_pte
205                 && pte != shadow_notrap_nonpresent_pte;
206 }
207
208 static int is_writeble_pte(unsigned long pte)
209 {
210         return pte & PT_WRITABLE_MASK;
211 }
212
213 static int is_dirty_pte(unsigned long pte)
214 {
215         return pte & PT_DIRTY_MASK;
216 }
217
218 static int is_io_pte(unsigned long pte)
219 {
220         return pte & PT_SHADOW_IO_MARK;
221 }
222
223 static int is_rmap_pte(u64 pte)
224 {
225         return pte != shadow_trap_nonpresent_pte
226                 && pte != shadow_notrap_nonpresent_pte;
227 }
228
229 static gfn_t pse36_gfn_delta(u32 gpte)
230 {
231         int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
232
233         return (gpte & PT32_DIR_PSE36_MASK) << shift;
234 }
235
236 static void set_shadow_pte(u64 *sptep, u64 spte)
237 {
238 #ifdef CONFIG_X86_64
239         set_64bit((unsigned long *)sptep, spte);
240 #else
241         set_64bit((unsigned long long *)sptep, spte);
242 #endif
243 }
244
245 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
246                                   struct kmem_cache *base_cache, int min)
247 {
248         void *obj;
249
250         if (cache->nobjs >= min)
251                 return 0;
252         while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
253                 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
254                 if (!obj)
255                         return -ENOMEM;
256                 cache->objects[cache->nobjs++] = obj;
257         }
258         return 0;
259 }
260
261 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
262 {
263         while (mc->nobjs)
264                 kfree(mc->objects[--mc->nobjs]);
265 }
266
267 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
268                                        int min)
269 {
270         struct page *page;
271
272         if (cache->nobjs >= min)
273                 return 0;
274         while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
275                 page = alloc_page(GFP_KERNEL);
276                 if (!page)
277                         return -ENOMEM;
278                 set_page_private(page, 0);
279                 cache->objects[cache->nobjs++] = page_address(page);
280         }
281         return 0;
282 }
283
284 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
285 {
286         while (mc->nobjs)
287                 free_page((unsigned long)mc->objects[--mc->nobjs]);
288 }
289
290 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
291 {
292         int r;
293
294         kvm_mmu_free_some_pages(vcpu);
295         r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_chain_cache,
296                                    pte_chain_cache, 4);
297         if (r)
298                 goto out;
299         r = mmu_topup_memory_cache(&vcpu->arch.mmu_rmap_desc_cache,
300                                    rmap_desc_cache, 1);
301         if (r)
302                 goto out;
303         r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
304         if (r)
305                 goto out;
306         r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
307                                    mmu_page_header_cache, 4);
308 out:
309         return r;
310 }
311
312 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
313 {
314         mmu_free_memory_cache(&vcpu->arch.mmu_pte_chain_cache);
315         mmu_free_memory_cache(&vcpu->arch.mmu_rmap_desc_cache);
316         mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
317         mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
318 }
319
320 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc,
321                                     size_t size)
322 {
323         void *p;
324
325         BUG_ON(!mc->nobjs);
326         p = mc->objects[--mc->nobjs];
327         memset(p, 0, size);
328         return p;
329 }
330
331 static struct kvm_pte_chain *mmu_alloc_pte_chain(struct kvm_vcpu *vcpu)
332 {
333         return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_chain_cache,
334                                       sizeof(struct kvm_pte_chain));
335 }
336
337 static void mmu_free_pte_chain(struct kvm_pte_chain *pc)
338 {
339         kfree(pc);
340 }
341
342 static struct kvm_rmap_desc *mmu_alloc_rmap_desc(struct kvm_vcpu *vcpu)
343 {
344         return mmu_memory_cache_alloc(&vcpu->arch.mmu_rmap_desc_cache,
345                                       sizeof(struct kvm_rmap_desc));
346 }
347
348 static void mmu_free_rmap_desc(struct kvm_rmap_desc *rd)
349 {
350         kfree(rd);
351 }
352
353 /*
354  * Take gfn and return the reverse mapping to it.
355  * Note: gfn must be unaliased before this function get called
356  */
357
358 static unsigned long *gfn_to_rmap(struct kvm *kvm, gfn_t gfn)
359 {
360         struct kvm_memory_slot *slot;
361
362         slot = gfn_to_memslot(kvm, gfn);
363         return &slot->rmap[gfn - slot->base_gfn];
364 }
365
366 /*
367  * Reverse mapping data structures:
368  *
369  * If rmapp bit zero is zero, then rmapp point to the shadw page table entry
370  * that points to page_address(page).
371  *
372  * If rmapp bit zero is one, (then rmap & ~1) points to a struct kvm_rmap_desc
373  * containing more mappings.
374  */
375 static void rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
376 {
377         struct kvm_mmu_page *sp;
378         struct kvm_rmap_desc *desc;
379         unsigned long *rmapp;
380         int i;
381
382         if (!is_rmap_pte(*spte))
383                 return;
384         gfn = unalias_gfn(vcpu->kvm, gfn);
385         sp = page_header(__pa(spte));
386         sp->gfns[spte - sp->spt] = gfn;
387         rmapp = gfn_to_rmap(vcpu->kvm, gfn);
388         if (!*rmapp) {
389                 rmap_printk("rmap_add: %p %llx 0->1\n", spte, *spte);
390                 *rmapp = (unsigned long)spte;
391         } else if (!(*rmapp & 1)) {
392                 rmap_printk("rmap_add: %p %llx 1->many\n", spte, *spte);
393                 desc = mmu_alloc_rmap_desc(vcpu);
394                 desc->shadow_ptes[0] = (u64 *)*rmapp;
395                 desc->shadow_ptes[1] = spte;
396                 *rmapp = (unsigned long)desc | 1;
397         } else {
398                 rmap_printk("rmap_add: %p %llx many->many\n", spte, *spte);
399                 desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
400                 while (desc->shadow_ptes[RMAP_EXT-1] && desc->more)
401                         desc = desc->more;
402                 if (desc->shadow_ptes[RMAP_EXT-1]) {
403                         desc->more = mmu_alloc_rmap_desc(vcpu);
404                         desc = desc->more;
405                 }
406                 for (i = 0; desc->shadow_ptes[i]; ++i)
407                         ;
408                 desc->shadow_ptes[i] = spte;
409         }
410 }
411
412 static void rmap_desc_remove_entry(unsigned long *rmapp,
413                                    struct kvm_rmap_desc *desc,
414                                    int i,
415                                    struct kvm_rmap_desc *prev_desc)
416 {
417         int j;
418
419         for (j = RMAP_EXT - 1; !desc->shadow_ptes[j] && j > i; --j)
420                 ;
421         desc->shadow_ptes[i] = desc->shadow_ptes[j];
422         desc->shadow_ptes[j] = NULL;
423         if (j != 0)
424                 return;
425         if (!prev_desc && !desc->more)
426                 *rmapp = (unsigned long)desc->shadow_ptes[0];
427         else
428                 if (prev_desc)
429                         prev_desc->more = desc->more;
430                 else
431                         *rmapp = (unsigned long)desc->more | 1;
432         mmu_free_rmap_desc(desc);
433 }
434
435 static void rmap_remove(struct kvm *kvm, u64 *spte)
436 {
437         struct kvm_rmap_desc *desc;
438         struct kvm_rmap_desc *prev_desc;
439         struct kvm_mmu_page *sp;
440         struct page *page;
441         unsigned long *rmapp;
442         int i;
443
444         if (!is_rmap_pte(*spte))
445                 return;
446         sp = page_header(__pa(spte));
447         page = pfn_to_page((*spte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT);
448         mark_page_accessed(page);
449         if (is_writeble_pte(*spte))
450                 kvm_release_page_dirty(page);
451         else
452                 kvm_release_page_clean(page);
453         rmapp = gfn_to_rmap(kvm, sp->gfns[spte - sp->spt]);
454         if (!*rmapp) {
455                 printk(KERN_ERR "rmap_remove: %p %llx 0->BUG\n", spte, *spte);
456                 BUG();
457         } else if (!(*rmapp & 1)) {
458                 rmap_printk("rmap_remove:  %p %llx 1->0\n", spte, *spte);
459                 if ((u64 *)*rmapp != spte) {
460                         printk(KERN_ERR "rmap_remove:  %p %llx 1->BUG\n",
461                                spte, *spte);
462                         BUG();
463                 }
464                 *rmapp = 0;
465         } else {
466                 rmap_printk("rmap_remove:  %p %llx many->many\n", spte, *spte);
467                 desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
468                 prev_desc = NULL;
469                 while (desc) {
470                         for (i = 0; i < RMAP_EXT && desc->shadow_ptes[i]; ++i)
471                                 if (desc->shadow_ptes[i] == spte) {
472                                         rmap_desc_remove_entry(rmapp,
473                                                                desc, i,
474                                                                prev_desc);
475                                         return;
476                                 }
477                         prev_desc = desc;
478                         desc = desc->more;
479                 }
480                 BUG();
481         }
482 }
483
484 static u64 *rmap_next(struct kvm *kvm, unsigned long *rmapp, u64 *spte)
485 {
486         struct kvm_rmap_desc *desc;
487         struct kvm_rmap_desc *prev_desc;
488         u64 *prev_spte;
489         int i;
490
491         if (!*rmapp)
492                 return NULL;
493         else if (!(*rmapp & 1)) {
494                 if (!spte)
495                         return (u64 *)*rmapp;
496                 return NULL;
497         }
498         desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
499         prev_desc = NULL;
500         prev_spte = NULL;
501         while (desc) {
502                 for (i = 0; i < RMAP_EXT && desc->shadow_ptes[i]; ++i) {
503                         if (prev_spte == spte)
504                                 return desc->shadow_ptes[i];
505                         prev_spte = desc->shadow_ptes[i];
506                 }
507                 desc = desc->more;
508         }
509         return NULL;
510 }
511
512 static void rmap_write_protect(struct kvm *kvm, u64 gfn)
513 {
514         unsigned long *rmapp;
515         u64 *spte;
516         int write_protected = 0;
517
518         gfn = unalias_gfn(kvm, gfn);
519         rmapp = gfn_to_rmap(kvm, gfn);
520
521         spte = rmap_next(kvm, rmapp, NULL);
522         while (spte) {
523                 BUG_ON(!spte);
524                 BUG_ON(!(*spte & PT_PRESENT_MASK));
525                 rmap_printk("rmap_write_protect: spte %p %llx\n", spte, *spte);
526                 if (is_writeble_pte(*spte)) {
527                         set_shadow_pte(spte, *spte & ~PT_WRITABLE_MASK);
528                         write_protected = 1;
529                 }
530                 spte = rmap_next(kvm, rmapp, spte);
531         }
532         if (write_protected)
533                 kvm_flush_remote_tlbs(kvm);
534 }
535
536 #ifdef MMU_DEBUG
537 static int is_empty_shadow_page(u64 *spt)
538 {
539         u64 *pos;
540         u64 *end;
541
542         for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
543                 if ((*pos & ~PT_SHADOW_IO_MARK) != shadow_trap_nonpresent_pte) {
544                         printk(KERN_ERR "%s: %p %llx\n", __FUNCTION__,
545                                pos, *pos);
546                         return 0;
547                 }
548         return 1;
549 }
550 #endif
551
552 static void kvm_mmu_free_page(struct kvm *kvm, struct kvm_mmu_page *sp)
553 {
554         ASSERT(is_empty_shadow_page(sp->spt));
555         list_del(&sp->link);
556         __free_page(virt_to_page(sp->spt));
557         __free_page(virt_to_page(sp->gfns));
558         kfree(sp);
559         ++kvm->arch.n_free_mmu_pages;
560 }
561
562 static unsigned kvm_page_table_hashfn(gfn_t gfn)
563 {
564         return gfn;
565 }
566
567 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu,
568                                                u64 *parent_pte)
569 {
570         struct kvm_mmu_page *sp;
571
572         if (!vcpu->kvm->arch.n_free_mmu_pages)
573                 return NULL;
574
575         sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache, sizeof *sp);
576         sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
577         sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
578         set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
579         list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
580         ASSERT(is_empty_shadow_page(sp->spt));
581         sp->slot_bitmap = 0;
582         sp->multimapped = 0;
583         sp->parent_pte = parent_pte;
584         --vcpu->kvm->arch.n_free_mmu_pages;
585         return sp;
586 }
587
588 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
589                                     struct kvm_mmu_page *sp, u64 *parent_pte)
590 {
591         struct kvm_pte_chain *pte_chain;
592         struct hlist_node *node;
593         int i;
594
595         if (!parent_pte)
596                 return;
597         if (!sp->multimapped) {
598                 u64 *old = sp->parent_pte;
599
600                 if (!old) {
601                         sp->parent_pte = parent_pte;
602                         return;
603                 }
604                 sp->multimapped = 1;
605                 pte_chain = mmu_alloc_pte_chain(vcpu);
606                 INIT_HLIST_HEAD(&sp->parent_ptes);
607                 hlist_add_head(&pte_chain->link, &sp->parent_ptes);
608                 pte_chain->parent_ptes[0] = old;
609         }
610         hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link) {
611                 if (pte_chain->parent_ptes[NR_PTE_CHAIN_ENTRIES-1])
612                         continue;
613                 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i)
614                         if (!pte_chain->parent_ptes[i]) {
615                                 pte_chain->parent_ptes[i] = parent_pte;
616                                 return;
617                         }
618         }
619         pte_chain = mmu_alloc_pte_chain(vcpu);
620         BUG_ON(!pte_chain);
621         hlist_add_head(&pte_chain->link, &sp->parent_ptes);
622         pte_chain->parent_ptes[0] = parent_pte;
623 }
624
625 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
626                                        u64 *parent_pte)
627 {
628         struct kvm_pte_chain *pte_chain;
629         struct hlist_node *node;
630         int i;
631
632         if (!sp->multimapped) {
633                 BUG_ON(sp->parent_pte != parent_pte);
634                 sp->parent_pte = NULL;
635                 return;
636         }
637         hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
638                 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
639                         if (!pte_chain->parent_ptes[i])
640                                 break;
641                         if (pte_chain->parent_ptes[i] != parent_pte)
642                                 continue;
643                         while (i + 1 < NR_PTE_CHAIN_ENTRIES
644                                 && pte_chain->parent_ptes[i + 1]) {
645                                 pte_chain->parent_ptes[i]
646                                         = pte_chain->parent_ptes[i + 1];
647                                 ++i;
648                         }
649                         pte_chain->parent_ptes[i] = NULL;
650                         if (i == 0) {
651                                 hlist_del(&pte_chain->link);
652                                 mmu_free_pte_chain(pte_chain);
653                                 if (hlist_empty(&sp->parent_ptes)) {
654                                         sp->multimapped = 0;
655                                         sp->parent_pte = NULL;
656                                 }
657                         }
658                         return;
659                 }
660         BUG();
661 }
662
663 static struct kvm_mmu_page *kvm_mmu_lookup_page(struct kvm *kvm, gfn_t gfn)
664 {
665         unsigned index;
666         struct hlist_head *bucket;
667         struct kvm_mmu_page *sp;
668         struct hlist_node *node;
669
670         pgprintk("%s: looking for gfn %lx\n", __FUNCTION__, gfn);
671         index = kvm_page_table_hashfn(gfn) % KVM_NUM_MMU_PAGES;
672         bucket = &kvm->arch.mmu_page_hash[index];
673         hlist_for_each_entry(sp, node, bucket, hash_link)
674                 if (sp->gfn == gfn && !sp->role.metaphysical) {
675                         pgprintk("%s: found role %x\n",
676                                  __FUNCTION__, sp->role.word);
677                         return sp;
678                 }
679         return NULL;
680 }
681
682 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
683                                              gfn_t gfn,
684                                              gva_t gaddr,
685                                              unsigned level,
686                                              int metaphysical,
687                                              unsigned access,
688                                              u64 *parent_pte,
689                                              bool *new_page)
690 {
691         union kvm_mmu_page_role role;
692         unsigned index;
693         unsigned quadrant;
694         struct hlist_head *bucket;
695         struct kvm_mmu_page *sp;
696         struct hlist_node *node;
697
698         role.word = 0;
699         role.glevels = vcpu->arch.mmu.root_level;
700         role.level = level;
701         role.metaphysical = metaphysical;
702         role.access = access;
703         if (vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
704                 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
705                 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
706                 role.quadrant = quadrant;
707         }
708         pgprintk("%s: looking gfn %lx role %x\n", __FUNCTION__,
709                  gfn, role.word);
710         index = kvm_page_table_hashfn(gfn) % KVM_NUM_MMU_PAGES;
711         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
712         hlist_for_each_entry(sp, node, bucket, hash_link)
713                 if (sp->gfn == gfn && sp->role.word == role.word) {
714                         mmu_page_add_parent_pte(vcpu, sp, parent_pte);
715                         pgprintk("%s: found\n", __FUNCTION__);
716                         return sp;
717                 }
718         ++vcpu->kvm->stat.mmu_cache_miss;
719         sp = kvm_mmu_alloc_page(vcpu, parent_pte);
720         if (!sp)
721                 return sp;
722         pgprintk("%s: adding gfn %lx role %x\n", __FUNCTION__, gfn, role.word);
723         sp->gfn = gfn;
724         sp->role = role;
725         hlist_add_head(&sp->hash_link, bucket);
726         vcpu->arch.mmu.prefetch_page(vcpu, sp);
727         if (!metaphysical)
728                 rmap_write_protect(vcpu->kvm, gfn);
729         if (new_page)
730                 *new_page = 1;
731         return sp;
732 }
733
734 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
735                                          struct kvm_mmu_page *sp)
736 {
737         unsigned i;
738         u64 *pt;
739         u64 ent;
740
741         pt = sp->spt;
742
743         if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
744                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
745                         if (is_shadow_present_pte(pt[i]))
746                                 rmap_remove(kvm, &pt[i]);
747                         pt[i] = shadow_trap_nonpresent_pte;
748                 }
749                 kvm_flush_remote_tlbs(kvm);
750                 return;
751         }
752
753         for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
754                 ent = pt[i];
755
756                 pt[i] = shadow_trap_nonpresent_pte;
757                 if (!is_shadow_present_pte(ent))
758                         continue;
759                 ent &= PT64_BASE_ADDR_MASK;
760                 mmu_page_remove_parent_pte(page_header(ent), &pt[i]);
761         }
762         kvm_flush_remote_tlbs(kvm);
763 }
764
765 static void kvm_mmu_put_page(struct kvm_mmu_page *sp, u64 *parent_pte)
766 {
767         mmu_page_remove_parent_pte(sp, parent_pte);
768 }
769
770 static void kvm_mmu_reset_last_pte_updated(struct kvm *kvm)
771 {
772         int i;
773
774         for (i = 0; i < KVM_MAX_VCPUS; ++i)
775                 if (kvm->vcpus[i])
776                         kvm->vcpus[i]->arch.last_pte_updated = NULL;
777 }
778
779 static void kvm_mmu_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp)
780 {
781         u64 *parent_pte;
782
783         ++kvm->stat.mmu_shadow_zapped;
784         while (sp->multimapped || sp->parent_pte) {
785                 if (!sp->multimapped)
786                         parent_pte = sp->parent_pte;
787                 else {
788                         struct kvm_pte_chain *chain;
789
790                         chain = container_of(sp->parent_ptes.first,
791                                              struct kvm_pte_chain, link);
792                         parent_pte = chain->parent_ptes[0];
793                 }
794                 BUG_ON(!parent_pte);
795                 kvm_mmu_put_page(sp, parent_pte);
796                 set_shadow_pte(parent_pte, shadow_trap_nonpresent_pte);
797         }
798         kvm_mmu_page_unlink_children(kvm, sp);
799         if (!sp->root_count) {
800                 hlist_del(&sp->hash_link);
801                 kvm_mmu_free_page(kvm, sp);
802         } else
803                 list_move(&sp->link, &kvm->arch.active_mmu_pages);
804         kvm_mmu_reset_last_pte_updated(kvm);
805 }
806
807 /*
808  * Changing the number of mmu pages allocated to the vm
809  * Note: if kvm_nr_mmu_pages is too small, you will get dead lock
810  */
811 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int kvm_nr_mmu_pages)
812 {
813         /*
814          * If we set the number of mmu pages to be smaller be than the
815          * number of actived pages , we must to free some mmu pages before we
816          * change the value
817          */
818
819         if ((kvm->arch.n_alloc_mmu_pages - kvm->arch.n_free_mmu_pages) >
820             kvm_nr_mmu_pages) {
821                 int n_used_mmu_pages = kvm->arch.n_alloc_mmu_pages
822                                        - kvm->arch.n_free_mmu_pages;
823
824                 while (n_used_mmu_pages > kvm_nr_mmu_pages) {
825                         struct kvm_mmu_page *page;
826
827                         page = container_of(kvm->arch.active_mmu_pages.prev,
828                                             struct kvm_mmu_page, link);
829                         kvm_mmu_zap_page(kvm, page);
830                         n_used_mmu_pages--;
831                 }
832                 kvm->arch.n_free_mmu_pages = 0;
833         }
834         else
835                 kvm->arch.n_free_mmu_pages += kvm_nr_mmu_pages
836                                          - kvm->arch.n_alloc_mmu_pages;
837
838         kvm->arch.n_alloc_mmu_pages = kvm_nr_mmu_pages;
839 }
840
841 static int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
842 {
843         unsigned index;
844         struct hlist_head *bucket;
845         struct kvm_mmu_page *sp;
846         struct hlist_node *node, *n;
847         int r;
848
849         pgprintk("%s: looking for gfn %lx\n", __FUNCTION__, gfn);
850         r = 0;
851         index = kvm_page_table_hashfn(gfn) % KVM_NUM_MMU_PAGES;
852         bucket = &kvm->arch.mmu_page_hash[index];
853         hlist_for_each_entry_safe(sp, node, n, bucket, hash_link)
854                 if (sp->gfn == gfn && !sp->role.metaphysical) {
855                         pgprintk("%s: gfn %lx role %x\n", __FUNCTION__, gfn,
856                                  sp->role.word);
857                         kvm_mmu_zap_page(kvm, sp);
858                         r = 1;
859                 }
860         return r;
861 }
862
863 static void mmu_unshadow(struct kvm *kvm, gfn_t gfn)
864 {
865         struct kvm_mmu_page *sp;
866
867         while ((sp = kvm_mmu_lookup_page(kvm, gfn)) != NULL) {
868                 pgprintk("%s: zap %lx %x\n", __FUNCTION__, gfn, sp->role.word);
869                 kvm_mmu_zap_page(kvm, sp);
870         }
871 }
872
873 static void page_header_update_slot(struct kvm *kvm, void *pte, gfn_t gfn)
874 {
875         int slot = memslot_id(kvm, gfn_to_memslot(kvm, gfn));
876         struct kvm_mmu_page *sp = page_header(__pa(pte));
877
878         __set_bit(slot, &sp->slot_bitmap);
879 }
880
881 struct page *gva_to_page(struct kvm_vcpu *vcpu, gva_t gva)
882 {
883         gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
884
885         if (gpa == UNMAPPED_GVA)
886                 return NULL;
887         return gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
888 }
889
890 static void mmu_set_spte(struct kvm_vcpu *vcpu, u64 *shadow_pte,
891                          unsigned pt_access, unsigned pte_access,
892                          int user_fault, int write_fault, int dirty,
893                          int *ptwrite, gfn_t gfn)
894 {
895         u64 spte;
896         int was_rmapped = is_rmap_pte(*shadow_pte);
897         struct page *page;
898
899         pgprintk("%s: spte %llx access %x write_fault %d"
900                  " user_fault %d gfn %lx\n",
901                  __FUNCTION__, *shadow_pte, pt_access,
902                  write_fault, user_fault, gfn);
903
904         /*
905          * We don't set the accessed bit, since we sometimes want to see
906          * whether the guest actually used the pte (in order to detect
907          * demand paging).
908          */
909         spte = PT_PRESENT_MASK | PT_DIRTY_MASK;
910         if (!dirty)
911                 pte_access &= ~ACC_WRITE_MASK;
912         if (!(pte_access & ACC_EXEC_MASK))
913                 spte |= PT64_NX_MASK;
914
915         page = gfn_to_page(vcpu->kvm, gfn);
916
917         spte |= PT_PRESENT_MASK;
918         if (pte_access & ACC_USER_MASK)
919                 spte |= PT_USER_MASK;
920
921         if (is_error_page(page)) {
922                 set_shadow_pte(shadow_pte,
923                                shadow_trap_nonpresent_pte | PT_SHADOW_IO_MARK);
924                 kvm_release_page_clean(page);
925                 return;
926         }
927
928         spte |= page_to_phys(page);
929
930         if ((pte_access & ACC_WRITE_MASK)
931             || (write_fault && !is_write_protection(vcpu) && !user_fault)) {
932                 struct kvm_mmu_page *shadow;
933
934                 spte |= PT_WRITABLE_MASK;
935                 if (user_fault) {
936                         mmu_unshadow(vcpu->kvm, gfn);
937                         goto unshadowed;
938                 }
939
940                 shadow = kvm_mmu_lookup_page(vcpu->kvm, gfn);
941                 if (shadow) {
942                         pgprintk("%s: found shadow page for %lx, marking ro\n",
943                                  __FUNCTION__, gfn);
944                         pte_access &= ~ACC_WRITE_MASK;
945                         if (is_writeble_pte(spte)) {
946                                 spte &= ~PT_WRITABLE_MASK;
947                                 kvm_x86_ops->tlb_flush(vcpu);
948                         }
949                         if (write_fault)
950                                 *ptwrite = 1;
951                 }
952         }
953
954 unshadowed:
955
956         if (pte_access & ACC_WRITE_MASK)
957                 mark_page_dirty(vcpu->kvm, gfn);
958
959         pgprintk("%s: setting spte %llx\n", __FUNCTION__, spte);
960         set_shadow_pte(shadow_pte, spte);
961         page_header_update_slot(vcpu->kvm, shadow_pte, gfn);
962         if (!was_rmapped) {
963                 rmap_add(vcpu, shadow_pte, gfn);
964                 if (!is_rmap_pte(*shadow_pte))
965                         kvm_release_page_clean(page);
966         }
967         else
968                 kvm_release_page_clean(page);
969         if (!ptwrite || !*ptwrite)
970                 vcpu->arch.last_pte_updated = shadow_pte;
971 }
972
973 static void nonpaging_new_cr3(struct kvm_vcpu *vcpu)
974 {
975 }
976
977 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, int write, gfn_t gfn)
978 {
979         int level = PT32E_ROOT_LEVEL;
980         hpa_t table_addr = vcpu->arch.mmu.root_hpa;
981         int pt_write = 0;
982
983         for (; ; level--) {
984                 u32 index = PT64_INDEX(v, level);
985                 u64 *table;
986
987                 ASSERT(VALID_PAGE(table_addr));
988                 table = __va(table_addr);
989
990                 if (level == 1) {
991                         mmu_set_spte(vcpu, &table[index], ACC_ALL, ACC_ALL,
992                                      0, write, 1, &pt_write, gfn);
993                         return pt_write || is_io_pte(table[index]);
994                 }
995
996                 if (table[index] == shadow_trap_nonpresent_pte) {
997                         struct kvm_mmu_page *new_table;
998                         gfn_t pseudo_gfn;
999
1000                         pseudo_gfn = (v & PT64_DIR_BASE_ADDR_MASK)
1001                                 >> PAGE_SHIFT;
1002                         new_table = kvm_mmu_get_page(vcpu, pseudo_gfn,
1003                                                      v, level - 1,
1004                                                      1, ACC_ALL, &table[index],
1005                                                      NULL);
1006                         if (!new_table) {
1007                                 pgprintk("nonpaging_map: ENOMEM\n");
1008                                 return -ENOMEM;
1009                         }
1010
1011                         table[index] = __pa(new_table->spt) | PT_PRESENT_MASK
1012                                 | PT_WRITABLE_MASK | PT_USER_MASK;
1013                 }
1014                 table_addr = table[index] & PT64_BASE_ADDR_MASK;
1015         }
1016 }
1017
1018 static void nonpaging_prefetch_page(struct kvm_vcpu *vcpu,
1019                                     struct kvm_mmu_page *sp)
1020 {
1021         int i;
1022
1023         for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
1024                 sp->spt[i] = shadow_trap_nonpresent_pte;
1025 }
1026
1027 static void mmu_free_roots(struct kvm_vcpu *vcpu)
1028 {
1029         int i;
1030         struct kvm_mmu_page *sp;
1031
1032         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
1033                 return;
1034 #ifdef CONFIG_X86_64
1035         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1036                 hpa_t root = vcpu->arch.mmu.root_hpa;
1037
1038                 sp = page_header(root);
1039                 --sp->root_count;
1040                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1041                 return;
1042         }
1043 #endif
1044         for (i = 0; i < 4; ++i) {
1045                 hpa_t root = vcpu->arch.mmu.pae_root[i];
1046
1047                 if (root) {
1048                         root &= PT64_BASE_ADDR_MASK;
1049                         sp = page_header(root);
1050                         --sp->root_count;
1051                 }
1052                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
1053         }
1054         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1055 }
1056
1057 static void mmu_alloc_roots(struct kvm_vcpu *vcpu)
1058 {
1059         int i;
1060         gfn_t root_gfn;
1061         struct kvm_mmu_page *sp;
1062
1063         root_gfn = vcpu->arch.cr3 >> PAGE_SHIFT;
1064
1065 #ifdef CONFIG_X86_64
1066         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1067                 hpa_t root = vcpu->arch.mmu.root_hpa;
1068
1069                 ASSERT(!VALID_PAGE(root));
1070                 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
1071                                       PT64_ROOT_LEVEL, 0, ACC_ALL, NULL, NULL);
1072                 root = __pa(sp->spt);
1073                 ++sp->root_count;
1074                 vcpu->arch.mmu.root_hpa = root;
1075                 return;
1076         }
1077 #endif
1078         for (i = 0; i < 4; ++i) {
1079                 hpa_t root = vcpu->arch.mmu.pae_root[i];
1080
1081                 ASSERT(!VALID_PAGE(root));
1082                 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
1083                         if (!is_present_pte(vcpu->arch.pdptrs[i])) {
1084                                 vcpu->arch.mmu.pae_root[i] = 0;
1085                                 continue;
1086                         }
1087                         root_gfn = vcpu->arch.pdptrs[i] >> PAGE_SHIFT;
1088                 } else if (vcpu->arch.mmu.root_level == 0)
1089                         root_gfn = 0;
1090                 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30,
1091                                       PT32_ROOT_LEVEL, !is_paging(vcpu),
1092                                       ACC_ALL, NULL, NULL);
1093                 root = __pa(sp->spt);
1094                 ++sp->root_count;
1095                 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
1096         }
1097         vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
1098 }
1099
1100 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr)
1101 {
1102         return vaddr;
1103 }
1104
1105 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
1106                                 u32 error_code)
1107 {
1108         gfn_t gfn;
1109         int r;
1110
1111         pgprintk("%s: gva %lx error %x\n", __FUNCTION__, gva, error_code);
1112         r = mmu_topup_memory_caches(vcpu);
1113         if (r)
1114                 return r;
1115
1116         ASSERT(vcpu);
1117         ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
1118
1119         gfn = gva >> PAGE_SHIFT;
1120
1121         return nonpaging_map(vcpu, gva & PAGE_MASK,
1122                              error_code & PFERR_WRITE_MASK, gfn);
1123 }
1124
1125 static void nonpaging_free(struct kvm_vcpu *vcpu)
1126 {
1127         mmu_free_roots(vcpu);
1128 }
1129
1130 static int nonpaging_init_context(struct kvm_vcpu *vcpu)
1131 {
1132         struct kvm_mmu *context = &vcpu->arch.mmu;
1133
1134         context->new_cr3 = nonpaging_new_cr3;
1135         context->page_fault = nonpaging_page_fault;
1136         context->gva_to_gpa = nonpaging_gva_to_gpa;
1137         context->free = nonpaging_free;
1138         context->prefetch_page = nonpaging_prefetch_page;
1139         context->root_level = 0;
1140         context->shadow_root_level = PT32E_ROOT_LEVEL;
1141         context->root_hpa = INVALID_PAGE;
1142         return 0;
1143 }
1144
1145 void kvm_mmu_flush_tlb(struct kvm_vcpu *vcpu)
1146 {
1147         ++vcpu->stat.tlb_flush;
1148         kvm_x86_ops->tlb_flush(vcpu);
1149 }
1150
1151 static void paging_new_cr3(struct kvm_vcpu *vcpu)
1152 {
1153         pgprintk("%s: cr3 %lx\n", __FUNCTION__, vcpu->cr3);
1154         mmu_free_roots(vcpu);
1155 }
1156
1157 static void inject_page_fault(struct kvm_vcpu *vcpu,
1158                               u64 addr,
1159                               u32 err_code)
1160 {
1161         kvm_inject_page_fault(vcpu, addr, err_code);
1162 }
1163
1164 static void paging_free(struct kvm_vcpu *vcpu)
1165 {
1166         nonpaging_free(vcpu);
1167 }
1168
1169 #define PTTYPE 64
1170 #include "paging_tmpl.h"
1171 #undef PTTYPE
1172
1173 #define PTTYPE 32
1174 #include "paging_tmpl.h"
1175 #undef PTTYPE
1176
1177 static int paging64_init_context_common(struct kvm_vcpu *vcpu, int level)
1178 {
1179         struct kvm_mmu *context = &vcpu->arch.mmu;
1180
1181         ASSERT(is_pae(vcpu));
1182         context->new_cr3 = paging_new_cr3;
1183         context->page_fault = paging64_page_fault;
1184         context->gva_to_gpa = paging64_gva_to_gpa;
1185         context->prefetch_page = paging64_prefetch_page;
1186         context->free = paging_free;
1187         context->root_level = level;
1188         context->shadow_root_level = level;
1189         context->root_hpa = INVALID_PAGE;
1190         return 0;
1191 }
1192
1193 static int paging64_init_context(struct kvm_vcpu *vcpu)
1194 {
1195         return paging64_init_context_common(vcpu, PT64_ROOT_LEVEL);
1196 }
1197
1198 static int paging32_init_context(struct kvm_vcpu *vcpu)
1199 {
1200         struct kvm_mmu *context = &vcpu->arch.mmu;
1201
1202         context->new_cr3 = paging_new_cr3;
1203         context->page_fault = paging32_page_fault;
1204         context->gva_to_gpa = paging32_gva_to_gpa;
1205         context->free = paging_free;
1206         context->prefetch_page = paging32_prefetch_page;
1207         context->root_level = PT32_ROOT_LEVEL;
1208         context->shadow_root_level = PT32E_ROOT_LEVEL;
1209         context->root_hpa = INVALID_PAGE;
1210         return 0;
1211 }
1212
1213 static int paging32E_init_context(struct kvm_vcpu *vcpu)
1214 {
1215         return paging64_init_context_common(vcpu, PT32E_ROOT_LEVEL);
1216 }
1217
1218 static int init_kvm_mmu(struct kvm_vcpu *vcpu)
1219 {
1220         ASSERT(vcpu);
1221         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
1222
1223         if (!is_paging(vcpu))
1224                 return nonpaging_init_context(vcpu);
1225         else if (is_long_mode(vcpu))
1226                 return paging64_init_context(vcpu);
1227         else if (is_pae(vcpu))
1228                 return paging32E_init_context(vcpu);
1229         else
1230                 return paging32_init_context(vcpu);
1231 }
1232
1233 static void destroy_kvm_mmu(struct kvm_vcpu *vcpu)
1234 {
1235         ASSERT(vcpu);
1236         if (VALID_PAGE(vcpu->arch.mmu.root_hpa)) {
1237                 vcpu->arch.mmu.free(vcpu);
1238                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1239         }
1240 }
1241
1242 int kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
1243 {
1244         destroy_kvm_mmu(vcpu);
1245         return init_kvm_mmu(vcpu);
1246 }
1247 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
1248
1249 int kvm_mmu_load(struct kvm_vcpu *vcpu)
1250 {
1251         int r;
1252
1253         mutex_lock(&vcpu->kvm->lock);
1254         r = mmu_topup_memory_caches(vcpu);
1255         if (r)
1256                 goto out;
1257         mmu_alloc_roots(vcpu);
1258         kvm_x86_ops->set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
1259         kvm_mmu_flush_tlb(vcpu);
1260 out:
1261         mutex_unlock(&vcpu->kvm->lock);
1262         return r;
1263 }
1264 EXPORT_SYMBOL_GPL(kvm_mmu_load);
1265
1266 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
1267 {
1268         mmu_free_roots(vcpu);
1269 }
1270
1271 static void mmu_pte_write_zap_pte(struct kvm_vcpu *vcpu,
1272                                   struct kvm_mmu_page *sp,
1273                                   u64 *spte)
1274 {
1275         u64 pte;
1276         struct kvm_mmu_page *child;
1277
1278         pte = *spte;
1279         if (is_shadow_present_pte(pte)) {
1280                 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
1281                         rmap_remove(vcpu->kvm, spte);
1282                 else {
1283                         child = page_header(pte & PT64_BASE_ADDR_MASK);
1284                         mmu_page_remove_parent_pte(child, spte);
1285                 }
1286         }
1287         set_shadow_pte(spte, shadow_trap_nonpresent_pte);
1288 }
1289
1290 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
1291                                   struct kvm_mmu_page *sp,
1292                                   u64 *spte,
1293                                   const void *new, int bytes,
1294                                   int offset_in_pte)
1295 {
1296         if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
1297                 ++vcpu->kvm->stat.mmu_pde_zapped;
1298                 return;
1299         }
1300
1301         ++vcpu->kvm->stat.mmu_pte_updated;
1302         if (sp->role.glevels == PT32_ROOT_LEVEL)
1303                 paging32_update_pte(vcpu, sp, spte, new, bytes, offset_in_pte);
1304         else
1305                 paging64_update_pte(vcpu, sp, spte, new, bytes, offset_in_pte);
1306 }
1307
1308 static bool need_remote_flush(u64 old, u64 new)
1309 {
1310         if (!is_shadow_present_pte(old))
1311                 return false;
1312         if (!is_shadow_present_pte(new))
1313                 return true;
1314         if ((old ^ new) & PT64_BASE_ADDR_MASK)
1315                 return true;
1316         old ^= PT64_NX_MASK;
1317         new ^= PT64_NX_MASK;
1318         return (old & ~new & PT64_PERM_MASK) != 0;
1319 }
1320
1321 static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, u64 old, u64 new)
1322 {
1323         if (need_remote_flush(old, new))
1324                 kvm_flush_remote_tlbs(vcpu->kvm);
1325         else
1326                 kvm_mmu_flush_tlb(vcpu);
1327 }
1328
1329 static bool last_updated_pte_accessed(struct kvm_vcpu *vcpu)
1330 {
1331         u64 *spte = vcpu->arch.last_pte_updated;
1332
1333         return !!(spte && (*spte & PT_ACCESSED_MASK));
1334 }
1335
1336 void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
1337                        const u8 *new, int bytes)
1338 {
1339         gfn_t gfn = gpa >> PAGE_SHIFT;
1340         struct kvm_mmu_page *sp;
1341         struct hlist_node *node, *n;
1342         struct hlist_head *bucket;
1343         unsigned index;
1344         u64 entry;
1345         u64 *spte;
1346         unsigned offset = offset_in_page(gpa);
1347         unsigned pte_size;
1348         unsigned page_offset;
1349         unsigned misaligned;
1350         unsigned quadrant;
1351         int level;
1352         int flooded = 0;
1353         int npte;
1354
1355         pgprintk("%s: gpa %llx bytes %d\n", __FUNCTION__, gpa, bytes);
1356         ++vcpu->kvm->stat.mmu_pte_write;
1357         kvm_mmu_audit(vcpu, "pre pte write");
1358         if (gfn == vcpu->arch.last_pt_write_gfn
1359             && !last_updated_pte_accessed(vcpu)) {
1360                 ++vcpu->arch.last_pt_write_count;
1361                 if (vcpu->arch.last_pt_write_count >= 3)
1362                         flooded = 1;
1363         } else {
1364                 vcpu->arch.last_pt_write_gfn = gfn;
1365                 vcpu->arch.last_pt_write_count = 1;
1366                 vcpu->arch.last_pte_updated = NULL;
1367         }
1368         index = kvm_page_table_hashfn(gfn) % KVM_NUM_MMU_PAGES;
1369         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
1370         hlist_for_each_entry_safe(sp, node, n, bucket, hash_link) {
1371                 if (sp->gfn != gfn || sp->role.metaphysical)
1372                         continue;
1373                 pte_size = sp->role.glevels == PT32_ROOT_LEVEL ? 4 : 8;
1374                 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
1375                 misaligned |= bytes < 4;
1376                 if (misaligned || flooded) {
1377                         /*
1378                          * Misaligned accesses are too much trouble to fix
1379                          * up; also, they usually indicate a page is not used
1380                          * as a page table.
1381                          *
1382                          * If we're seeing too many writes to a page,
1383                          * it may no longer be a page table, or we may be
1384                          * forking, in which case it is better to unmap the
1385                          * page.
1386                          */
1387                         pgprintk("misaligned: gpa %llx bytes %d role %x\n",
1388                                  gpa, bytes, sp->role.word);
1389                         kvm_mmu_zap_page(vcpu->kvm, sp);
1390                         ++vcpu->kvm->stat.mmu_flooded;
1391                         continue;
1392                 }
1393                 page_offset = offset;
1394                 level = sp->role.level;
1395                 npte = 1;
1396                 if (sp->role.glevels == PT32_ROOT_LEVEL) {
1397                         page_offset <<= 1;      /* 32->64 */
1398                         /*
1399                          * A 32-bit pde maps 4MB while the shadow pdes map
1400                          * only 2MB.  So we need to double the offset again
1401                          * and zap two pdes instead of one.
1402                          */
1403                         if (level == PT32_ROOT_LEVEL) {
1404                                 page_offset &= ~7; /* kill rounding error */
1405                                 page_offset <<= 1;
1406                                 npte = 2;
1407                         }
1408                         quadrant = page_offset >> PAGE_SHIFT;
1409                         page_offset &= ~PAGE_MASK;
1410                         if (quadrant != sp->role.quadrant)
1411                                 continue;
1412                 }
1413                 spte = &sp->spt[page_offset / sizeof(*spte)];
1414                 while (npte--) {
1415                         entry = *spte;
1416                         mmu_pte_write_zap_pte(vcpu, sp, spte);
1417                         mmu_pte_write_new_pte(vcpu, sp, spte, new, bytes,
1418                                               page_offset & (pte_size - 1));
1419                         mmu_pte_write_flush_tlb(vcpu, entry, *spte);
1420                         ++spte;
1421                 }
1422         }
1423         kvm_mmu_audit(vcpu, "post pte write");
1424 }
1425
1426 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
1427 {
1428         gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
1429
1430         return kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1431 }
1432
1433 void __kvm_mmu_free_some_pages(struct kvm_vcpu *vcpu)
1434 {
1435         while (vcpu->kvm->arch.n_free_mmu_pages < KVM_REFILL_PAGES) {
1436                 struct kvm_mmu_page *sp;
1437
1438                 sp = container_of(vcpu->kvm->arch.active_mmu_pages.prev,
1439                                   struct kvm_mmu_page, link);
1440                 kvm_mmu_zap_page(vcpu->kvm, sp);
1441                 ++vcpu->kvm->stat.mmu_recycled;
1442         }
1443 }
1444
1445 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code)
1446 {
1447         int r;
1448         enum emulation_result er;
1449
1450         mutex_lock(&vcpu->kvm->lock);
1451         r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code);
1452         if (r < 0)
1453                 goto out;
1454
1455         if (!r) {
1456                 r = 1;
1457                 goto out;
1458         }
1459
1460         r = mmu_topup_memory_caches(vcpu);
1461         if (r)
1462                 goto out;
1463
1464         er = emulate_instruction(vcpu, vcpu->run, cr2, error_code, 0);
1465         mutex_unlock(&vcpu->kvm->lock);
1466
1467         switch (er) {
1468         case EMULATE_DONE:
1469                 return 1;
1470         case EMULATE_DO_MMIO:
1471                 ++vcpu->stat.mmio_exits;
1472                 return 0;
1473         case EMULATE_FAIL:
1474                 kvm_report_emulation_failure(vcpu, "pagetable");
1475                 return 1;
1476         default:
1477                 BUG();
1478         }
1479 out:
1480         mutex_unlock(&vcpu->kvm->lock);
1481         return r;
1482 }
1483 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
1484
1485 static void free_mmu_pages(struct kvm_vcpu *vcpu)
1486 {
1487         struct kvm_mmu_page *sp;
1488
1489         while (!list_empty(&vcpu->kvm->arch.active_mmu_pages)) {
1490                 sp = container_of(vcpu->kvm->arch.active_mmu_pages.next,
1491                                   struct kvm_mmu_page, link);
1492                 kvm_mmu_zap_page(vcpu->kvm, sp);
1493         }
1494         free_page((unsigned long)vcpu->arch.mmu.pae_root);
1495 }
1496
1497 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
1498 {
1499         struct page *page;
1500         int i;
1501
1502         ASSERT(vcpu);
1503
1504         if (vcpu->kvm->arch.n_requested_mmu_pages)
1505                 vcpu->kvm->arch.n_free_mmu_pages =
1506                                         vcpu->kvm->arch.n_requested_mmu_pages;
1507         else
1508                 vcpu->kvm->arch.n_free_mmu_pages =
1509                                         vcpu->kvm->arch.n_alloc_mmu_pages;
1510         /*
1511          * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
1512          * Therefore we need to allocate shadow page tables in the first
1513          * 4GB of memory, which happens to fit the DMA32 zone.
1514          */
1515         page = alloc_page(GFP_KERNEL | __GFP_DMA32);
1516         if (!page)
1517                 goto error_1;
1518         vcpu->arch.mmu.pae_root = page_address(page);
1519         for (i = 0; i < 4; ++i)
1520                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
1521
1522         return 0;
1523
1524 error_1:
1525         free_mmu_pages(vcpu);
1526         return -ENOMEM;
1527 }
1528
1529 int kvm_mmu_create(struct kvm_vcpu *vcpu)
1530 {
1531         ASSERT(vcpu);
1532         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
1533
1534         return alloc_mmu_pages(vcpu);
1535 }
1536
1537 int kvm_mmu_setup(struct kvm_vcpu *vcpu)
1538 {
1539         ASSERT(vcpu);
1540         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
1541
1542         return init_kvm_mmu(vcpu);
1543 }
1544
1545 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
1546 {
1547         ASSERT(vcpu);
1548
1549         destroy_kvm_mmu(vcpu);
1550         free_mmu_pages(vcpu);
1551         mmu_free_memory_caches(vcpu);
1552 }
1553
1554 void kvm_mmu_slot_remove_write_access(struct kvm *kvm, int slot)
1555 {
1556         struct kvm_mmu_page *sp;
1557
1558         list_for_each_entry(sp, &kvm->arch.active_mmu_pages, link) {
1559                 int i;
1560                 u64 *pt;
1561
1562                 if (!test_bit(slot, &sp->slot_bitmap))
1563                         continue;
1564
1565                 pt = sp->spt;
1566                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
1567                         /* avoid RMW */
1568                         if (pt[i] & PT_WRITABLE_MASK)
1569                                 pt[i] &= ~PT_WRITABLE_MASK;
1570         }
1571 }
1572
1573 void kvm_mmu_zap_all(struct kvm *kvm)
1574 {
1575         struct kvm_mmu_page *sp, *node;
1576
1577         list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link)
1578                 kvm_mmu_zap_page(kvm, sp);
1579
1580         kvm_flush_remote_tlbs(kvm);
1581 }
1582
1583 void kvm_mmu_module_exit(void)
1584 {
1585         if (pte_chain_cache)
1586                 kmem_cache_destroy(pte_chain_cache);
1587         if (rmap_desc_cache)
1588                 kmem_cache_destroy(rmap_desc_cache);
1589         if (mmu_page_header_cache)
1590                 kmem_cache_destroy(mmu_page_header_cache);
1591 }
1592
1593 int kvm_mmu_module_init(void)
1594 {
1595         pte_chain_cache = kmem_cache_create("kvm_pte_chain",
1596                                             sizeof(struct kvm_pte_chain),
1597                                             0, 0, NULL);
1598         if (!pte_chain_cache)
1599                 goto nomem;
1600         rmap_desc_cache = kmem_cache_create("kvm_rmap_desc",
1601                                             sizeof(struct kvm_rmap_desc),
1602                                             0, 0, NULL);
1603         if (!rmap_desc_cache)
1604                 goto nomem;
1605
1606         mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
1607                                                   sizeof(struct kvm_mmu_page),
1608                                                   0, 0, NULL);
1609         if (!mmu_page_header_cache)
1610                 goto nomem;
1611
1612         return 0;
1613
1614 nomem:
1615         kvm_mmu_module_exit();
1616         return -ENOMEM;
1617 }
1618
1619 /*
1620  * Caculate mmu pages needed for kvm.
1621  */
1622 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
1623 {
1624         int i;
1625         unsigned int nr_mmu_pages;
1626         unsigned int  nr_pages = 0;
1627
1628         for (i = 0; i < kvm->nmemslots; i++)
1629                 nr_pages += kvm->memslots[i].npages;
1630
1631         nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
1632         nr_mmu_pages = max(nr_mmu_pages,
1633                         (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
1634
1635         return nr_mmu_pages;
1636 }
1637
1638 #ifdef AUDIT
1639
1640 static const char *audit_msg;
1641
1642 static gva_t canonicalize(gva_t gva)
1643 {
1644 #ifdef CONFIG_X86_64
1645         gva = (long long)(gva << 16) >> 16;
1646 #endif
1647         return gva;
1648 }
1649
1650 static void audit_mappings_page(struct kvm_vcpu *vcpu, u64 page_pte,
1651                                 gva_t va, int level)
1652 {
1653         u64 *pt = __va(page_pte & PT64_BASE_ADDR_MASK);
1654         int i;
1655         gva_t va_delta = 1ul << (PAGE_SHIFT + 9 * (level - 1));
1656
1657         for (i = 0; i < PT64_ENT_PER_PAGE; ++i, va += va_delta) {
1658                 u64 ent = pt[i];
1659
1660                 if (ent == shadow_trap_nonpresent_pte)
1661                         continue;
1662
1663                 va = canonicalize(va);
1664                 if (level > 1) {
1665                         if (ent == shadow_notrap_nonpresent_pte)
1666                                 printk(KERN_ERR "audit: (%s) nontrapping pte"
1667                                        " in nonleaf level: levels %d gva %lx"
1668                                        " level %d pte %llx\n", audit_msg,
1669                                        vcpu->arch.mmu.root_level, va, level, ent);
1670
1671                         audit_mappings_page(vcpu, ent, va, level - 1);
1672                 } else {
1673                         gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, va);
1674                         struct page *page = gpa_to_page(vcpu, gpa);
1675                         hpa_t hpa = page_to_phys(page);
1676
1677                         if (is_shadow_present_pte(ent)
1678                             && (ent & PT64_BASE_ADDR_MASK) != hpa)
1679                                 printk(KERN_ERR "xx audit error: (%s) levels %d"
1680                                        " gva %lx gpa %llx hpa %llx ent %llx %d\n",
1681                                        audit_msg, vcpu->arch.mmu.root_level,
1682                                        va, gpa, hpa, ent,
1683                                        is_shadow_present_pte(ent));
1684                         else if (ent == shadow_notrap_nonpresent_pte
1685                                  && !is_error_hpa(hpa))
1686                                 printk(KERN_ERR "audit: (%s) notrap shadow,"
1687                                        " valid guest gva %lx\n", audit_msg, va);
1688                         kvm_release_page_clean(page);
1689
1690                 }
1691         }
1692 }
1693
1694 static void audit_mappings(struct kvm_vcpu *vcpu)
1695 {
1696         unsigned i;
1697
1698         if (vcpu->arch.mmu.root_level == 4)
1699                 audit_mappings_page(vcpu, vcpu->arch.mmu.root_hpa, 0, 4);
1700         else
1701                 for (i = 0; i < 4; ++i)
1702                         if (vcpu->arch.mmu.pae_root[i] & PT_PRESENT_MASK)
1703                                 audit_mappings_page(vcpu,
1704                                                     vcpu->arch.mmu.pae_root[i],
1705                                                     i << 30,
1706                                                     2);
1707 }
1708
1709 static int count_rmaps(struct kvm_vcpu *vcpu)
1710 {
1711         int nmaps = 0;
1712         int i, j, k;
1713
1714         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
1715                 struct kvm_memory_slot *m = &vcpu->kvm->memslots[i];
1716                 struct kvm_rmap_desc *d;
1717
1718                 for (j = 0; j < m->npages; ++j) {
1719                         unsigned long *rmapp = &m->rmap[j];
1720
1721                         if (!*rmapp)
1722                                 continue;
1723                         if (!(*rmapp & 1)) {
1724                                 ++nmaps;
1725                                 continue;
1726                         }
1727                         d = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
1728                         while (d) {
1729                                 for (k = 0; k < RMAP_EXT; ++k)
1730                                         if (d->shadow_ptes[k])
1731                                                 ++nmaps;
1732                                         else
1733                                                 break;
1734                                 d = d->more;
1735                         }
1736                 }
1737         }
1738         return nmaps;
1739 }
1740
1741 static int count_writable_mappings(struct kvm_vcpu *vcpu)
1742 {
1743         int nmaps = 0;
1744         struct kvm_mmu_page *sp;
1745         int i;
1746
1747         list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
1748                 u64 *pt = sp->spt;
1749
1750                 if (sp->role.level != PT_PAGE_TABLE_LEVEL)
1751                         continue;
1752
1753                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1754                         u64 ent = pt[i];
1755
1756                         if (!(ent & PT_PRESENT_MASK))
1757                                 continue;
1758                         if (!(ent & PT_WRITABLE_MASK))
1759                                 continue;
1760                         ++nmaps;
1761                 }
1762         }
1763         return nmaps;
1764 }
1765
1766 static void audit_rmap(struct kvm_vcpu *vcpu)
1767 {
1768         int n_rmap = count_rmaps(vcpu);
1769         int n_actual = count_writable_mappings(vcpu);
1770
1771         if (n_rmap != n_actual)
1772                 printk(KERN_ERR "%s: (%s) rmap %d actual %d\n",
1773                        __FUNCTION__, audit_msg, n_rmap, n_actual);
1774 }
1775
1776 static void audit_write_protection(struct kvm_vcpu *vcpu)
1777 {
1778         struct kvm_mmu_page *sp;
1779         struct kvm_memory_slot *slot;
1780         unsigned long *rmapp;
1781         gfn_t gfn;
1782
1783         list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
1784                 if (sp->role.metaphysical)
1785                         continue;
1786
1787                 slot = gfn_to_memslot(vcpu->kvm, sp->gfn);
1788                 gfn = unalias_gfn(vcpu->kvm, sp->gfn);
1789                 rmapp = &slot->rmap[gfn - slot->base_gfn];
1790                 if (*rmapp)
1791                         printk(KERN_ERR "%s: (%s) shadow page has writable"
1792                                " mappings: gfn %lx role %x\n",
1793                                __FUNCTION__, audit_msg, sp->gfn,
1794                                sp->role.word);
1795         }
1796 }
1797
1798 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg)
1799 {
1800         int olddbg = dbg;
1801
1802         dbg = 0;
1803         audit_msg = msg;
1804         audit_rmap(vcpu);
1805         audit_write_protection(vcpu);
1806         audit_mappings(vcpu);
1807         dbg = olddbg;
1808 }
1809
1810 #endif