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