]> git.karo-electronics.de Git - mv-sheeva.git/blob - arch/x86/xen/mmu.c
xen: defer building p2m mfn structures until kernel is mapped
[mv-sheeva.git] / arch / x86 / xen / mmu.c
1 /*
2  * Xen mmu operations
3  *
4  * This file contains the various mmu fetch and update operations.
5  * The most important job they must perform is the mapping between the
6  * domain's pfn and the overall machine mfns.
7  *
8  * Xen allows guests to directly update the pagetable, in a controlled
9  * fashion.  In other words, the guest modifies the same pagetable
10  * that the CPU actually uses, which eliminates the overhead of having
11  * a separate shadow pagetable.
12  *
13  * In order to allow this, it falls on the guest domain to map its
14  * notion of a "physical" pfn - which is just a domain-local linear
15  * address - into a real "machine address" which the CPU's MMU can
16  * use.
17  *
18  * A pgd_t/pmd_t/pte_t will typically contain an mfn, and so can be
19  * inserted directly into the pagetable.  When creating a new
20  * pte/pmd/pgd, it converts the passed pfn into an mfn.  Conversely,
21  * when reading the content back with __(pgd|pmd|pte)_val, it converts
22  * the mfn back into a pfn.
23  *
24  * The other constraint is that all pages which make up a pagetable
25  * must be mapped read-only in the guest.  This prevents uncontrolled
26  * guest updates to the pagetable.  Xen strictly enforces this, and
27  * will disallow any pagetable update which will end up mapping a
28  * pagetable page RW, and will disallow using any writable page as a
29  * pagetable.
30  *
31  * Naively, when loading %cr3 with the base of a new pagetable, Xen
32  * would need to validate the whole pagetable before going on.
33  * Naturally, this is quite slow.  The solution is to "pin" a
34  * pagetable, which enforces all the constraints on the pagetable even
35  * when it is not actively in use.  This menas that Xen can be assured
36  * that it is still valid when you do load it into %cr3, and doesn't
37  * need to revalidate it.
38  *
39  * Jeremy Fitzhardinge <jeremy@xensource.com>, XenSource Inc, 2007
40  */
41 #include <linux/sched.h>
42 #include <linux/highmem.h>
43 #include <linux/debugfs.h>
44 #include <linux/bug.h>
45 #include <linux/vmalloc.h>
46 #include <linux/module.h>
47 #include <linux/gfp.h>
48
49 #include <asm/pgtable.h>
50 #include <asm/tlbflush.h>
51 #include <asm/fixmap.h>
52 #include <asm/mmu_context.h>
53 #include <asm/setup.h>
54 #include <asm/paravirt.h>
55 #include <asm/e820.h>
56 #include <asm/linkage.h>
57 #include <asm/page.h>
58
59 #include <asm/xen/hypercall.h>
60 #include <asm/xen/hypervisor.h>
61
62 #include <xen/xen.h>
63 #include <xen/page.h>
64 #include <xen/interface/xen.h>
65 #include <xen/interface/hvm/hvm_op.h>
66 #include <xen/interface/version.h>
67 #include <xen/interface/memory.h>
68 #include <xen/hvc-console.h>
69
70 #include "multicalls.h"
71 #include "mmu.h"
72 #include "debugfs.h"
73
74 #define MMU_UPDATE_HISTO        30
75
76 /*
77  * Protects atomic reservation decrease/increase against concurrent increases.
78  * Also protects non-atomic updates of current_pages and driver_pages, and
79  * balloon lists.
80  */
81 DEFINE_SPINLOCK(xen_reservation_lock);
82
83 #ifdef CONFIG_XEN_DEBUG_FS
84
85 static struct {
86         u32 pgd_update;
87         u32 pgd_update_pinned;
88         u32 pgd_update_batched;
89
90         u32 pud_update;
91         u32 pud_update_pinned;
92         u32 pud_update_batched;
93
94         u32 pmd_update;
95         u32 pmd_update_pinned;
96         u32 pmd_update_batched;
97
98         u32 pte_update;
99         u32 pte_update_pinned;
100         u32 pte_update_batched;
101
102         u32 mmu_update;
103         u32 mmu_update_extended;
104         u32 mmu_update_histo[MMU_UPDATE_HISTO];
105
106         u32 prot_commit;
107         u32 prot_commit_batched;
108
109         u32 set_pte_at;
110         u32 set_pte_at_batched;
111         u32 set_pte_at_pinned;
112         u32 set_pte_at_current;
113         u32 set_pte_at_kernel;
114 } mmu_stats;
115
116 static u8 zero_stats;
117
118 static inline void check_zero(void)
119 {
120         if (unlikely(zero_stats)) {
121                 memset(&mmu_stats, 0, sizeof(mmu_stats));
122                 zero_stats = 0;
123         }
124 }
125
126 #define ADD_STATS(elem, val)                    \
127         do { check_zero(); mmu_stats.elem += (val); } while(0)
128
129 #else  /* !CONFIG_XEN_DEBUG_FS */
130
131 #define ADD_STATS(elem, val)    do { (void)(val); } while(0)
132
133 #endif /* CONFIG_XEN_DEBUG_FS */
134
135
136 /*
137  * Identity map, in addition to plain kernel map.  This needs to be
138  * large enough to allocate page table pages to allocate the rest.
139  * Each page can map 2MB.
140  */
141 #define LEVEL1_IDENT_ENTRIES    (PTRS_PER_PTE * 4)
142 static RESERVE_BRK_ARRAY(pte_t, level1_ident_pgt, LEVEL1_IDENT_ENTRIES);
143
144 #ifdef CONFIG_X86_64
145 /* l3 pud for userspace vsyscall mapping */
146 static pud_t level3_user_vsyscall[PTRS_PER_PUD] __page_aligned_bss;
147 #endif /* CONFIG_X86_64 */
148
149 /*
150  * Note about cr3 (pagetable base) values:
151  *
152  * xen_cr3 contains the current logical cr3 value; it contains the
153  * last set cr3.  This may not be the current effective cr3, because
154  * its update may be being lazily deferred.  However, a vcpu looking
155  * at its own cr3 can use this value knowing that it everything will
156  * be self-consistent.
157  *
158  * xen_current_cr3 contains the actual vcpu cr3; it is set once the
159  * hypercall to set the vcpu cr3 is complete (so it may be a little
160  * out of date, but it will never be set early).  If one vcpu is
161  * looking at another vcpu's cr3 value, it should use this variable.
162  */
163 DEFINE_PER_CPU(unsigned long, xen_cr3);  /* cr3 stored as physaddr */
164 DEFINE_PER_CPU(unsigned long, xen_current_cr3);  /* actual vcpu cr3 */
165
166
167 /*
168  * Just beyond the highest usermode address.  STACK_TOP_MAX has a
169  * redzone above it, so round it up to a PGD boundary.
170  */
171 #define USER_LIMIT      ((STACK_TOP_MAX + PGDIR_SIZE - 1) & PGDIR_MASK)
172
173 /*
174  * Xen leaves the responsibility for maintaining p2m mappings to the
175  * guests themselves, but it must also access and update the p2m array
176  * during suspend/resume when all the pages are reallocated.
177  *
178  * The p2m table is logically a flat array, but we implement it as a
179  * three-level tree to allow the address space to be sparse.
180  *
181  *                               Xen
182  *                                |
183  *     p2m_top              p2m_top_mfn
184  *       /  \                   /   \
185  * p2m_mid p2m_mid      p2m_mid_mfn p2m_mid_mfn
186  *    / \      / \         /           /
187  *  p2m p2m p2m p2m p2m p2m p2m ...
188  *
189  * The p2m_top and p2m_top_mfn levels are limited to 1 page, so the
190  * maximum representable pseudo-physical address space is:
191  *  P2M_TOP_PER_PAGE * P2M_MID_PER_PAGE * P2M_PER_PAGE pages
192  *
193  * P2M_PER_PAGE depends on the architecture, as a mfn is always
194  * unsigned long (8 bytes on 64-bit, 4 bytes on 32), leading to
195  * 512 and 1024 entries respectively. 
196  */
197
198 static unsigned long max_p2m_pfn __read_mostly;
199
200 #define P2M_PER_PAGE            (PAGE_SIZE / sizeof(unsigned long))
201 #define P2M_MID_PER_PAGE        (PAGE_SIZE / sizeof(unsigned long *))
202 #define P2M_TOP_PER_PAGE        (PAGE_SIZE / sizeof(unsigned long **))
203
204 #define MAX_P2M_PFN             (P2M_TOP_PER_PAGE * P2M_MID_PER_PAGE * P2M_PER_PAGE)
205
206 /* Placeholders for holes in the address space */
207 static RESERVE_BRK_ARRAY(unsigned long, p2m_missing, P2M_PER_PAGE);
208 static RESERVE_BRK_ARRAY(unsigned long *, p2m_mid_missing, P2M_MID_PER_PAGE);
209 static RESERVE_BRK_ARRAY(unsigned long, p2m_mid_missing_mfn, P2M_MID_PER_PAGE);
210
211 static RESERVE_BRK_ARRAY(unsigned long **, p2m_top, P2M_TOP_PER_PAGE);
212 static RESERVE_BRK_ARRAY(unsigned long, p2m_top_mfn, P2M_TOP_PER_PAGE);
213
214 RESERVE_BRK(p2m_mid, PAGE_SIZE * (MAX_DOMAIN_PAGES / (P2M_PER_PAGE * P2M_MID_PER_PAGE)));
215 RESERVE_BRK(p2m_mid_mfn, PAGE_SIZE * (MAX_DOMAIN_PAGES / (P2M_PER_PAGE * P2M_MID_PER_PAGE)));
216
217 static inline unsigned p2m_top_index(unsigned long pfn)
218 {
219         BUG_ON(pfn >= MAX_P2M_PFN);
220         return pfn / (P2M_MID_PER_PAGE * P2M_PER_PAGE);
221 }
222
223 static inline unsigned p2m_mid_index(unsigned long pfn)
224 {
225         return (pfn / P2M_PER_PAGE) % P2M_MID_PER_PAGE;
226 }
227
228 static inline unsigned p2m_index(unsigned long pfn)
229 {
230         return pfn % P2M_PER_PAGE;
231 }
232
233 static void p2m_top_init(unsigned long ***top)
234 {
235         unsigned i;
236
237         for (i = 0; i < P2M_TOP_PER_PAGE; i++)
238                 top[i] = p2m_mid_missing;
239 }
240
241 static void p2m_top_mfn_init(unsigned long *top)
242 {
243         unsigned i;
244
245         for (i = 0; i < P2M_TOP_PER_PAGE; i++)
246                 top[i] = virt_to_mfn(p2m_mid_missing_mfn);
247 }
248
249 static void p2m_mid_init(unsigned long **mid)
250 {
251         unsigned i;
252
253         for (i = 0; i < P2M_MID_PER_PAGE; i++)
254                 mid[i] = p2m_missing;
255 }
256
257 static void p2m_mid_mfn_init(unsigned long *mid)
258 {
259         unsigned i;
260
261         for (i = 0; i < P2M_MID_PER_PAGE; i++)
262                 mid[i] = virt_to_mfn(p2m_missing);
263 }
264
265 static void p2m_init(unsigned long *p2m)
266 {
267         unsigned i;
268
269         for (i = 0; i < P2M_MID_PER_PAGE; i++)
270                 p2m[i] = INVALID_P2M_ENTRY;
271 }
272
273 /*
274  * Build the parallel p2m_top_mfn and p2m_mid_mfn structures
275  *
276  * This is called both at boot time, and after resuming from suspend:
277  * - At boot time we're called very early, and must use extend_brk()
278  *   to allocate memory.
279  *
280  * - After resume we're called from within stop_machine, but the mfn
281  *   tree should alreay be completely allocated.
282  */
283 void xen_build_mfn_list_list(void)
284 {
285         unsigned pfn;
286
287         /* Pre-initialize p2m_top_mfn to be completely missing */
288         if (p2m_top_mfn == NULL) {
289                 p2m_mid_missing_mfn = extend_brk(PAGE_SIZE, PAGE_SIZE);
290                 p2m_mid_mfn_init(p2m_mid_missing_mfn);
291
292                 p2m_top_mfn = extend_brk(PAGE_SIZE, PAGE_SIZE);
293                 p2m_top_mfn_init(p2m_top_mfn);
294         }
295
296         for (pfn = 0; pfn < max_p2m_pfn; pfn += P2M_PER_PAGE) {
297                 unsigned topidx = p2m_top_index(pfn);
298                 unsigned mididx = p2m_mid_index(pfn);
299                 unsigned long **mid;
300                 unsigned long mid_mfn;
301                 unsigned long *mid_mfn_p;
302
303                 mid = p2m_top[topidx];
304
305                 /* Don't bother allocating any mfn mid levels if
306                    they're just missing */
307                 if (mid[mididx] == p2m_missing)
308                         continue;
309
310                 mid_mfn = p2m_top_mfn[topidx];
311                 mid_mfn_p = mfn_to_virt(mid_mfn);
312
313                 if (mid_mfn_p == p2m_mid_missing_mfn) {
314                         /*
315                          * XXX boot-time only!  We should never find
316                          * missing parts of the mfn tree after
317                          * runtime.  extend_brk() will BUG if we call
318                          * it too late.
319                          */
320                         mid_mfn_p = extend_brk(PAGE_SIZE, PAGE_SIZE);
321                         p2m_mid_mfn_init(mid_mfn_p);
322
323                         mid_mfn = virt_to_mfn(mid_mfn_p);
324                         
325                         p2m_top_mfn[topidx] = mid_mfn;
326                 }
327
328                 mid_mfn_p[mididx] = virt_to_mfn(mid[mididx]);
329         }
330 }
331
332 void xen_setup_mfn_list_list(void)
333 {
334         BUG_ON(HYPERVISOR_shared_info == &xen_dummy_shared_info);
335
336         HYPERVISOR_shared_info->arch.pfn_to_mfn_frame_list_list =
337                 virt_to_mfn(p2m_top_mfn);
338         HYPERVISOR_shared_info->arch.max_pfn = max_p2m_pfn;
339 }
340
341 /* Set up p2m_top to point to the domain-builder provided p2m pages */
342 void __init xen_build_dynamic_phys_to_machine(void)
343 {
344         unsigned long *mfn_list = (unsigned long *)xen_start_info->mfn_list;
345         unsigned long max_pfn = min(MAX_DOMAIN_PAGES, xen_start_info->nr_pages);
346         unsigned pfn;
347
348         max_p2m_pfn = max_pfn;
349
350         p2m_missing = extend_brk(PAGE_SIZE, PAGE_SIZE);
351         p2m_init(p2m_missing);
352
353         p2m_mid_missing = extend_brk(PAGE_SIZE, PAGE_SIZE);
354         p2m_mid_init(p2m_mid_missing);
355
356         p2m_top = extend_brk(PAGE_SIZE, PAGE_SIZE);
357         p2m_top_init(p2m_top);
358
359         /*
360          * The domain builder gives us a pre-constructed p2m array in
361          * mfn_list for all the pages initially given to us, so we just
362          * need to graft that into our tree structure.
363          */
364         for (pfn = 0; pfn < max_pfn; pfn += P2M_PER_PAGE) {
365                 unsigned topidx = p2m_top_index(pfn);
366                 unsigned mididx = p2m_mid_index(pfn);
367
368                 if (p2m_top[topidx] == p2m_mid_missing) {
369                         unsigned long **mid = extend_brk(PAGE_SIZE, PAGE_SIZE);
370                         p2m_mid_init(mid);
371
372                         p2m_top[topidx] = mid;
373                 }
374
375                 p2m_top[topidx][mididx] = &mfn_list[pfn];
376         }
377 }
378
379 unsigned long get_phys_to_machine(unsigned long pfn)
380 {
381         unsigned topidx, mididx, idx;
382
383         if (unlikely(pfn >= MAX_P2M_PFN))
384                 return INVALID_P2M_ENTRY;
385
386         topidx = p2m_top_index(pfn);
387         mididx = p2m_mid_index(pfn);
388         idx = p2m_index(pfn);
389
390         return p2m_top[topidx][mididx][idx];
391 }
392 EXPORT_SYMBOL_GPL(get_phys_to_machine);
393
394 static void *alloc_p2m_page(void)
395 {
396         return (void *)__get_free_page(GFP_KERNEL | __GFP_REPEAT);
397 }
398
399 static void free_p2m_page(void *p)
400 {
401         free_page((unsigned long)p);
402 }
403
404 /* 
405  * Fully allocate the p2m structure for a given pfn.  We need to check
406  * that both the top and mid levels are allocated, and make sure the
407  * parallel mfn tree is kept in sync.  We may race with other cpus, so
408  * the new pages are installed with cmpxchg; if we lose the race then
409  * simply free the page we allocated and use the one that's there.
410  */
411 static bool alloc_p2m(unsigned long pfn)
412 {
413         unsigned topidx, mididx;
414         unsigned long ***top_p, **mid;
415         unsigned long *top_mfn_p, *mid_mfn;
416
417         topidx = p2m_top_index(pfn);
418         mididx = p2m_mid_index(pfn);
419
420         top_p = &p2m_top[topidx];
421         mid = *top_p;
422
423         if (mid == p2m_mid_missing) {
424                 /* Mid level is missing, allocate a new one */
425                 mid = alloc_p2m_page();
426                 if (!mid)
427                         return false;
428
429                 p2m_mid_init(mid);
430
431                 if (cmpxchg(top_p, p2m_mid_missing, mid) != p2m_mid_missing)
432                         free_p2m_page(mid);
433         }
434
435         top_mfn_p = &p2m_top_mfn[topidx];
436         mid_mfn = mfn_to_virt(*top_mfn_p);
437
438         if (mid_mfn == p2m_mid_missing_mfn) {
439                 /* Separately check the mid mfn level */
440                 unsigned long missing_mfn;
441                 unsigned long mid_mfn_mfn;
442
443                 mid_mfn = alloc_p2m_page();
444                 if (!mid_mfn)
445                         return false;
446
447                 p2m_mid_mfn_init(mid_mfn);
448                 
449                 missing_mfn = virt_to_mfn(p2m_mid_missing_mfn);
450                 mid_mfn_mfn = virt_to_mfn(mid_mfn);
451                 if (cmpxchg(top_mfn_p, missing_mfn, mid_mfn_mfn) != missing_mfn)
452                         free_p2m_page(mid_mfn);
453         }
454
455         if (p2m_top[topidx][mididx] == p2m_missing) {
456                 /* p2m leaf page is missing */
457                 unsigned long *p2m;
458
459                 p2m = alloc_p2m_page();
460                 if (!p2m)
461                         return false;
462
463                 p2m_init(p2m);
464
465                 if (cmpxchg(&mid[mididx], p2m_missing, p2m) != p2m_missing)
466                         free_p2m_page(p2m);
467                 else
468                         mid_mfn[mididx] = virt_to_mfn(p2m);
469         }
470
471         return true;
472 }
473
474 /* Try to install p2m mapping; fail if intermediate bits missing */
475 bool __set_phys_to_machine(unsigned long pfn, unsigned long mfn)
476 {
477         unsigned topidx, mididx, idx;
478
479         if (unlikely(pfn >= MAX_P2M_PFN)) {
480                 BUG_ON(mfn != INVALID_P2M_ENTRY);
481                 return true;
482         }
483
484         topidx = p2m_top_index(pfn);
485         mididx = p2m_mid_index(pfn);
486         idx = p2m_index(pfn);
487
488         if (p2m_top[topidx][mididx] == p2m_missing)
489                 return mfn == INVALID_P2M_ENTRY;
490
491         p2m_top[topidx][mididx][idx] = mfn;
492
493         return true;
494 }
495
496 bool set_phys_to_machine(unsigned long pfn, unsigned long mfn)
497 {
498         if (unlikely(xen_feature(XENFEAT_auto_translated_physmap))) {
499                 BUG_ON(pfn != mfn && mfn != INVALID_P2M_ENTRY);
500                 return true;
501         }
502
503         if (unlikely(!__set_phys_to_machine(pfn, mfn)))  {
504                 if (!alloc_p2m(pfn))
505                         return false;
506
507                 if (!__set_phys_to_machine(pfn, mfn))
508                         return false;
509         }
510
511         return true;
512 }
513
514 unsigned long arbitrary_virt_to_mfn(void *vaddr)
515 {
516         xmaddr_t maddr = arbitrary_virt_to_machine(vaddr);
517
518         return PFN_DOWN(maddr.maddr);
519 }
520
521 xmaddr_t arbitrary_virt_to_machine(void *vaddr)
522 {
523         unsigned long address = (unsigned long)vaddr;
524         unsigned int level;
525         pte_t *pte;
526         unsigned offset;
527
528         /*
529          * if the PFN is in the linear mapped vaddr range, we can just use
530          * the (quick) virt_to_machine() p2m lookup
531          */
532         if (virt_addr_valid(vaddr))
533                 return virt_to_machine(vaddr);
534
535         /* otherwise we have to do a (slower) full page-table walk */
536
537         pte = lookup_address(address, &level);
538         BUG_ON(pte == NULL);
539         offset = address & ~PAGE_MASK;
540         return XMADDR(((phys_addr_t)pte_mfn(*pte) << PAGE_SHIFT) + offset);
541 }
542
543 void make_lowmem_page_readonly(void *vaddr)
544 {
545         pte_t *pte, ptev;
546         unsigned long address = (unsigned long)vaddr;
547         unsigned int level;
548
549         pte = lookup_address(address, &level);
550         BUG_ON(pte == NULL);
551
552         ptev = pte_wrprotect(*pte);
553
554         if (HYPERVISOR_update_va_mapping(address, ptev, 0))
555                 BUG();
556 }
557
558 void make_lowmem_page_readwrite(void *vaddr)
559 {
560         pte_t *pte, ptev;
561         unsigned long address = (unsigned long)vaddr;
562         unsigned int level;
563
564         pte = lookup_address(address, &level);
565         BUG_ON(pte == NULL);
566
567         ptev = pte_mkwrite(*pte);
568
569         if (HYPERVISOR_update_va_mapping(address, ptev, 0))
570                 BUG();
571 }
572
573
574 static bool xen_page_pinned(void *ptr)
575 {
576         struct page *page = virt_to_page(ptr);
577
578         return PagePinned(page);
579 }
580
581 static bool xen_iomap_pte(pte_t pte)
582 {
583         return pte_flags(pte) & _PAGE_IOMAP;
584 }
585
586 static void xen_set_iomap_pte(pte_t *ptep, pte_t pteval)
587 {
588         struct multicall_space mcs;
589         struct mmu_update *u;
590
591         mcs = xen_mc_entry(sizeof(*u));
592         u = mcs.args;
593
594         /* ptep might be kmapped when using 32-bit HIGHPTE */
595         u->ptr = arbitrary_virt_to_machine(ptep).maddr;
596         u->val = pte_val_ma(pteval);
597
598         MULTI_mmu_update(mcs.mc, mcs.args, 1, NULL, DOMID_IO);
599
600         xen_mc_issue(PARAVIRT_LAZY_MMU);
601 }
602
603 static void xen_extend_mmu_update(const struct mmu_update *update)
604 {
605         struct multicall_space mcs;
606         struct mmu_update *u;
607
608         mcs = xen_mc_extend_args(__HYPERVISOR_mmu_update, sizeof(*u));
609
610         if (mcs.mc != NULL) {
611                 ADD_STATS(mmu_update_extended, 1);
612                 ADD_STATS(mmu_update_histo[mcs.mc->args[1]], -1);
613
614                 mcs.mc->args[1]++;
615
616                 if (mcs.mc->args[1] < MMU_UPDATE_HISTO)
617                         ADD_STATS(mmu_update_histo[mcs.mc->args[1]], 1);
618                 else
619                         ADD_STATS(mmu_update_histo[0], 1);
620         } else {
621                 ADD_STATS(mmu_update, 1);
622                 mcs = __xen_mc_entry(sizeof(*u));
623                 MULTI_mmu_update(mcs.mc, mcs.args, 1, NULL, DOMID_SELF);
624                 ADD_STATS(mmu_update_histo[1], 1);
625         }
626
627         u = mcs.args;
628         *u = *update;
629 }
630
631 void xen_set_pmd_hyper(pmd_t *ptr, pmd_t val)
632 {
633         struct mmu_update u;
634
635         preempt_disable();
636
637         xen_mc_batch();
638
639         /* ptr may be ioremapped for 64-bit pagetable setup */
640         u.ptr = arbitrary_virt_to_machine(ptr).maddr;
641         u.val = pmd_val_ma(val);
642         xen_extend_mmu_update(&u);
643
644         ADD_STATS(pmd_update_batched, paravirt_get_lazy_mode() == PARAVIRT_LAZY_MMU);
645
646         xen_mc_issue(PARAVIRT_LAZY_MMU);
647
648         preempt_enable();
649 }
650
651 void xen_set_pmd(pmd_t *ptr, pmd_t val)
652 {
653         ADD_STATS(pmd_update, 1);
654
655         /* If page is not pinned, we can just update the entry
656            directly */
657         if (!xen_page_pinned(ptr)) {
658                 *ptr = val;
659                 return;
660         }
661
662         ADD_STATS(pmd_update_pinned, 1);
663
664         xen_set_pmd_hyper(ptr, val);
665 }
666
667 /*
668  * Associate a virtual page frame with a given physical page frame
669  * and protection flags for that frame.
670  */
671 void set_pte_mfn(unsigned long vaddr, unsigned long mfn, pgprot_t flags)
672 {
673         set_pte_vaddr(vaddr, mfn_pte(mfn, flags));
674 }
675
676 void xen_set_pte_at(struct mm_struct *mm, unsigned long addr,
677                     pte_t *ptep, pte_t pteval)
678 {
679         if (xen_iomap_pte(pteval)) {
680                 xen_set_iomap_pte(ptep, pteval);
681                 goto out;
682         }
683
684         ADD_STATS(set_pte_at, 1);
685 //      ADD_STATS(set_pte_at_pinned, xen_page_pinned(ptep));
686         ADD_STATS(set_pte_at_current, mm == current->mm);
687         ADD_STATS(set_pte_at_kernel, mm == &init_mm);
688
689         if (mm == current->mm || mm == &init_mm) {
690                 if (paravirt_get_lazy_mode() == PARAVIRT_LAZY_MMU) {
691                         struct multicall_space mcs;
692                         mcs = xen_mc_entry(0);
693
694                         MULTI_update_va_mapping(mcs.mc, addr, pteval, 0);
695                         ADD_STATS(set_pte_at_batched, 1);
696                         xen_mc_issue(PARAVIRT_LAZY_MMU);
697                         goto out;
698                 } else
699                         if (HYPERVISOR_update_va_mapping(addr, pteval, 0) == 0)
700                                 goto out;
701         }
702         xen_set_pte(ptep, pteval);
703
704 out:    return;
705 }
706
707 pte_t xen_ptep_modify_prot_start(struct mm_struct *mm,
708                                  unsigned long addr, pte_t *ptep)
709 {
710         /* Just return the pte as-is.  We preserve the bits on commit */
711         return *ptep;
712 }
713
714 void xen_ptep_modify_prot_commit(struct mm_struct *mm, unsigned long addr,
715                                  pte_t *ptep, pte_t pte)
716 {
717         struct mmu_update u;
718
719         xen_mc_batch();
720
721         u.ptr = arbitrary_virt_to_machine(ptep).maddr | MMU_PT_UPDATE_PRESERVE_AD;
722         u.val = pte_val_ma(pte);
723         xen_extend_mmu_update(&u);
724
725         ADD_STATS(prot_commit, 1);
726         ADD_STATS(prot_commit_batched, paravirt_get_lazy_mode() == PARAVIRT_LAZY_MMU);
727
728         xen_mc_issue(PARAVIRT_LAZY_MMU);
729 }
730
731 /* Assume pteval_t is equivalent to all the other *val_t types. */
732 static pteval_t pte_mfn_to_pfn(pteval_t val)
733 {
734         if (val & _PAGE_PRESENT) {
735                 unsigned long mfn = (val & PTE_PFN_MASK) >> PAGE_SHIFT;
736                 pteval_t flags = val & PTE_FLAGS_MASK;
737                 val = ((pteval_t)mfn_to_pfn(mfn) << PAGE_SHIFT) | flags;
738         }
739
740         return val;
741 }
742
743 static pteval_t pte_pfn_to_mfn(pteval_t val)
744 {
745         if (val & _PAGE_PRESENT) {
746                 unsigned long pfn = (val & PTE_PFN_MASK) >> PAGE_SHIFT;
747                 pteval_t flags = val & PTE_FLAGS_MASK;
748                 val = ((pteval_t)pfn_to_mfn(pfn) << PAGE_SHIFT) | flags;
749         }
750
751         return val;
752 }
753
754 static pteval_t iomap_pte(pteval_t val)
755 {
756         if (val & _PAGE_PRESENT) {
757                 unsigned long pfn = (val & PTE_PFN_MASK) >> PAGE_SHIFT;
758                 pteval_t flags = val & PTE_FLAGS_MASK;
759
760                 /* We assume the pte frame number is a MFN, so
761                    just use it as-is. */
762                 val = ((pteval_t)pfn << PAGE_SHIFT) | flags;
763         }
764
765         return val;
766 }
767
768 pteval_t xen_pte_val(pte_t pte)
769 {
770         if (xen_initial_domain() && (pte.pte & _PAGE_IOMAP))
771                 return pte.pte;
772
773         return pte_mfn_to_pfn(pte.pte);
774 }
775 PV_CALLEE_SAVE_REGS_THUNK(xen_pte_val);
776
777 pgdval_t xen_pgd_val(pgd_t pgd)
778 {
779         return pte_mfn_to_pfn(pgd.pgd);
780 }
781 PV_CALLEE_SAVE_REGS_THUNK(xen_pgd_val);
782
783 pte_t xen_make_pte(pteval_t pte)
784 {
785         phys_addr_t addr = (pte & PTE_PFN_MASK);
786
787         /*
788          * Unprivileged domains are allowed to do IOMAPpings for
789          * PCI passthrough, but not map ISA space.  The ISA
790          * mappings are just dummy local mappings to keep other
791          * parts of the kernel happy.
792          */
793         if (unlikely(pte & _PAGE_IOMAP) &&
794             (xen_initial_domain() || addr >= ISA_END_ADDRESS)) {
795                 pte = iomap_pte(pte);
796         } else {
797                 pte &= ~_PAGE_IOMAP;
798                 pte = pte_pfn_to_mfn(pte);
799         }
800
801         return native_make_pte(pte);
802 }
803 PV_CALLEE_SAVE_REGS_THUNK(xen_make_pte);
804
805 pgd_t xen_make_pgd(pgdval_t pgd)
806 {
807         pgd = pte_pfn_to_mfn(pgd);
808         return native_make_pgd(pgd);
809 }
810 PV_CALLEE_SAVE_REGS_THUNK(xen_make_pgd);
811
812 pmdval_t xen_pmd_val(pmd_t pmd)
813 {
814         return pte_mfn_to_pfn(pmd.pmd);
815 }
816 PV_CALLEE_SAVE_REGS_THUNK(xen_pmd_val);
817
818 void xen_set_pud_hyper(pud_t *ptr, pud_t val)
819 {
820         struct mmu_update u;
821
822         preempt_disable();
823
824         xen_mc_batch();
825
826         /* ptr may be ioremapped for 64-bit pagetable setup */
827         u.ptr = arbitrary_virt_to_machine(ptr).maddr;
828         u.val = pud_val_ma(val);
829         xen_extend_mmu_update(&u);
830
831         ADD_STATS(pud_update_batched, paravirt_get_lazy_mode() == PARAVIRT_LAZY_MMU);
832
833         xen_mc_issue(PARAVIRT_LAZY_MMU);
834
835         preempt_enable();
836 }
837
838 void xen_set_pud(pud_t *ptr, pud_t val)
839 {
840         ADD_STATS(pud_update, 1);
841
842         /* If page is not pinned, we can just update the entry
843            directly */
844         if (!xen_page_pinned(ptr)) {
845                 *ptr = val;
846                 return;
847         }
848
849         ADD_STATS(pud_update_pinned, 1);
850
851         xen_set_pud_hyper(ptr, val);
852 }
853
854 void xen_set_pte(pte_t *ptep, pte_t pte)
855 {
856         if (xen_iomap_pte(pte)) {
857                 xen_set_iomap_pte(ptep, pte);
858                 return;
859         }
860
861         ADD_STATS(pte_update, 1);
862 //      ADD_STATS(pte_update_pinned, xen_page_pinned(ptep));
863         ADD_STATS(pte_update_batched, paravirt_get_lazy_mode() == PARAVIRT_LAZY_MMU);
864
865 #ifdef CONFIG_X86_PAE
866         ptep->pte_high = pte.pte_high;
867         smp_wmb();
868         ptep->pte_low = pte.pte_low;
869 #else
870         *ptep = pte;
871 #endif
872 }
873
874 #ifdef CONFIG_X86_PAE
875 void xen_set_pte_atomic(pte_t *ptep, pte_t pte)
876 {
877         if (xen_iomap_pte(pte)) {
878                 xen_set_iomap_pte(ptep, pte);
879                 return;
880         }
881
882         set_64bit((u64 *)ptep, native_pte_val(pte));
883 }
884
885 void xen_pte_clear(struct mm_struct *mm, unsigned long addr, pte_t *ptep)
886 {
887         ptep->pte_low = 0;
888         smp_wmb();              /* make sure low gets written first */
889         ptep->pte_high = 0;
890 }
891
892 void xen_pmd_clear(pmd_t *pmdp)
893 {
894         set_pmd(pmdp, __pmd(0));
895 }
896 #endif  /* CONFIG_X86_PAE */
897
898 pmd_t xen_make_pmd(pmdval_t pmd)
899 {
900         pmd = pte_pfn_to_mfn(pmd);
901         return native_make_pmd(pmd);
902 }
903 PV_CALLEE_SAVE_REGS_THUNK(xen_make_pmd);
904
905 #if PAGETABLE_LEVELS == 4
906 pudval_t xen_pud_val(pud_t pud)
907 {
908         return pte_mfn_to_pfn(pud.pud);
909 }
910 PV_CALLEE_SAVE_REGS_THUNK(xen_pud_val);
911
912 pud_t xen_make_pud(pudval_t pud)
913 {
914         pud = pte_pfn_to_mfn(pud);
915
916         return native_make_pud(pud);
917 }
918 PV_CALLEE_SAVE_REGS_THUNK(xen_make_pud);
919
920 pgd_t *xen_get_user_pgd(pgd_t *pgd)
921 {
922         pgd_t *pgd_page = (pgd_t *)(((unsigned long)pgd) & PAGE_MASK);
923         unsigned offset = pgd - pgd_page;
924         pgd_t *user_ptr = NULL;
925
926         if (offset < pgd_index(USER_LIMIT)) {
927                 struct page *page = virt_to_page(pgd_page);
928                 user_ptr = (pgd_t *)page->private;
929                 if (user_ptr)
930                         user_ptr += offset;
931         }
932
933         return user_ptr;
934 }
935
936 static void __xen_set_pgd_hyper(pgd_t *ptr, pgd_t val)
937 {
938         struct mmu_update u;
939
940         u.ptr = virt_to_machine(ptr).maddr;
941         u.val = pgd_val_ma(val);
942         xen_extend_mmu_update(&u);
943 }
944
945 /*
946  * Raw hypercall-based set_pgd, intended for in early boot before
947  * there's a page structure.  This implies:
948  *  1. The only existing pagetable is the kernel's
949  *  2. It is always pinned
950  *  3. It has no user pagetable attached to it
951  */
952 void __init xen_set_pgd_hyper(pgd_t *ptr, pgd_t val)
953 {
954         preempt_disable();
955
956         xen_mc_batch();
957
958         __xen_set_pgd_hyper(ptr, val);
959
960         xen_mc_issue(PARAVIRT_LAZY_MMU);
961
962         preempt_enable();
963 }
964
965 void xen_set_pgd(pgd_t *ptr, pgd_t val)
966 {
967         pgd_t *user_ptr = xen_get_user_pgd(ptr);
968
969         ADD_STATS(pgd_update, 1);
970
971         /* If page is not pinned, we can just update the entry
972            directly */
973         if (!xen_page_pinned(ptr)) {
974                 *ptr = val;
975                 if (user_ptr) {
976                         WARN_ON(xen_page_pinned(user_ptr));
977                         *user_ptr = val;
978                 }
979                 return;
980         }
981
982         ADD_STATS(pgd_update_pinned, 1);
983         ADD_STATS(pgd_update_batched, paravirt_get_lazy_mode() == PARAVIRT_LAZY_MMU);
984
985         /* If it's pinned, then we can at least batch the kernel and
986            user updates together. */
987         xen_mc_batch();
988
989         __xen_set_pgd_hyper(ptr, val);
990         if (user_ptr)
991                 __xen_set_pgd_hyper(user_ptr, val);
992
993         xen_mc_issue(PARAVIRT_LAZY_MMU);
994 }
995 #endif  /* PAGETABLE_LEVELS == 4 */
996
997 /*
998  * (Yet another) pagetable walker.  This one is intended for pinning a
999  * pagetable.  This means that it walks a pagetable and calls the
1000  * callback function on each page it finds making up the page table,
1001  * at every level.  It walks the entire pagetable, but it only bothers
1002  * pinning pte pages which are below limit.  In the normal case this
1003  * will be STACK_TOP_MAX, but at boot we need to pin up to
1004  * FIXADDR_TOP.
1005  *
1006  * For 32-bit the important bit is that we don't pin beyond there,
1007  * because then we start getting into Xen's ptes.
1008  *
1009  * For 64-bit, we must skip the Xen hole in the middle of the address
1010  * space, just after the big x86-64 virtual hole.
1011  */
1012 static int __xen_pgd_walk(struct mm_struct *mm, pgd_t *pgd,
1013                           int (*func)(struct mm_struct *mm, struct page *,
1014                                       enum pt_level),
1015                           unsigned long limit)
1016 {
1017         int flush = 0;
1018         unsigned hole_low, hole_high;
1019         unsigned pgdidx_limit, pudidx_limit, pmdidx_limit;
1020         unsigned pgdidx, pudidx, pmdidx;
1021
1022         /* The limit is the last byte to be touched */
1023         limit--;
1024         BUG_ON(limit >= FIXADDR_TOP);
1025
1026         if (xen_feature(XENFEAT_auto_translated_physmap))
1027                 return 0;
1028
1029         /*
1030          * 64-bit has a great big hole in the middle of the address
1031          * space, which contains the Xen mappings.  On 32-bit these
1032          * will end up making a zero-sized hole and so is a no-op.
1033          */
1034         hole_low = pgd_index(USER_LIMIT);
1035         hole_high = pgd_index(PAGE_OFFSET);
1036
1037         pgdidx_limit = pgd_index(limit);
1038 #if PTRS_PER_PUD > 1
1039         pudidx_limit = pud_index(limit);
1040 #else
1041         pudidx_limit = 0;
1042 #endif
1043 #if PTRS_PER_PMD > 1
1044         pmdidx_limit = pmd_index(limit);
1045 #else
1046         pmdidx_limit = 0;
1047 #endif
1048
1049         for (pgdidx = 0; pgdidx <= pgdidx_limit; pgdidx++) {
1050                 pud_t *pud;
1051
1052                 if (pgdidx >= hole_low && pgdidx < hole_high)
1053                         continue;
1054
1055                 if (!pgd_val(pgd[pgdidx]))
1056                         continue;
1057
1058                 pud = pud_offset(&pgd[pgdidx], 0);
1059
1060                 if (PTRS_PER_PUD > 1) /* not folded */
1061                         flush |= (*func)(mm, virt_to_page(pud), PT_PUD);
1062
1063                 for (pudidx = 0; pudidx < PTRS_PER_PUD; pudidx++) {
1064                         pmd_t *pmd;
1065
1066                         if (pgdidx == pgdidx_limit &&
1067                             pudidx > pudidx_limit)
1068                                 goto out;
1069
1070                         if (pud_none(pud[pudidx]))
1071                                 continue;
1072
1073                         pmd = pmd_offset(&pud[pudidx], 0);
1074
1075                         if (PTRS_PER_PMD > 1) /* not folded */
1076                                 flush |= (*func)(mm, virt_to_page(pmd), PT_PMD);
1077
1078                         for (pmdidx = 0; pmdidx < PTRS_PER_PMD; pmdidx++) {
1079                                 struct page *pte;
1080
1081                                 if (pgdidx == pgdidx_limit &&
1082                                     pudidx == pudidx_limit &&
1083                                     pmdidx > pmdidx_limit)
1084                                         goto out;
1085
1086                                 if (pmd_none(pmd[pmdidx]))
1087                                         continue;
1088
1089                                 pte = pmd_page(pmd[pmdidx]);
1090                                 flush |= (*func)(mm, pte, PT_PTE);
1091                         }
1092                 }
1093         }
1094
1095 out:
1096         /* Do the top level last, so that the callbacks can use it as
1097            a cue to do final things like tlb flushes. */
1098         flush |= (*func)(mm, virt_to_page(pgd), PT_PGD);
1099
1100         return flush;
1101 }
1102
1103 static int xen_pgd_walk(struct mm_struct *mm,
1104                         int (*func)(struct mm_struct *mm, struct page *,
1105                                     enum pt_level),
1106                         unsigned long limit)
1107 {
1108         return __xen_pgd_walk(mm, mm->pgd, func, limit);
1109 }
1110
1111 /* If we're using split pte locks, then take the page's lock and
1112    return a pointer to it.  Otherwise return NULL. */
1113 static spinlock_t *xen_pte_lock(struct page *page, struct mm_struct *mm)
1114 {
1115         spinlock_t *ptl = NULL;
1116
1117 #if USE_SPLIT_PTLOCKS
1118         ptl = __pte_lockptr(page);
1119         spin_lock_nest_lock(ptl, &mm->page_table_lock);
1120 #endif
1121
1122         return ptl;
1123 }
1124
1125 static void xen_pte_unlock(void *v)
1126 {
1127         spinlock_t *ptl = v;
1128         spin_unlock(ptl);
1129 }
1130
1131 static void xen_do_pin(unsigned level, unsigned long pfn)
1132 {
1133         struct mmuext_op *op;
1134         struct multicall_space mcs;
1135
1136         mcs = __xen_mc_entry(sizeof(*op));
1137         op = mcs.args;
1138         op->cmd = level;
1139         op->arg1.mfn = pfn_to_mfn(pfn);
1140         MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
1141 }
1142
1143 static int xen_pin_page(struct mm_struct *mm, struct page *page,
1144                         enum pt_level level)
1145 {
1146         unsigned pgfl = TestSetPagePinned(page);
1147         int flush;
1148
1149         if (pgfl)
1150                 flush = 0;              /* already pinned */
1151         else if (PageHighMem(page))
1152                 /* kmaps need flushing if we found an unpinned
1153                    highpage */
1154                 flush = 1;
1155         else {
1156                 void *pt = lowmem_page_address(page);
1157                 unsigned long pfn = page_to_pfn(page);
1158                 struct multicall_space mcs = __xen_mc_entry(0);
1159                 spinlock_t *ptl;
1160
1161                 flush = 0;
1162
1163                 /*
1164                  * We need to hold the pagetable lock between the time
1165                  * we make the pagetable RO and when we actually pin
1166                  * it.  If we don't, then other users may come in and
1167                  * attempt to update the pagetable by writing it,
1168                  * which will fail because the memory is RO but not
1169                  * pinned, so Xen won't do the trap'n'emulate.
1170                  *
1171                  * If we're using split pte locks, we can't hold the
1172                  * entire pagetable's worth of locks during the
1173                  * traverse, because we may wrap the preempt count (8
1174                  * bits).  The solution is to mark RO and pin each PTE
1175                  * page while holding the lock.  This means the number
1176                  * of locks we end up holding is never more than a
1177                  * batch size (~32 entries, at present).
1178                  *
1179                  * If we're not using split pte locks, we needn't pin
1180                  * the PTE pages independently, because we're
1181                  * protected by the overall pagetable lock.
1182                  */
1183                 ptl = NULL;
1184                 if (level == PT_PTE)
1185                         ptl = xen_pte_lock(page, mm);
1186
1187                 MULTI_update_va_mapping(mcs.mc, (unsigned long)pt,
1188                                         pfn_pte(pfn, PAGE_KERNEL_RO),
1189                                         level == PT_PGD ? UVMF_TLB_FLUSH : 0);
1190
1191                 if (ptl) {
1192                         xen_do_pin(MMUEXT_PIN_L1_TABLE, pfn);
1193
1194                         /* Queue a deferred unlock for when this batch
1195                            is completed. */
1196                         xen_mc_callback(xen_pte_unlock, ptl);
1197                 }
1198         }
1199
1200         return flush;
1201 }
1202
1203 /* This is called just after a mm has been created, but it has not
1204    been used yet.  We need to make sure that its pagetable is all
1205    read-only, and can be pinned. */
1206 static void __xen_pgd_pin(struct mm_struct *mm, pgd_t *pgd)
1207 {
1208         xen_mc_batch();
1209
1210         if (__xen_pgd_walk(mm, pgd, xen_pin_page, USER_LIMIT)) {
1211                 /* re-enable interrupts for flushing */
1212                 xen_mc_issue(0);
1213
1214                 kmap_flush_unused();
1215
1216                 xen_mc_batch();
1217         }
1218
1219 #ifdef CONFIG_X86_64
1220         {
1221                 pgd_t *user_pgd = xen_get_user_pgd(pgd);
1222
1223                 xen_do_pin(MMUEXT_PIN_L4_TABLE, PFN_DOWN(__pa(pgd)));
1224
1225                 if (user_pgd) {
1226                         xen_pin_page(mm, virt_to_page(user_pgd), PT_PGD);
1227                         xen_do_pin(MMUEXT_PIN_L4_TABLE,
1228                                    PFN_DOWN(__pa(user_pgd)));
1229                 }
1230         }
1231 #else /* CONFIG_X86_32 */
1232 #ifdef CONFIG_X86_PAE
1233         /* Need to make sure unshared kernel PMD is pinnable */
1234         xen_pin_page(mm, pgd_page(pgd[pgd_index(TASK_SIZE)]),
1235                      PT_PMD);
1236 #endif
1237         xen_do_pin(MMUEXT_PIN_L3_TABLE, PFN_DOWN(__pa(pgd)));
1238 #endif /* CONFIG_X86_64 */
1239         xen_mc_issue(0);
1240 }
1241
1242 static void xen_pgd_pin(struct mm_struct *mm)
1243 {
1244         __xen_pgd_pin(mm, mm->pgd);
1245 }
1246
1247 /*
1248  * On save, we need to pin all pagetables to make sure they get their
1249  * mfns turned into pfns.  Search the list for any unpinned pgds and pin
1250  * them (unpinned pgds are not currently in use, probably because the
1251  * process is under construction or destruction).
1252  *
1253  * Expected to be called in stop_machine() ("equivalent to taking
1254  * every spinlock in the system"), so the locking doesn't really
1255  * matter all that much.
1256  */
1257 void xen_mm_pin_all(void)
1258 {
1259         unsigned long flags;
1260         struct page *page;
1261
1262         spin_lock_irqsave(&pgd_lock, flags);
1263
1264         list_for_each_entry(page, &pgd_list, lru) {
1265                 if (!PagePinned(page)) {
1266                         __xen_pgd_pin(&init_mm, (pgd_t *)page_address(page));
1267                         SetPageSavePinned(page);
1268                 }
1269         }
1270
1271         spin_unlock_irqrestore(&pgd_lock, flags);
1272 }
1273
1274 /*
1275  * The init_mm pagetable is really pinned as soon as its created, but
1276  * that's before we have page structures to store the bits.  So do all
1277  * the book-keeping now.
1278  */
1279 static __init int xen_mark_pinned(struct mm_struct *mm, struct page *page,
1280                                   enum pt_level level)
1281 {
1282         SetPagePinned(page);
1283         return 0;
1284 }
1285
1286 static void __init xen_mark_init_mm_pinned(void)
1287 {
1288         xen_pgd_walk(&init_mm, xen_mark_pinned, FIXADDR_TOP);
1289 }
1290
1291 static int xen_unpin_page(struct mm_struct *mm, struct page *page,
1292                           enum pt_level level)
1293 {
1294         unsigned pgfl = TestClearPagePinned(page);
1295
1296         if (pgfl && !PageHighMem(page)) {
1297                 void *pt = lowmem_page_address(page);
1298                 unsigned long pfn = page_to_pfn(page);
1299                 spinlock_t *ptl = NULL;
1300                 struct multicall_space mcs;
1301
1302                 /*
1303                  * Do the converse to pin_page.  If we're using split
1304                  * pte locks, we must be holding the lock for while
1305                  * the pte page is unpinned but still RO to prevent
1306                  * concurrent updates from seeing it in this
1307                  * partially-pinned state.
1308                  */
1309                 if (level == PT_PTE) {
1310                         ptl = xen_pte_lock(page, mm);
1311
1312                         if (ptl)
1313                                 xen_do_pin(MMUEXT_UNPIN_TABLE, pfn);
1314                 }
1315
1316                 mcs = __xen_mc_entry(0);
1317
1318                 MULTI_update_va_mapping(mcs.mc, (unsigned long)pt,
1319                                         pfn_pte(pfn, PAGE_KERNEL),
1320                                         level == PT_PGD ? UVMF_TLB_FLUSH : 0);
1321
1322                 if (ptl) {
1323                         /* unlock when batch completed */
1324                         xen_mc_callback(xen_pte_unlock, ptl);
1325                 }
1326         }
1327
1328         return 0;               /* never need to flush on unpin */
1329 }
1330
1331 /* Release a pagetables pages back as normal RW */
1332 static void __xen_pgd_unpin(struct mm_struct *mm, pgd_t *pgd)
1333 {
1334         xen_mc_batch();
1335
1336         xen_do_pin(MMUEXT_UNPIN_TABLE, PFN_DOWN(__pa(pgd)));
1337
1338 #ifdef CONFIG_X86_64
1339         {
1340                 pgd_t *user_pgd = xen_get_user_pgd(pgd);
1341
1342                 if (user_pgd) {
1343                         xen_do_pin(MMUEXT_UNPIN_TABLE,
1344                                    PFN_DOWN(__pa(user_pgd)));
1345                         xen_unpin_page(mm, virt_to_page(user_pgd), PT_PGD);
1346                 }
1347         }
1348 #endif
1349
1350 #ifdef CONFIG_X86_PAE
1351         /* Need to make sure unshared kernel PMD is unpinned */
1352         xen_unpin_page(mm, pgd_page(pgd[pgd_index(TASK_SIZE)]),
1353                        PT_PMD);
1354 #endif
1355
1356         __xen_pgd_walk(mm, pgd, xen_unpin_page, USER_LIMIT);
1357
1358         xen_mc_issue(0);
1359 }
1360
1361 static void xen_pgd_unpin(struct mm_struct *mm)
1362 {
1363         __xen_pgd_unpin(mm, mm->pgd);
1364 }
1365
1366 /*
1367  * On resume, undo any pinning done at save, so that the rest of the
1368  * kernel doesn't see any unexpected pinned pagetables.
1369  */
1370 void xen_mm_unpin_all(void)
1371 {
1372         unsigned long flags;
1373         struct page *page;
1374
1375         spin_lock_irqsave(&pgd_lock, flags);
1376
1377         list_for_each_entry(page, &pgd_list, lru) {
1378                 if (PageSavePinned(page)) {
1379                         BUG_ON(!PagePinned(page));
1380                         __xen_pgd_unpin(&init_mm, (pgd_t *)page_address(page));
1381                         ClearPageSavePinned(page);
1382                 }
1383         }
1384
1385         spin_unlock_irqrestore(&pgd_lock, flags);
1386 }
1387
1388 void xen_activate_mm(struct mm_struct *prev, struct mm_struct *next)
1389 {
1390         spin_lock(&next->page_table_lock);
1391         xen_pgd_pin(next);
1392         spin_unlock(&next->page_table_lock);
1393 }
1394
1395 void xen_dup_mmap(struct mm_struct *oldmm, struct mm_struct *mm)
1396 {
1397         spin_lock(&mm->page_table_lock);
1398         xen_pgd_pin(mm);
1399         spin_unlock(&mm->page_table_lock);
1400 }
1401
1402
1403 #ifdef CONFIG_SMP
1404 /* Another cpu may still have their %cr3 pointing at the pagetable, so
1405    we need to repoint it somewhere else before we can unpin it. */
1406 static void drop_other_mm_ref(void *info)
1407 {
1408         struct mm_struct *mm = info;
1409         struct mm_struct *active_mm;
1410
1411         active_mm = percpu_read(cpu_tlbstate.active_mm);
1412
1413         if (active_mm == mm)
1414                 leave_mm(smp_processor_id());
1415
1416         /* If this cpu still has a stale cr3 reference, then make sure
1417            it has been flushed. */
1418         if (percpu_read(xen_current_cr3) == __pa(mm->pgd))
1419                 load_cr3(swapper_pg_dir);
1420 }
1421
1422 static void xen_drop_mm_ref(struct mm_struct *mm)
1423 {
1424         cpumask_var_t mask;
1425         unsigned cpu;
1426
1427         if (current->active_mm == mm) {
1428                 if (current->mm == mm)
1429                         load_cr3(swapper_pg_dir);
1430                 else
1431                         leave_mm(smp_processor_id());
1432         }
1433
1434         /* Get the "official" set of cpus referring to our pagetable. */
1435         if (!alloc_cpumask_var(&mask, GFP_ATOMIC)) {
1436                 for_each_online_cpu(cpu) {
1437                         if (!cpumask_test_cpu(cpu, mm_cpumask(mm))
1438                             && per_cpu(xen_current_cr3, cpu) != __pa(mm->pgd))
1439                                 continue;
1440                         smp_call_function_single(cpu, drop_other_mm_ref, mm, 1);
1441                 }
1442                 return;
1443         }
1444         cpumask_copy(mask, mm_cpumask(mm));
1445
1446         /* It's possible that a vcpu may have a stale reference to our
1447            cr3, because its in lazy mode, and it hasn't yet flushed
1448            its set of pending hypercalls yet.  In this case, we can
1449            look at its actual current cr3 value, and force it to flush
1450            if needed. */
1451         for_each_online_cpu(cpu) {
1452                 if (per_cpu(xen_current_cr3, cpu) == __pa(mm->pgd))
1453                         cpumask_set_cpu(cpu, mask);
1454         }
1455
1456         if (!cpumask_empty(mask))
1457                 smp_call_function_many(mask, drop_other_mm_ref, mm, 1);
1458         free_cpumask_var(mask);
1459 }
1460 #else
1461 static void xen_drop_mm_ref(struct mm_struct *mm)
1462 {
1463         if (current->active_mm == mm)
1464                 load_cr3(swapper_pg_dir);
1465 }
1466 #endif
1467
1468 /*
1469  * While a process runs, Xen pins its pagetables, which means that the
1470  * hypervisor forces it to be read-only, and it controls all updates
1471  * to it.  This means that all pagetable updates have to go via the
1472  * hypervisor, which is moderately expensive.
1473  *
1474  * Since we're pulling the pagetable down, we switch to use init_mm,
1475  * unpin old process pagetable and mark it all read-write, which
1476  * allows further operations on it to be simple memory accesses.
1477  *
1478  * The only subtle point is that another CPU may be still using the
1479  * pagetable because of lazy tlb flushing.  This means we need need to
1480  * switch all CPUs off this pagetable before we can unpin it.
1481  */
1482 void xen_exit_mmap(struct mm_struct *mm)
1483 {
1484         get_cpu();              /* make sure we don't move around */
1485         xen_drop_mm_ref(mm);
1486         put_cpu();
1487
1488         spin_lock(&mm->page_table_lock);
1489
1490         /* pgd may not be pinned in the error exit path of execve */
1491         if (xen_page_pinned(mm->pgd))
1492                 xen_pgd_unpin(mm);
1493
1494         spin_unlock(&mm->page_table_lock);
1495 }
1496
1497 static __init void xen_pagetable_setup_start(pgd_t *base)
1498 {
1499 }
1500
1501 static void xen_post_allocator_init(void);
1502
1503 static __init void xen_pagetable_setup_done(pgd_t *base)
1504 {
1505         xen_setup_shared_info();
1506         xen_post_allocator_init();
1507 }
1508
1509 static void xen_write_cr2(unsigned long cr2)
1510 {
1511         percpu_read(xen_vcpu)->arch.cr2 = cr2;
1512 }
1513
1514 static unsigned long xen_read_cr2(void)
1515 {
1516         return percpu_read(xen_vcpu)->arch.cr2;
1517 }
1518
1519 unsigned long xen_read_cr2_direct(void)
1520 {
1521         return percpu_read(xen_vcpu_info.arch.cr2);
1522 }
1523
1524 static void xen_flush_tlb(void)
1525 {
1526         struct mmuext_op *op;
1527         struct multicall_space mcs;
1528
1529         preempt_disable();
1530
1531         mcs = xen_mc_entry(sizeof(*op));
1532
1533         op = mcs.args;
1534         op->cmd = MMUEXT_TLB_FLUSH_LOCAL;
1535         MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
1536
1537         xen_mc_issue(PARAVIRT_LAZY_MMU);
1538
1539         preempt_enable();
1540 }
1541
1542 static void xen_flush_tlb_single(unsigned long addr)
1543 {
1544         struct mmuext_op *op;
1545         struct multicall_space mcs;
1546
1547         preempt_disable();
1548
1549         mcs = xen_mc_entry(sizeof(*op));
1550         op = mcs.args;
1551         op->cmd = MMUEXT_INVLPG_LOCAL;
1552         op->arg1.linear_addr = addr & PAGE_MASK;
1553         MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
1554
1555         xen_mc_issue(PARAVIRT_LAZY_MMU);
1556
1557         preempt_enable();
1558 }
1559
1560 static void xen_flush_tlb_others(const struct cpumask *cpus,
1561                                  struct mm_struct *mm, unsigned long va)
1562 {
1563         struct {
1564                 struct mmuext_op op;
1565                 DECLARE_BITMAP(mask, NR_CPUS);
1566         } *args;
1567         struct multicall_space mcs;
1568
1569         if (cpumask_empty(cpus))
1570                 return;         /* nothing to do */
1571
1572         mcs = xen_mc_entry(sizeof(*args));
1573         args = mcs.args;
1574         args->op.arg2.vcpumask = to_cpumask(args->mask);
1575
1576         /* Remove us, and any offline CPUS. */
1577         cpumask_and(to_cpumask(args->mask), cpus, cpu_online_mask);
1578         cpumask_clear_cpu(smp_processor_id(), to_cpumask(args->mask));
1579
1580         if (va == TLB_FLUSH_ALL) {
1581                 args->op.cmd = MMUEXT_TLB_FLUSH_MULTI;
1582         } else {
1583                 args->op.cmd = MMUEXT_INVLPG_MULTI;
1584                 args->op.arg1.linear_addr = va;
1585         }
1586
1587         MULTI_mmuext_op(mcs.mc, &args->op, 1, NULL, DOMID_SELF);
1588
1589         xen_mc_issue(PARAVIRT_LAZY_MMU);
1590 }
1591
1592 static unsigned long xen_read_cr3(void)
1593 {
1594         return percpu_read(xen_cr3);
1595 }
1596
1597 static void set_current_cr3(void *v)
1598 {
1599         percpu_write(xen_current_cr3, (unsigned long)v);
1600 }
1601
1602 static void __xen_write_cr3(bool kernel, unsigned long cr3)
1603 {
1604         struct mmuext_op *op;
1605         struct multicall_space mcs;
1606         unsigned long mfn;
1607
1608         if (cr3)
1609                 mfn = pfn_to_mfn(PFN_DOWN(cr3));
1610         else
1611                 mfn = 0;
1612
1613         WARN_ON(mfn == 0 && kernel);
1614
1615         mcs = __xen_mc_entry(sizeof(*op));
1616
1617         op = mcs.args;
1618         op->cmd = kernel ? MMUEXT_NEW_BASEPTR : MMUEXT_NEW_USER_BASEPTR;
1619         op->arg1.mfn = mfn;
1620
1621         MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
1622
1623         if (kernel) {
1624                 percpu_write(xen_cr3, cr3);
1625
1626                 /* Update xen_current_cr3 once the batch has actually
1627                    been submitted. */
1628                 xen_mc_callback(set_current_cr3, (void *)cr3);
1629         }
1630 }
1631
1632 static void xen_write_cr3(unsigned long cr3)
1633 {
1634         BUG_ON(preemptible());
1635
1636         xen_mc_batch();  /* disables interrupts */
1637
1638         /* Update while interrupts are disabled, so its atomic with
1639            respect to ipis */
1640         percpu_write(xen_cr3, cr3);
1641
1642         __xen_write_cr3(true, cr3);
1643
1644 #ifdef CONFIG_X86_64
1645         {
1646                 pgd_t *user_pgd = xen_get_user_pgd(__va(cr3));
1647                 if (user_pgd)
1648                         __xen_write_cr3(false, __pa(user_pgd));
1649                 else
1650                         __xen_write_cr3(false, 0);
1651         }
1652 #endif
1653
1654         xen_mc_issue(PARAVIRT_LAZY_CPU);  /* interrupts restored */
1655 }
1656
1657 static int xen_pgd_alloc(struct mm_struct *mm)
1658 {
1659         pgd_t *pgd = mm->pgd;
1660         int ret = 0;
1661
1662         BUG_ON(PagePinned(virt_to_page(pgd)));
1663
1664 #ifdef CONFIG_X86_64
1665         {
1666                 struct page *page = virt_to_page(pgd);
1667                 pgd_t *user_pgd;
1668
1669                 BUG_ON(page->private != 0);
1670
1671                 ret = -ENOMEM;
1672
1673                 user_pgd = (pgd_t *)__get_free_page(GFP_KERNEL | __GFP_ZERO);
1674                 page->private = (unsigned long)user_pgd;
1675
1676                 if (user_pgd != NULL) {
1677                         user_pgd[pgd_index(VSYSCALL_START)] =
1678                                 __pgd(__pa(level3_user_vsyscall) | _PAGE_TABLE);
1679                         ret = 0;
1680                 }
1681
1682                 BUG_ON(PagePinned(virt_to_page(xen_get_user_pgd(pgd))));
1683         }
1684 #endif
1685
1686         return ret;
1687 }
1688
1689 static void xen_pgd_free(struct mm_struct *mm, pgd_t *pgd)
1690 {
1691 #ifdef CONFIG_X86_64
1692         pgd_t *user_pgd = xen_get_user_pgd(pgd);
1693
1694         if (user_pgd)
1695                 free_page((unsigned long)user_pgd);
1696 #endif
1697 }
1698
1699 #ifdef CONFIG_X86_32
1700 static __init pte_t mask_rw_pte(pte_t *ptep, pte_t pte)
1701 {
1702         /* If there's an existing pte, then don't allow _PAGE_RW to be set */
1703         if (pte_val_ma(*ptep) & _PAGE_PRESENT)
1704                 pte = __pte_ma(((pte_val_ma(*ptep) & _PAGE_RW) | ~_PAGE_RW) &
1705                                pte_val_ma(pte));
1706
1707         return pte;
1708 }
1709
1710 /* Init-time set_pte while constructing initial pagetables, which
1711    doesn't allow RO pagetable pages to be remapped RW */
1712 static __init void xen_set_pte_init(pte_t *ptep, pte_t pte)
1713 {
1714         pte = mask_rw_pte(ptep, pte);
1715
1716         xen_set_pte(ptep, pte);
1717 }
1718 #endif
1719
1720 static void pin_pagetable_pfn(unsigned cmd, unsigned long pfn)
1721 {
1722         struct mmuext_op op;
1723         op.cmd = cmd;
1724         op.arg1.mfn = pfn_to_mfn(pfn);
1725         if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF))
1726                 BUG();
1727 }
1728
1729 /* Early in boot, while setting up the initial pagetable, assume
1730    everything is pinned. */
1731 static __init void xen_alloc_pte_init(struct mm_struct *mm, unsigned long pfn)
1732 {
1733 #ifdef CONFIG_FLATMEM
1734         BUG_ON(mem_map);        /* should only be used early */
1735 #endif
1736         make_lowmem_page_readonly(__va(PFN_PHYS(pfn)));
1737         pin_pagetable_pfn(MMUEXT_PIN_L1_TABLE, pfn);
1738 }
1739
1740 /* Used for pmd and pud */
1741 static __init void xen_alloc_pmd_init(struct mm_struct *mm, unsigned long pfn)
1742 {
1743 #ifdef CONFIG_FLATMEM
1744         BUG_ON(mem_map);        /* should only be used early */
1745 #endif
1746         make_lowmem_page_readonly(__va(PFN_PHYS(pfn)));
1747 }
1748
1749 /* Early release_pte assumes that all pts are pinned, since there's
1750    only init_mm and anything attached to that is pinned. */
1751 static __init void xen_release_pte_init(unsigned long pfn)
1752 {
1753         pin_pagetable_pfn(MMUEXT_UNPIN_TABLE, pfn);
1754         make_lowmem_page_readwrite(__va(PFN_PHYS(pfn)));
1755 }
1756
1757 static __init void xen_release_pmd_init(unsigned long pfn)
1758 {
1759         make_lowmem_page_readwrite(__va(PFN_PHYS(pfn)));
1760 }
1761
1762 /* This needs to make sure the new pte page is pinned iff its being
1763    attached to a pinned pagetable. */
1764 static void xen_alloc_ptpage(struct mm_struct *mm, unsigned long pfn, unsigned level)
1765 {
1766         struct page *page = pfn_to_page(pfn);
1767
1768         if (PagePinned(virt_to_page(mm->pgd))) {
1769                 SetPagePinned(page);
1770
1771                 if (!PageHighMem(page)) {
1772                         make_lowmem_page_readonly(__va(PFN_PHYS((unsigned long)pfn)));
1773                         if (level == PT_PTE && USE_SPLIT_PTLOCKS)
1774                                 pin_pagetable_pfn(MMUEXT_PIN_L1_TABLE, pfn);
1775                 } else {
1776                         /* make sure there are no stray mappings of
1777                            this page */
1778                         kmap_flush_unused();
1779                 }
1780         }
1781 }
1782
1783 static void xen_alloc_pte(struct mm_struct *mm, unsigned long pfn)
1784 {
1785         xen_alloc_ptpage(mm, pfn, PT_PTE);
1786 }
1787
1788 static void xen_alloc_pmd(struct mm_struct *mm, unsigned long pfn)
1789 {
1790         xen_alloc_ptpage(mm, pfn, PT_PMD);
1791 }
1792
1793 /* This should never happen until we're OK to use struct page */
1794 static void xen_release_ptpage(unsigned long pfn, unsigned level)
1795 {
1796         struct page *page = pfn_to_page(pfn);
1797
1798         if (PagePinned(page)) {
1799                 if (!PageHighMem(page)) {
1800                         if (level == PT_PTE && USE_SPLIT_PTLOCKS)
1801                                 pin_pagetable_pfn(MMUEXT_UNPIN_TABLE, pfn);
1802                         make_lowmem_page_readwrite(__va(PFN_PHYS(pfn)));
1803                 }
1804                 ClearPagePinned(page);
1805         }
1806 }
1807
1808 static void xen_release_pte(unsigned long pfn)
1809 {
1810         xen_release_ptpage(pfn, PT_PTE);
1811 }
1812
1813 static void xen_release_pmd(unsigned long pfn)
1814 {
1815         xen_release_ptpage(pfn, PT_PMD);
1816 }
1817
1818 #if PAGETABLE_LEVELS == 4
1819 static void xen_alloc_pud(struct mm_struct *mm, unsigned long pfn)
1820 {
1821         xen_alloc_ptpage(mm, pfn, PT_PUD);
1822 }
1823
1824 static void xen_release_pud(unsigned long pfn)
1825 {
1826         xen_release_ptpage(pfn, PT_PUD);
1827 }
1828 #endif
1829
1830 void __init xen_reserve_top(void)
1831 {
1832 #ifdef CONFIG_X86_32
1833         unsigned long top = HYPERVISOR_VIRT_START;
1834         struct xen_platform_parameters pp;
1835
1836         if (HYPERVISOR_xen_version(XENVER_platform_parameters, &pp) == 0)
1837                 top = pp.virt_start;
1838
1839         reserve_top_address(-top);
1840 #endif  /* CONFIG_X86_32 */
1841 }
1842
1843 /*
1844  * Like __va(), but returns address in the kernel mapping (which is
1845  * all we have until the physical memory mapping has been set up.
1846  */
1847 static void *__ka(phys_addr_t paddr)
1848 {
1849 #ifdef CONFIG_X86_64
1850         return (void *)(paddr + __START_KERNEL_map);
1851 #else
1852         return __va(paddr);
1853 #endif
1854 }
1855
1856 /* Convert a machine address to physical address */
1857 static unsigned long m2p(phys_addr_t maddr)
1858 {
1859         phys_addr_t paddr;
1860
1861         maddr &= PTE_PFN_MASK;
1862         paddr = mfn_to_pfn(maddr >> PAGE_SHIFT) << PAGE_SHIFT;
1863
1864         return paddr;
1865 }
1866
1867 /* Convert a machine address to kernel virtual */
1868 static void *m2v(phys_addr_t maddr)
1869 {
1870         return __ka(m2p(maddr));
1871 }
1872
1873 static void set_page_prot(void *addr, pgprot_t prot)
1874 {
1875         unsigned long pfn = __pa(addr) >> PAGE_SHIFT;
1876         pte_t pte = pfn_pte(pfn, prot);
1877
1878         if (HYPERVISOR_update_va_mapping((unsigned long)addr, pte, 0))
1879                 BUG();
1880 }
1881
1882 static __init void xen_map_identity_early(pmd_t *pmd, unsigned long max_pfn)
1883 {
1884         unsigned pmdidx, pteidx;
1885         unsigned ident_pte;
1886         unsigned long pfn;
1887
1888         level1_ident_pgt = extend_brk(sizeof(pte_t) * LEVEL1_IDENT_ENTRIES,
1889                                       PAGE_SIZE);
1890
1891         ident_pte = 0;
1892         pfn = 0;
1893         for (pmdidx = 0; pmdidx < PTRS_PER_PMD && pfn < max_pfn; pmdidx++) {
1894                 pte_t *pte_page;
1895
1896                 /* Reuse or allocate a page of ptes */
1897                 if (pmd_present(pmd[pmdidx]))
1898                         pte_page = m2v(pmd[pmdidx].pmd);
1899                 else {
1900                         /* Check for free pte pages */
1901                         if (ident_pte == LEVEL1_IDENT_ENTRIES)
1902                                 break;
1903
1904                         pte_page = &level1_ident_pgt[ident_pte];
1905                         ident_pte += PTRS_PER_PTE;
1906
1907                         pmd[pmdidx] = __pmd(__pa(pte_page) | _PAGE_TABLE);
1908                 }
1909
1910                 /* Install mappings */
1911                 for (pteidx = 0; pteidx < PTRS_PER_PTE; pteidx++, pfn++) {
1912                         pte_t pte;
1913
1914                         if (pfn > max_pfn_mapped)
1915                                 max_pfn_mapped = pfn;
1916
1917                         if (!pte_none(pte_page[pteidx]))
1918                                 continue;
1919
1920                         pte = pfn_pte(pfn, PAGE_KERNEL_EXEC);
1921                         pte_page[pteidx] = pte;
1922                 }
1923         }
1924
1925         for (pteidx = 0; pteidx < ident_pte; pteidx += PTRS_PER_PTE)
1926                 set_page_prot(&level1_ident_pgt[pteidx], PAGE_KERNEL_RO);
1927
1928         set_page_prot(pmd, PAGE_KERNEL_RO);
1929 }
1930
1931 #ifdef CONFIG_X86_64
1932 static void convert_pfn_mfn(void *v)
1933 {
1934         pte_t *pte = v;
1935         int i;
1936
1937         /* All levels are converted the same way, so just treat them
1938            as ptes. */
1939         for (i = 0; i < PTRS_PER_PTE; i++)
1940                 pte[i] = xen_make_pte(pte[i].pte);
1941 }
1942
1943 /*
1944  * Set up the inital kernel pagetable.
1945  *
1946  * We can construct this by grafting the Xen provided pagetable into
1947  * head_64.S's preconstructed pagetables.  We copy the Xen L2's into
1948  * level2_ident_pgt, level2_kernel_pgt and level2_fixmap_pgt.  This
1949  * means that only the kernel has a physical mapping to start with -
1950  * but that's enough to get __va working.  We need to fill in the rest
1951  * of the physical mapping once some sort of allocator has been set
1952  * up.
1953  */
1954 __init pgd_t *xen_setup_kernel_pagetable(pgd_t *pgd,
1955                                          unsigned long max_pfn)
1956 {
1957         pud_t *l3;
1958         pmd_t *l2;
1959
1960         /* Zap identity mapping */
1961         init_level4_pgt[0] = __pgd(0);
1962
1963         /* Pre-constructed entries are in pfn, so convert to mfn */
1964         convert_pfn_mfn(init_level4_pgt);
1965         convert_pfn_mfn(level3_ident_pgt);
1966         convert_pfn_mfn(level3_kernel_pgt);
1967
1968         l3 = m2v(pgd[pgd_index(__START_KERNEL_map)].pgd);
1969         l2 = m2v(l3[pud_index(__START_KERNEL_map)].pud);
1970
1971         memcpy(level2_ident_pgt, l2, sizeof(pmd_t) * PTRS_PER_PMD);
1972         memcpy(level2_kernel_pgt, l2, sizeof(pmd_t) * PTRS_PER_PMD);
1973
1974         l3 = m2v(pgd[pgd_index(__START_KERNEL_map + PMD_SIZE)].pgd);
1975         l2 = m2v(l3[pud_index(__START_KERNEL_map + PMD_SIZE)].pud);
1976         memcpy(level2_fixmap_pgt, l2, sizeof(pmd_t) * PTRS_PER_PMD);
1977
1978         /* Set up identity map */
1979         xen_map_identity_early(level2_ident_pgt, max_pfn);
1980
1981         /* Make pagetable pieces RO */
1982         set_page_prot(init_level4_pgt, PAGE_KERNEL_RO);
1983         set_page_prot(level3_ident_pgt, PAGE_KERNEL_RO);
1984         set_page_prot(level3_kernel_pgt, PAGE_KERNEL_RO);
1985         set_page_prot(level3_user_vsyscall, PAGE_KERNEL_RO);
1986         set_page_prot(level2_kernel_pgt, PAGE_KERNEL_RO);
1987         set_page_prot(level2_fixmap_pgt, PAGE_KERNEL_RO);
1988
1989         /* Pin down new L4 */
1990         pin_pagetable_pfn(MMUEXT_PIN_L4_TABLE,
1991                           PFN_DOWN(__pa_symbol(init_level4_pgt)));
1992
1993         /* Unpin Xen-provided one */
1994         pin_pagetable_pfn(MMUEXT_UNPIN_TABLE, PFN_DOWN(__pa(pgd)));
1995
1996         /* Switch over */
1997         pgd = init_level4_pgt;
1998
1999         /*
2000          * At this stage there can be no user pgd, and no page
2001          * structure to attach it to, so make sure we just set kernel
2002          * pgd.
2003          */
2004         xen_mc_batch();
2005         __xen_write_cr3(true, __pa(pgd));
2006         xen_mc_issue(PARAVIRT_LAZY_CPU);
2007
2008         reserve_early(__pa(xen_start_info->pt_base),
2009                       __pa(xen_start_info->pt_base +
2010                            xen_start_info->nr_pt_frames * PAGE_SIZE),
2011                       "XEN PAGETABLES");
2012
2013         return pgd;
2014 }
2015 #else   /* !CONFIG_X86_64 */
2016 static RESERVE_BRK_ARRAY(pmd_t, level2_kernel_pgt, PTRS_PER_PMD);
2017
2018 __init pgd_t *xen_setup_kernel_pagetable(pgd_t *pgd,
2019                                          unsigned long max_pfn)
2020 {
2021         pmd_t *kernel_pmd;
2022
2023         level2_kernel_pgt = extend_brk(sizeof(pmd_t *) * PTRS_PER_PMD, PAGE_SIZE);
2024
2025         max_pfn_mapped = PFN_DOWN(__pa(xen_start_info->pt_base) +
2026                                   xen_start_info->nr_pt_frames * PAGE_SIZE +
2027                                   512*1024);
2028
2029         kernel_pmd = m2v(pgd[KERNEL_PGD_BOUNDARY].pgd);
2030         memcpy(level2_kernel_pgt, kernel_pmd, sizeof(pmd_t) * PTRS_PER_PMD);
2031
2032         xen_map_identity_early(level2_kernel_pgt, max_pfn);
2033
2034         memcpy(swapper_pg_dir, pgd, sizeof(pgd_t) * PTRS_PER_PGD);
2035         set_pgd(&swapper_pg_dir[KERNEL_PGD_BOUNDARY],
2036                         __pgd(__pa(level2_kernel_pgt) | _PAGE_PRESENT));
2037
2038         set_page_prot(level2_kernel_pgt, PAGE_KERNEL_RO);
2039         set_page_prot(swapper_pg_dir, PAGE_KERNEL_RO);
2040         set_page_prot(empty_zero_page, PAGE_KERNEL_RO);
2041
2042         pin_pagetable_pfn(MMUEXT_UNPIN_TABLE, PFN_DOWN(__pa(pgd)));
2043
2044         xen_write_cr3(__pa(swapper_pg_dir));
2045
2046         pin_pagetable_pfn(MMUEXT_PIN_L3_TABLE, PFN_DOWN(__pa(swapper_pg_dir)));
2047
2048         reserve_early(__pa(xen_start_info->pt_base),
2049                       __pa(xen_start_info->pt_base +
2050                            xen_start_info->nr_pt_frames * PAGE_SIZE),
2051                       "XEN PAGETABLES");
2052
2053         return swapper_pg_dir;
2054 }
2055 #endif  /* CONFIG_X86_64 */
2056
2057 static void xen_set_fixmap(unsigned idx, phys_addr_t phys, pgprot_t prot)
2058 {
2059         pte_t pte;
2060
2061         phys >>= PAGE_SHIFT;
2062
2063         switch (idx) {
2064         case FIX_BTMAP_END ... FIX_BTMAP_BEGIN:
2065 #ifdef CONFIG_X86_F00F_BUG
2066         case FIX_F00F_IDT:
2067 #endif
2068 #ifdef CONFIG_X86_32
2069         case FIX_WP_TEST:
2070         case FIX_VDSO:
2071 # ifdef CONFIG_HIGHMEM
2072         case FIX_KMAP_BEGIN ... FIX_KMAP_END:
2073 # endif
2074 #else
2075         case VSYSCALL_LAST_PAGE ... VSYSCALL_FIRST_PAGE:
2076 #endif
2077 #ifdef CONFIG_X86_LOCAL_APIC
2078         case FIX_APIC_BASE:     /* maps dummy local APIC */
2079 #endif
2080         case FIX_TEXT_POKE0:
2081         case FIX_TEXT_POKE1:
2082                 /* All local page mappings */
2083                 pte = pfn_pte(phys, prot);
2084                 break;
2085
2086         case FIX_PARAVIRT_BOOTMAP:
2087                 /* This is an MFN, but it isn't an IO mapping from the
2088                    IO domain */
2089                 pte = mfn_pte(phys, prot);
2090                 break;
2091
2092         default:
2093                 /* By default, set_fixmap is used for hardware mappings */
2094                 pte = mfn_pte(phys, __pgprot(pgprot_val(prot) | _PAGE_IOMAP));
2095                 break;
2096         }
2097
2098         __native_set_fixmap(idx, pte);
2099
2100 #ifdef CONFIG_X86_64
2101         /* Replicate changes to map the vsyscall page into the user
2102            pagetable vsyscall mapping. */
2103         if (idx >= VSYSCALL_LAST_PAGE && idx <= VSYSCALL_FIRST_PAGE) {
2104                 unsigned long vaddr = __fix_to_virt(idx);
2105                 set_pte_vaddr_pud(level3_user_vsyscall, vaddr, pte);
2106         }
2107 #endif
2108 }
2109
2110 static __init void xen_post_allocator_init(void)
2111 {
2112         pv_mmu_ops.set_pte = xen_set_pte;
2113         pv_mmu_ops.set_pmd = xen_set_pmd;
2114         pv_mmu_ops.set_pud = xen_set_pud;
2115 #if PAGETABLE_LEVELS == 4
2116         pv_mmu_ops.set_pgd = xen_set_pgd;
2117 #endif
2118
2119         /* This will work as long as patching hasn't happened yet
2120            (which it hasn't) */
2121         pv_mmu_ops.alloc_pte = xen_alloc_pte;
2122         pv_mmu_ops.alloc_pmd = xen_alloc_pmd;
2123         pv_mmu_ops.release_pte = xen_release_pte;
2124         pv_mmu_ops.release_pmd = xen_release_pmd;
2125 #if PAGETABLE_LEVELS == 4
2126         pv_mmu_ops.alloc_pud = xen_alloc_pud;
2127         pv_mmu_ops.release_pud = xen_release_pud;
2128 #endif
2129
2130 #ifdef CONFIG_X86_64
2131         SetPagePinned(virt_to_page(level3_user_vsyscall));
2132 #endif
2133         xen_mark_init_mm_pinned();
2134 }
2135
2136 static void xen_leave_lazy_mmu(void)
2137 {
2138         preempt_disable();
2139         xen_mc_flush();
2140         paravirt_leave_lazy_mmu();
2141         preempt_enable();
2142 }
2143
2144 static const struct pv_mmu_ops xen_mmu_ops __initdata = {
2145         .read_cr2 = xen_read_cr2,
2146         .write_cr2 = xen_write_cr2,
2147
2148         .read_cr3 = xen_read_cr3,
2149         .write_cr3 = xen_write_cr3,
2150
2151         .flush_tlb_user = xen_flush_tlb,
2152         .flush_tlb_kernel = xen_flush_tlb,
2153         .flush_tlb_single = xen_flush_tlb_single,
2154         .flush_tlb_others = xen_flush_tlb_others,
2155
2156         .pte_update = paravirt_nop,
2157         .pte_update_defer = paravirt_nop,
2158
2159         .pgd_alloc = xen_pgd_alloc,
2160         .pgd_free = xen_pgd_free,
2161
2162         .alloc_pte = xen_alloc_pte_init,
2163         .release_pte = xen_release_pte_init,
2164         .alloc_pmd = xen_alloc_pmd_init,
2165         .alloc_pmd_clone = paravirt_nop,
2166         .release_pmd = xen_release_pmd_init,
2167
2168 #ifdef CONFIG_X86_64
2169         .set_pte = xen_set_pte,
2170 #else
2171         .set_pte = xen_set_pte_init,
2172 #endif
2173         .set_pte_at = xen_set_pte_at,
2174         .set_pmd = xen_set_pmd_hyper,
2175
2176         .ptep_modify_prot_start = __ptep_modify_prot_start,
2177         .ptep_modify_prot_commit = __ptep_modify_prot_commit,
2178
2179         .pte_val = PV_CALLEE_SAVE(xen_pte_val),
2180         .pgd_val = PV_CALLEE_SAVE(xen_pgd_val),
2181
2182         .make_pte = PV_CALLEE_SAVE(xen_make_pte),
2183         .make_pgd = PV_CALLEE_SAVE(xen_make_pgd),
2184
2185 #ifdef CONFIG_X86_PAE
2186         .set_pte_atomic = xen_set_pte_atomic,
2187         .pte_clear = xen_pte_clear,
2188         .pmd_clear = xen_pmd_clear,
2189 #endif  /* CONFIG_X86_PAE */
2190         .set_pud = xen_set_pud_hyper,
2191
2192         .make_pmd = PV_CALLEE_SAVE(xen_make_pmd),
2193         .pmd_val = PV_CALLEE_SAVE(xen_pmd_val),
2194
2195 #if PAGETABLE_LEVELS == 4
2196         .pud_val = PV_CALLEE_SAVE(xen_pud_val),
2197         .make_pud = PV_CALLEE_SAVE(xen_make_pud),
2198         .set_pgd = xen_set_pgd_hyper,
2199
2200         .alloc_pud = xen_alloc_pmd_init,
2201         .release_pud = xen_release_pmd_init,
2202 #endif  /* PAGETABLE_LEVELS == 4 */
2203
2204         .activate_mm = xen_activate_mm,
2205         .dup_mmap = xen_dup_mmap,
2206         .exit_mmap = xen_exit_mmap,
2207
2208         .lazy_mode = {
2209                 .enter = paravirt_enter_lazy_mmu,
2210                 .leave = xen_leave_lazy_mmu,
2211         },
2212
2213         .set_fixmap = xen_set_fixmap,
2214 };
2215
2216 void __init xen_init_mmu_ops(void)
2217 {
2218         x86_init.paging.pagetable_setup_start = xen_pagetable_setup_start;
2219         x86_init.paging.pagetable_setup_done = xen_pagetable_setup_done;
2220         pv_mmu_ops = xen_mmu_ops;
2221
2222         vmap_lazy_unmap = false;
2223 }
2224
2225 /* Protected by xen_reservation_lock. */
2226 #define MAX_CONTIG_ORDER 9 /* 2MB */
2227 static unsigned long discontig_frames[1<<MAX_CONTIG_ORDER];
2228
2229 #define VOID_PTE (mfn_pte(0, __pgprot(0)))
2230 static void xen_zap_pfn_range(unsigned long vaddr, unsigned int order,
2231                                 unsigned long *in_frames,
2232                                 unsigned long *out_frames)
2233 {
2234         int i;
2235         struct multicall_space mcs;
2236
2237         xen_mc_batch();
2238         for (i = 0; i < (1UL<<order); i++, vaddr += PAGE_SIZE) {
2239                 mcs = __xen_mc_entry(0);
2240
2241                 if (in_frames)
2242                         in_frames[i] = virt_to_mfn(vaddr);
2243
2244                 MULTI_update_va_mapping(mcs.mc, vaddr, VOID_PTE, 0);
2245                 set_phys_to_machine(virt_to_pfn(vaddr), INVALID_P2M_ENTRY);
2246
2247                 if (out_frames)
2248                         out_frames[i] = virt_to_pfn(vaddr);
2249         }
2250         xen_mc_issue(0);
2251 }
2252
2253 /*
2254  * Update the pfn-to-mfn mappings for a virtual address range, either to
2255  * point to an array of mfns, or contiguously from a single starting
2256  * mfn.
2257  */
2258 static void xen_remap_exchanged_ptes(unsigned long vaddr, int order,
2259                                      unsigned long *mfns,
2260                                      unsigned long first_mfn)
2261 {
2262         unsigned i, limit;
2263         unsigned long mfn;
2264
2265         xen_mc_batch();
2266
2267         limit = 1u << order;
2268         for (i = 0; i < limit; i++, vaddr += PAGE_SIZE) {
2269                 struct multicall_space mcs;
2270                 unsigned flags;
2271
2272                 mcs = __xen_mc_entry(0);
2273                 if (mfns)
2274                         mfn = mfns[i];
2275                 else
2276                         mfn = first_mfn + i;
2277
2278                 if (i < (limit - 1))
2279                         flags = 0;
2280                 else {
2281                         if (order == 0)
2282                                 flags = UVMF_INVLPG | UVMF_ALL;
2283                         else
2284                                 flags = UVMF_TLB_FLUSH | UVMF_ALL;
2285                 }
2286
2287                 MULTI_update_va_mapping(mcs.mc, vaddr,
2288                                 mfn_pte(mfn, PAGE_KERNEL), flags);
2289
2290                 set_phys_to_machine(virt_to_pfn(vaddr), mfn);
2291         }
2292
2293         xen_mc_issue(0);
2294 }
2295
2296 /*
2297  * Perform the hypercall to exchange a region of our pfns to point to
2298  * memory with the required contiguous alignment.  Takes the pfns as
2299  * input, and populates mfns as output.
2300  *
2301  * Returns a success code indicating whether the hypervisor was able to
2302  * satisfy the request or not.
2303  */
2304 static int xen_exchange_memory(unsigned long extents_in, unsigned int order_in,
2305                                unsigned long *pfns_in,
2306                                unsigned long extents_out,
2307                                unsigned int order_out,
2308                                unsigned long *mfns_out,
2309                                unsigned int address_bits)
2310 {
2311         long rc;
2312         int success;
2313
2314         struct xen_memory_exchange exchange = {
2315                 .in = {
2316                         .nr_extents   = extents_in,
2317                         .extent_order = order_in,
2318                         .extent_start = pfns_in,
2319                         .domid        = DOMID_SELF
2320                 },
2321                 .out = {
2322                         .nr_extents   = extents_out,
2323                         .extent_order = order_out,
2324                         .extent_start = mfns_out,
2325                         .address_bits = address_bits,
2326                         .domid        = DOMID_SELF
2327                 }
2328         };
2329
2330         BUG_ON(extents_in << order_in != extents_out << order_out);
2331
2332         rc = HYPERVISOR_memory_op(XENMEM_exchange, &exchange);
2333         success = (exchange.nr_exchanged == extents_in);
2334
2335         BUG_ON(!success && ((exchange.nr_exchanged != 0) || (rc == 0)));
2336         BUG_ON(success && (rc != 0));
2337
2338         return success;
2339 }
2340
2341 int xen_create_contiguous_region(unsigned long vstart, unsigned int order,
2342                                  unsigned int address_bits)
2343 {
2344         unsigned long *in_frames = discontig_frames, out_frame;
2345         unsigned long  flags;
2346         int            success;
2347
2348         /*
2349          * Currently an auto-translated guest will not perform I/O, nor will
2350          * it require PAE page directories below 4GB. Therefore any calls to
2351          * this function are redundant and can be ignored.
2352          */
2353
2354         if (xen_feature(XENFEAT_auto_translated_physmap))
2355                 return 0;
2356
2357         if (unlikely(order > MAX_CONTIG_ORDER))
2358                 return -ENOMEM;
2359
2360         memset((void *) vstart, 0, PAGE_SIZE << order);
2361
2362         spin_lock_irqsave(&xen_reservation_lock, flags);
2363
2364         /* 1. Zap current PTEs, remembering MFNs. */
2365         xen_zap_pfn_range(vstart, order, in_frames, NULL);
2366
2367         /* 2. Get a new contiguous memory extent. */
2368         out_frame = virt_to_pfn(vstart);
2369         success = xen_exchange_memory(1UL << order, 0, in_frames,
2370                                       1, order, &out_frame,
2371                                       address_bits);
2372
2373         /* 3. Map the new extent in place of old pages. */
2374         if (success)
2375                 xen_remap_exchanged_ptes(vstart, order, NULL, out_frame);
2376         else
2377                 xen_remap_exchanged_ptes(vstart, order, in_frames, 0);
2378
2379         spin_unlock_irqrestore(&xen_reservation_lock, flags);
2380
2381         return success ? 0 : -ENOMEM;
2382 }
2383 EXPORT_SYMBOL_GPL(xen_create_contiguous_region);
2384
2385 void xen_destroy_contiguous_region(unsigned long vstart, unsigned int order)
2386 {
2387         unsigned long *out_frames = discontig_frames, in_frame;
2388         unsigned long  flags;
2389         int success;
2390
2391         if (xen_feature(XENFEAT_auto_translated_physmap))
2392                 return;
2393
2394         if (unlikely(order > MAX_CONTIG_ORDER))
2395                 return;
2396
2397         memset((void *) vstart, 0, PAGE_SIZE << order);
2398
2399         spin_lock_irqsave(&xen_reservation_lock, flags);
2400
2401         /* 1. Find start MFN of contiguous extent. */
2402         in_frame = virt_to_mfn(vstart);
2403
2404         /* 2. Zap current PTEs. */
2405         xen_zap_pfn_range(vstart, order, NULL, out_frames);
2406
2407         /* 3. Do the exchange for non-contiguous MFNs. */
2408         success = xen_exchange_memory(1, order, &in_frame, 1UL << order,
2409                                         0, out_frames, 0);
2410
2411         /* 4. Map new pages in place of old pages. */
2412         if (success)
2413                 xen_remap_exchanged_ptes(vstart, order, out_frames, 0);
2414         else
2415                 xen_remap_exchanged_ptes(vstart, order, NULL, in_frame);
2416
2417         spin_unlock_irqrestore(&xen_reservation_lock, flags);
2418 }
2419 EXPORT_SYMBOL_GPL(xen_destroy_contiguous_region);
2420
2421 #ifdef CONFIG_XEN_PVHVM
2422 static void xen_hvm_exit_mmap(struct mm_struct *mm)
2423 {
2424         struct xen_hvm_pagetable_dying a;
2425         int rc;
2426
2427         a.domid = DOMID_SELF;
2428         a.gpa = __pa(mm->pgd);
2429         rc = HYPERVISOR_hvm_op(HVMOP_pagetable_dying, &a);
2430         WARN_ON_ONCE(rc < 0);
2431 }
2432
2433 static int is_pagetable_dying_supported(void)
2434 {
2435         struct xen_hvm_pagetable_dying a;
2436         int rc = 0;
2437
2438         a.domid = DOMID_SELF;
2439         a.gpa = 0x00;
2440         rc = HYPERVISOR_hvm_op(HVMOP_pagetable_dying, &a);
2441         if (rc < 0) {
2442                 printk(KERN_DEBUG "HVMOP_pagetable_dying not supported\n");
2443                 return 0;
2444         }
2445         return 1;
2446 }
2447
2448 void __init xen_hvm_init_mmu_ops(void)
2449 {
2450         if (is_pagetable_dying_supported())
2451                 pv_mmu_ops.exit_mmap = xen_hvm_exit_mmap;
2452 }
2453 #endif
2454
2455 #ifdef CONFIG_XEN_DEBUG_FS
2456
2457 static struct dentry *d_mmu_debug;
2458
2459 static int __init xen_mmu_debugfs(void)
2460 {
2461         struct dentry *d_xen = xen_init_debugfs();
2462
2463         if (d_xen == NULL)
2464                 return -ENOMEM;
2465
2466         d_mmu_debug = debugfs_create_dir("mmu", d_xen);
2467
2468         debugfs_create_u8("zero_stats", 0644, d_mmu_debug, &zero_stats);
2469
2470         debugfs_create_u32("pgd_update", 0444, d_mmu_debug, &mmu_stats.pgd_update);
2471         debugfs_create_u32("pgd_update_pinned", 0444, d_mmu_debug,
2472                            &mmu_stats.pgd_update_pinned);
2473         debugfs_create_u32("pgd_update_batched", 0444, d_mmu_debug,
2474                            &mmu_stats.pgd_update_pinned);
2475
2476         debugfs_create_u32("pud_update", 0444, d_mmu_debug, &mmu_stats.pud_update);
2477         debugfs_create_u32("pud_update_pinned", 0444, d_mmu_debug,
2478                            &mmu_stats.pud_update_pinned);
2479         debugfs_create_u32("pud_update_batched", 0444, d_mmu_debug,
2480                            &mmu_stats.pud_update_pinned);
2481
2482         debugfs_create_u32("pmd_update", 0444, d_mmu_debug, &mmu_stats.pmd_update);
2483         debugfs_create_u32("pmd_update_pinned", 0444, d_mmu_debug,
2484                            &mmu_stats.pmd_update_pinned);
2485         debugfs_create_u32("pmd_update_batched", 0444, d_mmu_debug,
2486                            &mmu_stats.pmd_update_pinned);
2487
2488         debugfs_create_u32("pte_update", 0444, d_mmu_debug, &mmu_stats.pte_update);
2489 //      debugfs_create_u32("pte_update_pinned", 0444, d_mmu_debug,
2490 //                         &mmu_stats.pte_update_pinned);
2491         debugfs_create_u32("pte_update_batched", 0444, d_mmu_debug,
2492                            &mmu_stats.pte_update_pinned);
2493
2494         debugfs_create_u32("mmu_update", 0444, d_mmu_debug, &mmu_stats.mmu_update);
2495         debugfs_create_u32("mmu_update_extended", 0444, d_mmu_debug,
2496                            &mmu_stats.mmu_update_extended);
2497         xen_debugfs_create_u32_array("mmu_update_histo", 0444, d_mmu_debug,
2498                                      mmu_stats.mmu_update_histo, 20);
2499
2500         debugfs_create_u32("set_pte_at", 0444, d_mmu_debug, &mmu_stats.set_pte_at);
2501         debugfs_create_u32("set_pte_at_batched", 0444, d_mmu_debug,
2502                            &mmu_stats.set_pte_at_batched);
2503         debugfs_create_u32("set_pte_at_current", 0444, d_mmu_debug,
2504                            &mmu_stats.set_pte_at_current);
2505         debugfs_create_u32("set_pte_at_kernel", 0444, d_mmu_debug,
2506                            &mmu_stats.set_pte_at_kernel);
2507
2508         debugfs_create_u32("prot_commit", 0444, d_mmu_debug, &mmu_stats.prot_commit);
2509         debugfs_create_u32("prot_commit_batched", 0444, d_mmu_debug,
2510                            &mmu_stats.prot_commit_batched);
2511
2512         return 0;
2513 }
2514 fs_initcall(xen_mmu_debugfs);
2515
2516 #endif  /* CONFIG_XEN_DEBUG_FS */