]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/pc/mmu.c
segdesc: add /dev/^(ldt gdt) support
[plan9front.git] / sys / src / 9 / pc / mmu.c
1 /*
2  * Memory mappings.  Life was easier when 2G of memory was enough.
3  *
4  * The kernel memory starts at KZERO, with the text loaded at KZERO+1M
5  * (9load sits under 1M during the load).  The memory from KZERO to the
6  * top of memory is mapped 1-1 with physical memory, starting at physical
7  * address 0.  All kernel memory and data structures (i.e., the entries stored
8  * into conf.mem) must sit in this physical range: if KZERO is at 0xF0000000,
9  * then the kernel can only have 256MB of memory for itself.
10  * 
11  * The 256M below KZERO comprises three parts.  The lowest 4M is the
12  * virtual page table, a virtual address representation of the current 
13  * page table tree.  The second 4M is used for temporary per-process
14  * mappings managed by kmap and kunmap.  The remaining 248M is used
15  * for global (shared by all procs and all processors) device memory
16  * mappings and managed by vmap and vunmap.  The total amount (256M)
17  * could probably be reduced somewhat if desired.  The largest device
18  * mapping is that of the video card, and even though modern video cards
19  * have embarrassing amounts of memory, the video drivers only use one
20  * frame buffer worth (at most 16M).  Each is described in more detail below.
21  *
22  * The VPT is a 4M frame constructed by inserting the pdb into itself.
23  * This short-circuits one level of the page tables, with the result that 
24  * the contents of second-level page tables can be accessed at VPT.  
25  * We use the VPT to edit the page tables (see mmu) after inserting them
26  * into the page directory.  It is a convenient mechanism for mapping what
27  * might be otherwise-inaccessible pages.  The idea was borrowed from
28  * the Exokernel.
29  *
30  * The VPT doesn't solve all our problems, because we still need to 
31  * prepare page directories before we can install them.  For that, we
32  * use tmpmap/tmpunmap, which map a single page at TMPADDR.
33  */
34
35 #include        "u.h"
36 #include        "../port/lib.h"
37 #include        "mem.h"
38 #include        "dat.h"
39 #include        "fns.h"
40 #include        "io.h"
41
42 /*
43  * Simple segment descriptors with no translation.
44  */
45 #define DATASEGM(p)     { 0xFFFF, SEGG|SEGB|(0xF<<16)|SEGP|SEGPL(p)|SEGDATA|SEGW }
46 #define EXECSEGM(p)     { 0xFFFF, SEGG|SEGD|(0xF<<16)|SEGP|SEGPL(p)|SEGEXEC|SEGR }
47 #define EXEC16SEGM(p)   { 0xFFFF, SEGG|(0xF<<16)|SEGP|SEGPL(p)|SEGEXEC|SEGR }
48 #define TSSSEGM(b,p)    { ((b)<<16)|sizeof(Tss),\
49                           ((b)&0xFF000000)|(((b)>>16)&0xFF)|SEGTSS|SEGPL(p)|SEGP }
50
51 Segdesc gdt[NGDT] =
52 {
53 [NULLSEG]       { 0, 0},                /* null descriptor */
54 [KDSEG]         DATASEGM(0),            /* kernel data/stack */
55 [KESEG]         EXECSEGM(0),            /* kernel code */
56 [UDSEG]         DATASEGM(3),            /* user data/stack */
57 [UESEG]         EXECSEGM(3),            /* user code */
58 [TSSSEG]        TSSSEGM(0,0),           /* tss segment */
59 [KESEG16]               EXEC16SEGM(0),  /* kernel code 16-bit */
60 };
61
62 static int didmmuinit;
63 static void taskswitch(ulong, ulong);
64 static void memglobal(void);
65
66 #define vpt ((ulong*)VPT)
67 #define VPTX(va)                (((ulong)(va))>>12)
68 #define vpd (vpt+VPTX(VPT))
69
70 void
71 mmuinit0(void)
72 {
73         memmove(m->gdt, gdt, sizeof gdt);
74 }
75
76 void
77 mmuinit(void)
78 {
79         ulong x, *p;
80         ushort ptr[3];
81
82         didmmuinit = 1;
83
84         if(0) print("vpt=%#.8ux vpd=%#p kmap=%#.8ux\n",
85                 VPT, vpd, KMAP);
86
87         memglobal();
88         m->pdb[PDX(VPT)] = PADDR(m->pdb)|PTEWRITE|PTEVALID;
89         
90         m->tss = malloc(sizeof(Tss));
91         memset(m->tss, 0, sizeof(Tss));
92         m->tss->iomap = 0xDFFF<<16;
93
94         /*
95          * We used to keep the GDT in the Mach structure, but it
96          * turns out that that slows down access to the rest of the
97          * page.  Since the Mach structure is accessed quite often,
98          * it pays off anywhere from a factor of 1.25 to 2 on real
99          * hardware to separate them (the AMDs are more sensitive
100          * than Intels in this regard).  Under VMware it pays off
101          * a factor of about 10 to 100.
102          */
103         memmove(m->gdt, gdt, sizeof gdt);
104         x = (ulong)m->tss;
105         m->gdt[TSSSEG].d0 = (x<<16)|sizeof(Tss);
106         m->gdt[TSSSEG].d1 = (x&0xFF000000)|((x>>16)&0xFF)|SEGTSS|SEGPL(0)|SEGP;
107
108         ptr[0] = sizeof(gdt)-1;
109         x = (ulong)m->gdt;
110         ptr[1] = x & 0xFFFF;
111         ptr[2] = (x>>16) & 0xFFFF;
112         lgdt(ptr);
113
114         ptr[0] = sizeof(Segdesc)*256-1;
115         x = IDTADDR;
116         ptr[1] = x & 0xFFFF;
117         ptr[2] = (x>>16) & 0xFFFF;
118         lidt(ptr);
119
120         /* make kernel text unwritable */
121         for(x = KTZERO; x < (ulong)etext; x += BY2PG){
122                 p = mmuwalk(m->pdb, x, 2, 0);
123                 if(p == nil)
124                         panic("mmuinit");
125                 *p &= ~PTEWRITE;
126         }
127
128         taskswitch(PADDR(m->pdb),  (ulong)m + BY2PG);
129         ltr(TSSSEL);
130 }
131
132 /* 
133  * On processors that support it, we set the PTEGLOBAL bit in
134  * page table and page directory entries that map kernel memory.
135  * Doing this tells the processor not to bother flushing them
136  * from the TLB when doing the TLB flush associated with a 
137  * context switch (write to CR3).  Since kernel memory mappings
138  * are never removed, this is safe.  (If we ever remove kernel memory
139  * mappings, we can do a full flush by turning off the PGE bit in CR4,
140  * writing to CR3, and then turning the PGE bit back on.) 
141  *
142  * See also mmukmap below.
143  * 
144  * Processor support for the PTEGLOBAL bit is enabled in devarch.c.
145  */
146 static void
147 memglobal(void)
148 {
149         int i, j;
150         ulong *pde, *pte;
151
152         /* only need to do this once, on bootstrap processor */
153         if(m->machno != 0)
154                 return;
155
156         if(!m->havepge)
157                 return;
158
159         pde = m->pdb;
160         for(i=PDX(KZERO); i<1024; i++){
161                 if(pde[i] & PTEVALID){
162                         pde[i] |= PTEGLOBAL;
163                         if(!(pde[i] & PTESIZE)){
164                                 pte = KADDR(pde[i]&~(BY2PG-1));
165                                 for(j=0; j<1024; j++)
166                                         if(pte[j] & PTEVALID)
167                                                 pte[j] |= PTEGLOBAL;
168                         }
169                 }
170         }                       
171 }
172
173 /*
174  * Flush all the user-space and device-mapping mmu info
175  * for this process, because something has been deleted.
176  * It will be paged back in on demand.
177  */
178 void
179 flushmmu(void)
180 {
181         int s;
182
183         s = splhi();
184         up->newtlb = 1;
185         mmuswitch(up);
186         splx(s);
187 }
188
189 /*
190  * Flush a single page mapping from the tlb.
191  */
192 void
193 flushpg(ulong va)
194 {
195         if(X86FAMILY(m->cpuidax) >= 4)
196                 invlpg(va);
197         else
198                 putcr3(getcr3());
199 }
200         
201 /*
202  * Allocate a new page for a page directory. 
203  * We keep a small cache of pre-initialized
204  * page directories in each mach.
205  */
206 static Page*
207 mmupdballoc(void)
208 {
209         int s;
210         Page *page;
211         ulong *pdb;
212
213         s = splhi();
214         m->pdballoc++;
215         if(m->pdbpool == 0){
216                 spllo();
217                 page = newpage(0, 0, 0);
218                 page->va = (ulong)vpd;
219                 splhi();
220                 pdb = tmpmap(page);
221                 memmove(pdb, m->pdb, BY2PG);
222                 pdb[PDX(VPT)] = page->pa|PTEWRITE|PTEVALID;     /* set up VPT */
223                 tmpunmap(pdb);
224         }else{
225                 page = m->pdbpool;
226                 m->pdbpool = page->next;
227                 m->pdbcnt--;
228         }
229         splx(s);
230         return page;
231 }
232
233 static void
234 mmupdbfree(Proc *proc, Page *p)
235 {
236         if(islo())
237                 panic("mmupdbfree: islo");
238         m->pdbfree++;
239         if(m->pdbcnt >= 10){
240                 p->next = proc->mmufree;
241                 proc->mmufree = p;
242         }else{
243                 p->next = m->pdbpool;
244                 m->pdbpool = p;
245                 m->pdbcnt++;
246         }
247 }
248
249 /*
250  * A user-space memory segment has been deleted, or the
251  * process is exiting.  Clear all the pde entries for user-space
252  * memory mappings and device mappings.  Any entries that
253  * are needed will be paged back in as necessary.
254  */
255 static void
256 mmuptefree(Proc* proc)
257 {
258         int s;
259         ulong *pdb;
260         Page **last, *page;
261
262         if(proc->mmupdb == nil || proc->mmuused == nil)
263                 return;
264         s = splhi();
265         pdb = tmpmap(proc->mmupdb);
266         last = &proc->mmuused;
267         for(page = *last; page; page = page->next){
268                 pdb[page->daddr] = 0;
269                 last = &page->next;
270         }
271         tmpunmap(pdb);
272         splx(s);
273         *last = proc->mmufree;
274         proc->mmufree = proc->mmuused;
275         proc->mmuused = 0;
276 }
277
278 static void
279 taskswitch(ulong pdb, ulong stack)
280 {
281         Tss *tss;
282
283         tss = m->tss;
284         tss->ss0 = KDSEL;
285         tss->esp0 = stack;
286         tss->ss1 = KDSEL;
287         tss->esp1 = stack;
288         tss->ss2 = KDSEL;
289         tss->esp2 = stack;
290         putcr3(pdb);
291 }
292
293 void
294 mmuswitch(Proc* proc)
295 {
296         ulong *pdb;
297         ulong x;
298         int n;
299
300         if(proc->newtlb){
301                 mmuptefree(proc);
302                 proc->newtlb = 0;
303         }
304
305         if(proc->mmupdb){
306                 pdb = tmpmap(proc->mmupdb);
307                 pdb[PDX(MACHADDR)] = m->pdb[PDX(MACHADDR)];
308                 tmpunmap(pdb);
309                 taskswitch(proc->mmupdb->pa, (ulong)(proc->kstack+KSTACK));
310         }else
311                 taskswitch(PADDR(m->pdb), (ulong)(proc->kstack+KSTACK));
312
313         memmove(&m->gdt[PROCSEG0], proc->gdt, sizeof(proc->gdt));
314         if((x = (ulong)proc->ldt) && (n = proc->nldt) > 0){
315                 m->gdt[LDTSEG].d0 = (x<<16)|((n * sizeof(Segdesc)) - 1);
316                 m->gdt[LDTSEG].d1 = (x&0xFF000000)|((x>>16)&0xFF)|SEGLDT|SEGPL(0)|SEGP;
317                 lldt(LDTSEL);
318         } else
319                 lldt(NULLSEL);
320 }
321
322 /*
323  * Release any pages allocated for a page directory base or page-tables
324  * for this process:
325  *   switch to the prototype pdb for this processor (m->pdb);
326  *   call mmuptefree() to place all pages used for page-tables (proc->mmuused)
327  *   onto the process' free list (proc->mmufree). This has the side-effect of
328  *   cleaning any user entries in the pdb (proc->mmupdb);
329  *   if there's a pdb put it in the cache of pre-initialised pdb's
330  *   for this processor (m->pdbpool) or on the process' free list;
331  *   finally, place any pages freed back into the free pool (palloc).
332  * This routine is only called from schedinit() with palloc locked.
333  */
334 void
335 mmurelease(Proc* proc)
336 {
337         Page *page, *next;
338         ulong *pdb;
339
340         if(islo())
341                 panic("mmurelease: islo");
342         taskswitch(PADDR(m->pdb), (ulong)m + BY2PG);
343         if(proc->kmaptable){
344                 if(proc->mmupdb == nil)
345                         panic("mmurelease: no mmupdb");
346                 if(--proc->kmaptable->ref)
347                         panic("mmurelease: kmap ref %d", proc->kmaptable->ref);
348                 if(proc->nkmap)
349                         panic("mmurelease: nkmap %d", proc->nkmap);
350                 /*
351                  * remove kmaptable from pdb before putting pdb up for reuse.
352                  */
353                 pdb = tmpmap(proc->mmupdb);
354                 if(PPN(pdb[PDX(KMAP)]) != proc->kmaptable->pa)
355                         panic("mmurelease: bad kmap pde %#.8lux kmap %#.8lux",
356                                 pdb[PDX(KMAP)], proc->kmaptable->pa);
357                 pdb[PDX(KMAP)] = 0;
358                 tmpunmap(pdb);
359                 /*
360                  * move kmaptable to free list.
361                  */
362                 pagechainhead(proc->kmaptable);
363                 proc->kmaptable = 0;
364         }
365         if(proc->mmupdb){
366                 mmuptefree(proc);
367                 mmupdbfree(proc, proc->mmupdb);
368                 proc->mmupdb = 0;
369         }
370         for(page = proc->mmufree; page; page = next){
371                 next = page->next;
372                 if(--page->ref)
373                         panic("mmurelease: page->ref %d", page->ref);
374                 pagechainhead(page);
375         }
376         if(proc->mmufree && palloc.r.p)
377                 wakeup(&palloc.r);
378         proc->mmufree = 0;
379         if(proc->ldt){
380                 free(proc->ldt);
381                 proc->ldt = nil;
382                 proc->nldt = 0;
383         }
384 }
385
386 /*
387  * Allocate and install pdb for the current process.
388  */
389 static void
390 upallocpdb(void)
391 {
392         int s;
393         ulong *pdb;
394         Page *page;
395         
396         if(up->mmupdb != nil)
397                 return;
398         page = mmupdballoc();
399         s = splhi();
400         if(up->mmupdb != nil){
401                 /*
402                  * Perhaps we got an interrupt while
403                  * mmupdballoc was sleeping and that
404                  * interrupt allocated an mmupdb?
405                  * Seems unlikely.
406                  */
407                 mmupdbfree(up, page);
408                 splx(s);
409                 return;
410         }
411         pdb = tmpmap(page);
412         pdb[PDX(MACHADDR)] = m->pdb[PDX(MACHADDR)];
413         tmpunmap(pdb);
414         up->mmupdb = page;
415         putcr3(up->mmupdb->pa);
416         splx(s);
417 }
418
419 /*
420  * Update the mmu in response to a user fault.  pa may have PTEWRITE set.
421  */
422 void
423 putmmu(ulong va, ulong pa, Page*)
424 {
425         int old, s;
426         Page *page;
427
428         if(up->mmupdb == nil)
429                 upallocpdb();
430
431         /*
432          * We should be able to get through this with interrupts
433          * turned on (if we get interrupted we'll just pick up 
434          * where we left off) but we get many faults accessing
435          * vpt[] near the end of this function, and they always happen
436          * after the process has been switched out and then 
437          * switched back, usually many times in a row (perhaps
438          * it cannot switch back successfully for some reason).
439          * 
440          * In any event, I'm tired of searching for this bug.  
441          * Turn off interrupts during putmmu even though
442          * we shouldn't need to.                - rsc
443          */
444         
445         s = splhi();
446         if(!(vpd[PDX(va)]&PTEVALID)){
447                 if(up->mmufree == 0){
448                         spllo();
449                         page = newpage(0, 0, 0);
450                         splhi();
451                 }
452                 else{
453                         page = up->mmufree;
454                         up->mmufree = page->next;
455                 }
456                 vpd[PDX(va)] = PPN(page->pa)|PTEUSER|PTEWRITE|PTEVALID;
457                 /* page is now mapped into the VPT - clear it */
458                 memset((void*)(VPT+PDX(va)*BY2PG), 0, BY2PG);
459                 page->daddr = PDX(va);
460                 page->next = up->mmuused;
461                 up->mmuused = page;
462         }
463         old = vpt[VPTX(va)];
464         vpt[VPTX(va)] = pa|PTEUSER|PTEVALID;
465         if(old&PTEVALID)
466                 flushpg(va);
467         if(getcr3() != up->mmupdb->pa)
468                 print("bad cr3 %#.8lux %#.8lux\n", getcr3(), up->mmupdb->pa);
469         splx(s);
470 }
471
472 /*
473  * Double-check the user MMU.
474  * Error checking only.
475  */
476 void
477 checkmmu(ulong va, ulong pa)
478 {
479         if(up->mmupdb == 0)
480                 return;
481         if(!(vpd[PDX(va)]&PTEVALID) || !(vpt[VPTX(va)]&PTEVALID))
482                 return;
483         if(PPN(vpt[VPTX(va)]) != pa)
484                 print("%ld %s: va=%#08lux pa=%#08lux pte=%#08lux\n",
485                         up->pid, up->text,
486                         va, pa, vpt[VPTX(va)]);
487 }
488
489 /*
490  * Walk the page-table pointed to by pdb and return a pointer
491  * to the entry for virtual address va at the requested level.
492  * If the entry is invalid and create isn't requested then bail
493  * out early. Otherwise, for the 2nd level walk, allocate a new
494  * page-table page and register it in the 1st level.  This is used
495  * only to edit kernel mappings, which use pages from kernel memory,
496  * so it's okay to use KADDR to look at the tables.
497  */
498 ulong*
499 mmuwalk(ulong* pdb, ulong va, int level, int create)
500 {
501         ulong *table;
502         void *map;
503
504         table = &pdb[PDX(va)];
505         if(!(*table & PTEVALID) && create == 0)
506                 return 0;
507
508         switch(level){
509
510         default:
511                 return 0;
512
513         case 1:
514                 return table;
515
516         case 2:
517                 if(*table & PTESIZE)
518                         panic("mmuwalk2: va %luX entry %luX", va, *table);
519                 if(!(*table & PTEVALID)){
520                         /*
521                          * Have to call low-level allocator from
522                          * memory.c if we haven't set up the xalloc
523                          * tables yet.
524                          */
525                         if(didmmuinit)
526                                 map = xspanalloc(BY2PG, BY2PG, 0);
527                         else
528                                 map = rampage();
529                         if(map == nil)
530                                 panic("mmuwalk xspanalloc failed");
531                         *table = PADDR(map)|PTEWRITE|PTEVALID;
532                 }
533                 table = KADDR(PPN(*table));
534                 return &table[PTX(va)];
535         }
536 }
537
538 /*
539  * Device mappings are shared by all procs and processors and
540  * live in the virtual range VMAP to VMAP+VMAPSIZE.  The master
541  * copy of the mappings is stored in mach0->pdb, and they are
542  * paged in from there as necessary by vmapsync during faults.
543  */
544
545 static Lock vmaplock;
546
547 static int findhole(ulong *a, int n, int count);
548 static ulong vmapalloc(ulong size);
549 static void pdbunmap(ulong*, ulong, int);
550
551 /*
552  * Add a device mapping to the vmap range.
553  */
554 void*
555 vmap(ulong pa, int size)
556 {
557         int osize;
558         ulong o, va;
559         
560         /*
561          * might be asking for less than a page.
562          */
563         osize = size;
564         o = pa & (BY2PG-1);
565         pa -= o;
566         size += o;
567
568         size = ROUND(size, BY2PG);
569         if(pa == 0){
570                 print("vmap pa=0 pc=%#p\n", getcallerpc(&pa));
571                 return nil;
572         }
573         ilock(&vmaplock);
574         if((va = vmapalloc(size)) == 0 
575         || pdbmap(MACHP(0)->pdb, pa|PTEUNCACHED|PTEWRITE, va, size) < 0){
576                 iunlock(&vmaplock);
577                 return 0;
578         }
579         iunlock(&vmaplock);
580         /* avoid trap on local processor
581         for(i=0; i<size; i+=4*MB)
582                 vmapsync(va+i);
583         */
584         USED(osize);
585 //      print("  vmap %#.8lux %d => %#.8lux\n", pa+o, osize, va+o);
586         return (void*)(va + o);
587 }
588
589 static int
590 findhole(ulong *a, int n, int count)
591 {
592         int have, i;
593         
594         have = 0;
595         for(i=0; i<n; i++){
596                 if(a[i] == 0)
597                         have++;
598                 else
599                         have = 0;
600                 if(have >= count)
601                         return i+1 - have;
602         }
603         return -1;
604 }
605
606 /*
607  * Look for free space in the vmap.
608  */
609 static ulong
610 vmapalloc(ulong size)
611 {
612         int i, n, o;
613         ulong *vpdb;
614         int vpdbsize;
615         
616         vpdb = &MACHP(0)->pdb[PDX(VMAP)];
617         vpdbsize = VMAPSIZE/(4*MB);
618
619         if(size >= 4*MB){
620                 n = (size+4*MB-1) / (4*MB);
621                 if((o = findhole(vpdb, vpdbsize, n)) != -1)
622                         return VMAP + o*4*MB;
623                 return 0;
624         }
625         n = (size+BY2PG-1) / BY2PG;
626         for(i=0; i<vpdbsize; i++)
627                 if((vpdb[i]&PTEVALID) && !(vpdb[i]&PTESIZE))
628                         if((o = findhole(KADDR(PPN(vpdb[i])), WD2PG, n)) != -1)
629                                 return VMAP + i*4*MB + o*BY2PG;
630         if((o = findhole(vpdb, vpdbsize, 1)) != -1)
631                 return VMAP + o*4*MB;
632                 
633         /*
634          * could span page directory entries, but not worth the trouble.
635          * not going to be very much contention.
636          */
637         return 0;
638 }
639
640 /*
641  * Remove a device mapping from the vmap range.
642  * Since pdbunmap does not remove page tables, just entries,
643  * the call need not be interlocked with vmap.
644  */
645 void
646 vunmap(void *v, int size)
647 {
648         int i;
649         ulong va, o;
650         Mach *nm;
651         Proc *p;
652         
653         /*
654          * might not be aligned
655          */
656         va = (ulong)v;
657         o = va&(BY2PG-1);
658         va -= o;
659         size += o;
660         size = ROUND(size, BY2PG);
661         
662         if(size < 0 || va < VMAP || va+size > VMAP+VMAPSIZE)
663                 panic("vunmap va=%#.8lux size=%#x pc=%#.8lux",
664                         va, size, getcallerpc(&v));
665
666         pdbunmap(MACHP(0)->pdb, va, size);
667         
668         /*
669          * Flush mapping from all the tlbs and copied pdbs.
670          * This can be (and is) slow, since it is called only rarely.
671          * It is possible for vunmap to be called with up == nil,
672          * e.g. from the reset/init driver routines during system
673          * boot. In that case it suffices to flush the MACH(0) TLB
674          * and return.
675          */
676         if(!active.thunderbirdsarego){
677                 putcr3(PADDR(MACHP(0)->pdb));
678                 return;
679         }
680         for(i=0; i<conf.nproc; i++){
681                 p = proctab(i);
682                 if(p->state == Dead)
683                         continue;
684                 if(p != up)
685                         p->newtlb = 1;
686         }
687         for(i=0; i<conf.nmach; i++){
688                 nm = MACHP(i);
689                 if(nm != m)
690                         nm->flushmmu = 1;
691         }
692         flushmmu();
693         for(i=0; i<conf.nmach; i++){
694                 nm = MACHP(i);
695                 if(nm != m)
696                         while((active.machs&(1<<nm->machno)) && nm->flushmmu)
697                                 ;
698         }
699 }
700
701 /*
702  * Add kernel mappings for pa -> va for a section of size bytes.
703  */
704 int
705 pdbmap(ulong *pdb, ulong pa, ulong va, int size)
706 {
707         int pse;
708         ulong pgsz, *pte, *table;
709         ulong flag, off;
710         
711         flag = pa&0xFFF;
712         pa &= ~0xFFF;
713
714         if((MACHP(0)->cpuiddx & 0x08) && (getcr4() & 0x10))
715                 pse = 1;
716         else
717                 pse = 0;
718
719         for(off=0; off<size; off+=pgsz){
720                 table = &pdb[PDX(va+off)];
721                 if((*table&PTEVALID) && (*table&PTESIZE))
722                         panic("vmap: va=%#.8lux pa=%#.8lux pde=%#.8lux",
723                                 va+off, pa+off, *table);
724
725                 /*
726                  * Check if it can be mapped using a 4MB page:
727                  * va, pa aligned and size >= 4MB and processor can do it.
728                  */
729                 if(pse && (pa+off)%(4*MB) == 0 && (va+off)%(4*MB) == 0 && (size-off) >= 4*MB){
730                         *table = (pa+off)|flag|PTESIZE|PTEVALID;
731                         pgsz = 4*MB;
732                 }else{
733                         pte = mmuwalk(pdb, va+off, 2, 1);
734                         if(*pte&PTEVALID)
735                                 panic("vmap: va=%#.8lux pa=%#.8lux pte=%#.8lux",
736                                         va+off, pa+off, *pte);
737                         *pte = (pa+off)|flag|PTEVALID;
738                         pgsz = BY2PG;
739                 }
740         }
741         return 0;
742 }
743
744 /*
745  * Remove mappings.  Must already exist, for sanity.
746  * Only used for kernel mappings, so okay to use KADDR.
747  */
748 static void
749 pdbunmap(ulong *pdb, ulong va, int size)
750 {
751         ulong vae;
752         ulong *table;
753         
754         vae = va+size;
755         while(va < vae){
756                 table = &pdb[PDX(va)];
757                 if(!(*table & PTEVALID))
758                         panic("vunmap: not mapped");
759                 if(*table & PTESIZE){
760                         if(va & 4*MB-1)
761                                 panic("vunmap: misaligned: %#p\n", va);
762                         *table = 0;
763                         va += 4*MB;
764                         continue;
765                 }
766                 table = KADDR(PPN(*table));
767                 if(!(table[PTX(va)] & PTEVALID))
768                         panic("vunmap: not mapped");
769                 table[PTX(va)] = 0;
770                 va += BY2PG;
771         }
772 }
773
774 /*
775  * Handle a fault by bringing vmap up to date.
776  * Only copy pdb entries and they never go away,
777  * so no locking needed.
778  */
779 int
780 vmapsync(ulong va)
781 {
782         ulong entry, *table;
783
784         if(va < VMAP || va >= VMAP+VMAPSIZE)
785                 return 0;
786
787         entry = MACHP(0)->pdb[PDX(va)];
788         if(!(entry&PTEVALID))
789                 return 0;
790         if(!(entry&PTESIZE)){
791                 /* make sure entry will help the fault */
792                 table = KADDR(PPN(entry));
793                 if(!(table[PTX(va)]&PTEVALID))
794                         return 0;
795         }
796         vpd[PDX(va)] = entry;
797         /*
798          * TLB doesn't cache negative results, so no flush needed.
799          */
800         return 1;
801 }
802
803
804 /*
805  * KMap is used to map individual pages into virtual memory.
806  * It is rare to have more than a few KMaps at a time (in the 
807  * absence of interrupts, only two at a time are ever used,
808  * but interrupts can stack).  The mappings are local to a process,
809  * so we can use the same range of virtual address space for
810  * all processes without any coordination.
811  */
812 #define kpt (vpt+VPTX(KMAP))
813 #define NKPT (KMAPSIZE/BY2PG)
814
815 KMap*
816 kmap(Page *page)
817 {
818         int i, o, s;
819
820         if(up == nil)
821                 panic("kmap: up=0 pc=%#.8lux", getcallerpc(&page));
822         if(up->mmupdb == nil)
823                 upallocpdb();
824         if(up->nkmap < 0)
825                 panic("kmap %lud %s: nkmap=%d", up->pid, up->text, up->nkmap);
826         
827         /*
828          * Splhi shouldn't be necessary here, but paranoia reigns.
829          * See comment in putmmu above.
830          */
831         s = splhi();
832         up->nkmap++;
833         if(!(vpd[PDX(KMAP)]&PTEVALID)){
834                 /* allocate page directory */
835                 if(KMAPSIZE > BY2XPG)
836                         panic("bad kmapsize");
837                 if(up->kmaptable != nil)
838                         panic("kmaptable");
839                 spllo();
840                 up->kmaptable = newpage(0, 0, 0);
841                 splhi();
842                 vpd[PDX(KMAP)] = up->kmaptable->pa|PTEWRITE|PTEVALID;
843                 flushpg((ulong)kpt);
844                 memset(kpt, 0, BY2PG);
845                 kpt[0] = page->pa|PTEWRITE|PTEVALID;
846                 up->lastkmap = 0;
847                 splx(s);
848                 return (KMap*)KMAP;
849         }
850         if(up->kmaptable == nil)
851                 panic("no kmaptable");
852         o = up->lastkmap+1;
853         for(i=0; i<NKPT; i++){
854                 if(kpt[(i+o)%NKPT] == 0){
855                         o = (i+o)%NKPT;
856                         kpt[o] = page->pa|PTEWRITE|PTEVALID;
857                         up->lastkmap = o;
858                         splx(s);
859                         return (KMap*)(KMAP+o*BY2PG);
860                 }
861         }
862         panic("out of kmap");
863         return nil;
864 }
865
866 void
867 kunmap(KMap *k)
868 {
869         ulong va;
870
871         va = (ulong)k;
872         if(up->mmupdb == nil || !(vpd[PDX(KMAP)]&PTEVALID))
873                 panic("kunmap: no kmaps");
874         if(va < KMAP || va >= KMAP+KMAPSIZE)
875                 panic("kunmap: bad address %#.8lux pc=%#p", va, getcallerpc(&k));
876         if(!(vpt[VPTX(va)]&PTEVALID))
877                 panic("kunmap: not mapped %#.8lux pc=%#p", va, getcallerpc(&k));
878         up->nkmap--;
879         if(up->nkmap < 0)
880                 panic("kunmap %lud %s: nkmap=%d", up->pid, up->text, up->nkmap);
881         vpt[VPTX(va)] = 0;
882         flushpg(va);
883 }
884
885 /*
886  * Temporary one-page mapping used to edit page directories.
887  *
888  * The fasttmp #define controls whether the code optimizes
889  * the case where the page is already mapped in the physical
890  * memory window.  
891  */
892 #define fasttmp 1
893
894 void*
895 tmpmap(Page *p)
896 {
897         ulong i;
898         ulong *entry;
899         
900         if(islo())
901                 panic("tmpaddr: islo");
902
903         if(fasttmp && p->pa < -KZERO)
904                 return KADDR(p->pa);
905
906         /*
907          * PDX(TMPADDR) == PDX(MACHADDR), so this
908          * entry is private to the processor and shared 
909          * between up->mmupdb (if any) and m->pdb.
910          */
911         entry = &vpt[VPTX(TMPADDR)];
912         if(!(*entry&PTEVALID)){
913                 for(i=KZERO; i<=CPU0MACH; i+=BY2PG)
914                         print("%#p: *%#p=%#p (vpt=%#p index=%#p)\n", i, &vpt[VPTX(i)], vpt[VPTX(i)], vpt, VPTX(i));
915                 panic("tmpmap: no entry");
916         }
917         if(PPN(*entry) != PPN(TMPADDR-KZERO))
918                 panic("tmpmap: already mapped entry=%#.8lux", *entry);
919         *entry = p->pa|PTEWRITE|PTEVALID;
920         flushpg(TMPADDR);
921         return (void*)TMPADDR;
922 }
923
924 void
925 tmpunmap(void *v)
926 {
927         ulong *entry;
928         
929         if(islo())
930                 panic("tmpaddr: islo");
931         if(fasttmp && (ulong)v >= KZERO && v != (void*)TMPADDR)
932                 return;
933         if(v != (void*)TMPADDR)
934                 panic("tmpunmap: bad address");
935         entry = &vpt[VPTX(TMPADDR)];
936         if(!(*entry&PTEVALID) || PPN(*entry) == PPN(PADDR(TMPADDR)))
937                 panic("tmpmap: not mapped entry=%#.8lux", *entry);
938         *entry = PPN(TMPADDR-KZERO)|PTEWRITE|PTEVALID;
939         flushpg(TMPADDR);
940 }
941
942 /*
943  * These could go back to being macros once the kernel is debugged,
944  * but the extra checking is nice to have.
945  */
946 void*
947 kaddr(ulong pa)
948 {
949         if(pa > (ulong)-KZERO)
950                 panic("kaddr: pa=%#.8lux", pa);
951         return (void*)(pa+KZERO);
952 }
953
954 ulong
955 paddr(void *v)
956 {
957         ulong va;
958         
959         va = (ulong)v;
960         if(va < KZERO)
961                 panic("paddr: va=%#.8lux pc=%#p", va, getcallerpc(&v));
962         return va-KZERO;
963 }
964
965 /*
966  * More debugging.
967  */
968 void
969 countpagerefs(ulong *ref, int print)
970 {
971         int i, n;
972         Mach *mm;
973         Page *pg;
974         Proc *p;
975         
976         n = 0;
977         for(i=0; i<conf.nproc; i++){
978                 p = proctab(i);
979                 if(p->mmupdb){
980                         if(print){
981                                 if(ref[pagenumber(p->mmupdb)])
982                                         iprint("page %#.8lux is proc %d (pid %lud) pdb\n",
983                                                 p->mmupdb->pa, i, p->pid);
984                                 continue;
985                         }
986                         if(ref[pagenumber(p->mmupdb)]++ == 0)
987                                 n++;
988                         else
989                                 iprint("page %#.8lux is proc %d (pid %lud) pdb but has other refs!\n",
990                                         p->mmupdb->pa, i, p->pid);
991                 }
992                 if(p->kmaptable){
993                         if(print){
994                                 if(ref[pagenumber(p->kmaptable)])
995                                         iprint("page %#.8lux is proc %d (pid %lud) kmaptable\n",
996                                                 p->kmaptable->pa, i, p->pid);
997                                 continue;
998                         }
999                         if(ref[pagenumber(p->kmaptable)]++ == 0)
1000                                 n++;
1001                         else
1002                                 iprint("page %#.8lux is proc %d (pid %lud) kmaptable but has other refs!\n",
1003                                         p->kmaptable->pa, i, p->pid);
1004                 }
1005                 for(pg=p->mmuused; pg; pg=pg->next){
1006                         if(print){
1007                                 if(ref[pagenumber(pg)])
1008                                         iprint("page %#.8lux is on proc %d (pid %lud) mmuused\n",
1009                                                 pg->pa, i, p->pid);
1010                                 continue;
1011                         }
1012                         if(ref[pagenumber(pg)]++ == 0)
1013                                 n++;
1014                         else
1015                                 iprint("page %#.8lux is on proc %d (pid %lud) mmuused but has other refs!\n",
1016                                         pg->pa, i, p->pid);
1017                 }
1018                 for(pg=p->mmufree; pg; pg=pg->next){
1019                         if(print){
1020                                 if(ref[pagenumber(pg)])
1021                                         iprint("page %#.8lux is on proc %d (pid %lud) mmufree\n",
1022                                                 pg->pa, i, p->pid);
1023                                 continue;
1024                         }
1025                         if(ref[pagenumber(pg)]++ == 0)
1026                                 n++;
1027                         else
1028                                 iprint("page %#.8lux is on proc %d (pid %lud) mmufree but has other refs!\n",
1029                                         pg->pa, i, p->pid);
1030                 }
1031         }
1032         if(!print)
1033                 iprint("%d pages in proc mmu\n", n);
1034         n = 0;
1035         for(i=0; i<conf.nmach; i++){
1036                 mm = MACHP(i);
1037                 for(pg=mm->pdbpool; pg; pg=pg->next){
1038                         if(print){
1039                                 if(ref[pagenumber(pg)])
1040                                         iprint("page %#.8lux is in cpu%d pdbpool\n",
1041                                                 pg->pa, i);
1042                                 continue;
1043                         }
1044                         if(ref[pagenumber(pg)]++ == 0)
1045                                 n++;
1046                         else
1047                                 iprint("page %#.8lux is in cpu%d pdbpool but has other refs!\n",
1048                                         pg->pa, i);
1049                 }
1050         }
1051         if(!print){
1052                 iprint("%d pages in mach pdbpools\n", n);
1053                 for(i=0; i<conf.nmach; i++)
1054                         iprint("cpu%d: %d pdballoc, %d pdbfree\n",
1055                                 i, MACHP(i)->pdballoc, MACHP(i)->pdbfree);
1056         }
1057 }
1058
1059 void
1060 checkfault(ulong, ulong)
1061 {
1062 }
1063
1064 /*
1065  * Return the number of bytes that can be accessed via KADDR(pa).
1066  * If pa is not a valid argument to KADDR, return 0.
1067  */
1068 ulong
1069 cankaddr(ulong pa)
1070 {
1071         if(pa >= -KZERO)
1072                 return 0;
1073         return -KZERO - pa;
1074 }
1075