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