1 /* Copyright (c) 2009, 2010 The Regents of the University of California
2 * Barret Rhoden <brho@cs.berkeley.edu>
3 * See LICENSE for details.
5 * Virtual memory management functions. Creation, modification, etc, of virtual
6 * memory regions (VMRs) as well as mmap(), mprotect(), and munmap().
8 * In general, error checking / bounds checks are done in the main function
9 * (e.g. mmap()), and the work is done in a do_ function (e.g. do_mmap()).
10 * Versions of those functions that are called when the vmr lock is already held
11 * begin with __ (e.g. __do_munmap()).
13 * Note that if we were called from kern/src/syscall.c, we probably don't have
14 * an edible reference to p. */
17 #include <ros/common.h>
28 struct kmem_cache *vmr_kcache;
30 static int __vmr_free_pgs(struct proc *p, pte_t *pte, void *va, void *arg);
31 /* minor helper, will ease the file->chan transition */
32 static struct page_map *file2pm(struct file *file)
34 return file->f_mapping;
39 vmr_kcache = kmem_cache_create("vm_regions", sizeof(struct vm_region),
40 __alignof__(struct dentry), 0, 0, 0);
43 /* For now, the caller will set the prot, flags, file, and offset. In the
44 * future, we may put those in here, to do clever things with merging vm_regions
47 * TODO: take a look at solari's vmem alloc. And consider keeping these in a
48 * tree of some sort for easier lookups. */
49 struct vm_region *create_vmr(struct proc *p, uintptr_t va, size_t len)
51 struct vm_region *vmr = 0, *vm_i, *vm_next;
56 assert(va + len <= UMAPTOP);
57 /* Is there room before the first one: */
58 vm_i = TAILQ_FIRST(&p->vm_regions);
59 /* This works for now, but if all we have is BRK_END ones, we'll start
60 * growing backwards (TODO) */
61 if (!vm_i || (va + len < vm_i->vm_base)) {
62 vmr = kmem_cache_alloc(vmr_kcache, 0);
65 memset(vmr, 0, sizeof(struct vm_region));
67 TAILQ_INSERT_HEAD(&p->vm_regions, vmr, vm_link);
69 TAILQ_FOREACH(vm_i, &p->vm_regions, vm_link) {
70 vm_next = TAILQ_NEXT(vm_i, vm_link);
71 gap_end = vm_next ? vm_next->vm_base : UMAPTOP;
72 /* skip til we get past the 'hint' va */
75 /* Find a gap that is big enough */
76 if (gap_end - vm_i->vm_end >= len) {
77 vmr = kmem_cache_alloc(vmr_kcache, 0);
80 memset(vmr, 0, sizeof(struct vm_region));
81 /* if we can put it at va, let's do that. o/w, put it so it
83 if ((gap_end >= va + len) && (va >= vm_i->vm_end))
86 vmr->vm_base = vm_i->vm_end;
87 TAILQ_INSERT_AFTER(&p->vm_regions, vm_i, vmr, vm_link);
92 /* Finalize the creation, if we got one */
95 vmr->vm_end = vmr->vm_base + len;
98 warn("Not making a VMR, wanted %p, + %p = %p", va, len, va + len);
102 /* Split a VMR at va, returning the new VMR. It is set up the same way, with
103 * file offsets fixed accordingly. 'va' is the beginning of the new one, and
104 * must be page aligned. */
105 struct vm_region *split_vmr(struct vm_region *old_vmr, uintptr_t va)
107 struct vm_region *new_vmr;
110 if ((old_vmr->vm_base >= va) || (old_vmr->vm_end <= va))
112 new_vmr = kmem_cache_alloc(vmr_kcache, 0);
113 TAILQ_INSERT_AFTER(&old_vmr->vm_proc->vm_regions, old_vmr, new_vmr,
115 new_vmr->vm_proc = old_vmr->vm_proc;
116 new_vmr->vm_base = va;
117 new_vmr->vm_end = old_vmr->vm_end;
118 old_vmr->vm_end = va;
119 new_vmr->vm_prot = old_vmr->vm_prot;
120 new_vmr->vm_flags = old_vmr->vm_flags;
121 if (old_vmr->vm_file) {
122 kref_get(&old_vmr->vm_file->f_kref, 1);
123 new_vmr->vm_file = old_vmr->vm_file;
124 new_vmr->vm_foff = old_vmr->vm_foff +
125 old_vmr->vm_end - old_vmr->vm_base;
126 pm_add_vmr(file2pm(old_vmr->vm_file), new_vmr);
128 new_vmr->vm_file = 0;
129 new_vmr->vm_foff = 0;
134 /* Merges two vm regions. For now, it will check to make sure they are the
135 * same. The second one will be destroyed. */
136 int merge_vmr(struct vm_region *first, struct vm_region *second)
138 assert(first->vm_proc == second->vm_proc);
139 if ((first->vm_end != second->vm_base) ||
140 (first->vm_prot != second->vm_prot) ||
141 (first->vm_flags != second->vm_flags) ||
142 (first->vm_file != second->vm_file))
144 if ((first->vm_file) && (second->vm_foff != first->vm_foff +
145 first->vm_end - first->vm_base))
147 first->vm_end = second->vm_end;
152 /* Attempts to merge vmr with adjacent VMRs, returning a ptr to be used for vmr.
153 * It could be the same struct vmr, or possibly another one (usually lower in
154 * the address space. */
155 struct vm_region *merge_me(struct vm_region *vmr)
157 struct vm_region *vmr_temp;
158 /* Merge will fail if it cannot do it. If it succeeds, the second VMR is
159 * destroyed, so we need to be a bit careful. */
160 vmr_temp = TAILQ_PREV(vmr, vmr_tailq, vm_link);
162 if (!merge_vmr(vmr_temp, vmr))
164 vmr_temp = TAILQ_NEXT(vmr, vm_link);
166 merge_vmr(vmr, vmr_temp);
170 /* Grows the vm region up to (and not including) va. Fails if another is in the
172 int grow_vmr(struct vm_region *vmr, uintptr_t va)
175 struct vm_region *next = TAILQ_NEXT(vmr, vm_link);
176 if (next && next->vm_base < va)
178 if (va <= vmr->vm_end)
184 /* Shrinks the vm region down to (and not including) va. Whoever calls this
185 * will need to sort out the page table entries. */
186 int shrink_vmr(struct vm_region *vmr, uintptr_t va)
189 if ((va < vmr->vm_base) || (va > vmr->vm_end))
195 /* Called by the unmapper, just cleans up. Whoever calls this will need to sort
196 * out the page table entries. */
197 void destroy_vmr(struct vm_region *vmr)
200 pm_remove_vmr(file2pm(vmr->vm_file), vmr);
201 kref_put(&vmr->vm_file->f_kref);
203 TAILQ_REMOVE(&vmr->vm_proc->vm_regions, vmr, vm_link);
204 kmem_cache_free(vmr_kcache, vmr);
207 /* Given a va and a proc (later an mm, possibly), returns the owning vmr, or 0
208 * if there is none. */
209 struct vm_region *find_vmr(struct proc *p, uintptr_t va)
211 struct vm_region *vmr;
212 /* ugly linear seach */
213 TAILQ_FOREACH(vmr, &p->vm_regions, vm_link) {
214 if ((vmr->vm_base <= va) && (vmr->vm_end > va))
220 /* Finds the first vmr after va (including the one holding va), or 0 if there is
222 struct vm_region *find_first_vmr(struct proc *p, uintptr_t va)
224 struct vm_region *vmr;
225 /* ugly linear seach */
226 TAILQ_FOREACH(vmr, &p->vm_regions, vm_link) {
227 if ((vmr->vm_base <= va) && (vmr->vm_end > va))
229 if (vmr->vm_base > va)
235 /* Makes sure that no VMRs cross either the start or end of the given region
236 * [va, va + len), splitting any VMRs that are on the endpoints. */
237 void isolate_vmrs(struct proc *p, uintptr_t va, size_t len)
239 struct vm_region *vmr;
240 if ((vmr = find_vmr(p, va)))
242 /* TODO: don't want to do another find (linear search) */
243 if ((vmr = find_vmr(p, va + len)))
244 split_vmr(vmr, va + len);
247 void unmap_and_destroy_vmrs(struct proc *p)
249 struct vm_region *vmr_i, *vmr_temp;
250 /* this only gets called from __proc_free, so there should be no sync
251 * concerns. still, better safe than sorry. */
252 spin_lock(&p->vmr_lock);
254 spin_lock(&p->pte_lock);
255 TAILQ_FOREACH(vmr_i, &p->vm_regions, vm_link) {
256 /* note this CB sets the PTE = 0, regardless of if it was P or not */
257 env_user_mem_walk(p, (void*)vmr_i->vm_base,
258 vmr_i->vm_end - vmr_i->vm_base, __vmr_free_pgs, 0);
260 spin_unlock(&p->pte_lock);
261 /* need the safe style, since destroy_vmr modifies the list. also, we want
262 * to do this outside the pte lock, since it grabs the pm lock. */
263 TAILQ_FOREACH_SAFE(vmr_i, &p->vm_regions, vm_link, vmr_temp)
265 spin_unlock(&p->vmr_lock);
268 /* Helper: copies the contents of pages from p to new p. For pages that aren't
269 * present, once we support swapping or CoW, we can do something more
270 * intelligent. 0 on success, -ERROR on failure. */
271 static int copy_pages(struct proc *p, struct proc *new_p, uintptr_t va_start,
274 /* Sanity checks. If these fail, we had a screwed up VMR.
275 * Check for: alignment, wraparound, or userspace addresses */
276 if ((PGOFF(va_start)) ||
278 (va_end < va_start) || /* now, start > UMAPTOP -> end > UMAPTOP */
279 (va_end > UMAPTOP)) {
280 warn("VMR mapping is probably screwed up (%p - %p)", va_start,
284 int copy_page(struct proc *p, pte_t *pte, void *va, void *arg) {
285 struct proc *new_p = (struct proc*)arg;
287 if (PAGE_UNMAPPED(*pte))
289 /* pages could be !P, but right now that's only for file backed VMRs
290 * undergoing page removal, which isn't the caller of copy_pages. */
291 if (PAGE_PRESENT(*pte)) {
292 /* TODO: check for jumbos */
293 if (upage_alloc(new_p, &pp, 0))
295 if (page_insert(new_p->env_pgdir, pp, va, *pte & PTE_PERM)) {
299 memcpy(page2kva(pp), ppn2kva(PTE2PPN(*pte)), PGSIZE);
301 } else if (PAGE_PAGED_OUT(*pte)) {
302 /* TODO: (SWAP) will need to either make a copy or CoW/refcnt the
303 * backend store. For now, this PTE will be the same as the
305 panic("Swapping not supported!");
307 panic("Weird PTE %p in %s!", *pte, __FUNCTION__);
311 return env_user_mem_walk(p, (void*)va_start, va_end - va_start, ©_page,
315 /* This will make new_p have the same VMRs as p, and it will make sure all
316 * physical pages are copied over, with the exception of MAP_SHARED files.
317 * This is used by fork().
319 * Note that if you are working on a VMR that is a file, you'll want to be
320 * careful about how it is mapped (SHARED, PRIVATE, etc). */
321 int duplicate_vmrs(struct proc *p, struct proc *new_p)
324 struct vm_region *vmr, *vm_i;
325 TAILQ_FOREACH(vm_i, &p->vm_regions, vm_link) {
326 vmr = kmem_cache_alloc(vmr_kcache, 0);
329 vmr->vm_proc = new_p;
330 vmr->vm_base = vm_i->vm_base;
331 vmr->vm_end = vm_i->vm_end;
332 vmr->vm_prot = vm_i->vm_prot;
333 vmr->vm_flags = vm_i->vm_flags;
334 vmr->vm_file = vm_i->vm_file;
335 vmr->vm_foff = vm_i->vm_foff;
337 kref_get(&vm_i->vm_file->f_kref, 1);
338 pm_add_vmr(file2pm(vm_i->vm_file), vmr);
340 if (!vmr->vm_file || vmr->vm_flags & MAP_PRIVATE) {
341 assert(!(vmr->vm_flags & MAP_SHARED));
342 /* Copy over the memory from one VMR to the other */
343 if ((ret = copy_pages(p, new_p, vmr->vm_base, vmr->vm_end)))
346 TAILQ_INSERT_TAIL(&new_p->vm_regions, vmr, vm_link);
351 void print_vmrs(struct proc *p)
354 struct vm_region *vmr;
355 printk("VM Regions for proc %d\n", p->pid);
356 TAILQ_FOREACH(vmr, &p->vm_regions, vm_link)
357 printk("%02d: (%p - %p): 0x%08x, 0x%08x, %p, %p\n", count++,
358 vmr->vm_base, vmr->vm_end, vmr->vm_prot, vmr->vm_flags,
359 vmr->vm_file, vmr->vm_foff);
362 /* Helper: returns the number of pages required to hold nr_bytes */
363 static unsigned long nr_pages(unsigned long nr_bytes)
365 return (nr_bytes >> PGSHIFT) + (PGOFF(nr_bytes) ? 1 : 0);
368 /* Error values aren't quite comprehensive - check man mmap() once we do better
371 * The mmap call's offset is in units of PGSIZE (like Linux's mmap2()), but
372 * internally, the offset is tracked in bytes. The reason for the PGSIZE is for
373 * 32bit apps to enumerate large files, but a full 64bit system won't need that.
374 * We track things internally in bytes since that is how file pointers work, vmr
375 * bases and ends, and similar math. While it's not a hard change, there's no
376 * need for it, and ideally we'll be a fully 64bit system before we deal with
377 * files that large. */
378 void *mmap(struct proc *p, uintptr_t addr, size_t len, int prot, int flags,
379 int fd, size_t offset)
381 struct file *file = NULL;
383 printd("mmap(addr %x, len %x, prot %x, flags %x, fd %x, off %x)\n", addr,
384 len, prot, flags, fd, offset);
385 if (fd >= 0 && (flags & MAP_ANON)) {
394 file = get_file_from_fd(&p->open_files, fd);
400 /* If they don't care where to put it, we'll start looking after the break.
401 * We could just have userspace handle this (in glibc's mmap), so we don't
402 * need to know about BRK_END, but this will work for now (and may avoid
403 * bugs). Note that this limits mmap(0) a bit. Keep this in sync with
404 * __do_mmap()'s check. (Both are necessary). */
407 /* Still need to enforce this: */
408 addr = MAX(addr, MMAP_LOWEST_VA);
409 /* Need to check addr + len, after we do our addr adjustments */
410 if ((addr + len > UMAPTOP) || (PGOFF(addr))) {
414 void *result = do_mmap(p, addr, len, prot, flags, file, offset);
416 kref_put(&file->f_kref);
420 /* Helper: returns TRUE if the VMR is allowed to access the file with prot.
421 * This is a bit ghetto still: messes with the file mode and assumes it can walk
422 * the dentry/inode paths without locking. It also ignores the CoW stuff we'll
423 * need to do eventually. */
424 static bool check_file_perms(struct vm_region *vmr, struct file *file, int prot)
427 if (prot & PROT_READ) {
428 if (check_perms(file->f_dentry->d_inode, S_IRUSR))
431 if (prot & PROT_WRITE) {
432 /* if vmr maps a file as MAP_SHARED, then we need to make sure the
433 * protection change is in compliance with the open mode of the
435 if (vmr->vm_flags & MAP_SHARED) {
436 if (!(file->f_mode & S_IWUSR)) {
437 /* at this point, we have a file opened in the wrong mode,
438 * but we may be allowed to access it still. */
439 if (check_perms(file->f_dentry->d_inode, S_IWUSR)) {
442 /* it is okay, though we need to change the file mode. (note
443 * the lack of a lock/protection (TODO) */
444 file->f_mode |= S_IWUSR;
447 } else { /* PRIVATE mapping */
448 /* TODO: we want a CoW mapping (like we want in handle_page_fault()),
449 * since there is a concern of a process having the page already
450 * mapped in to a file it does not have permissions to, and then
451 * mprotecting it so it can access it. So we can't just change
452 * the prot, and we don't know yet if a page is mapped in. To
453 * handle this, we ought to sort out the CoW bit, and then this
454 * will be easy. Til then, just do a permissions check. If we
455 * start having weird issues with libc overwriting itself (since
456 * procs mprotect that W), then change this. */
457 if (check_perms(file->f_dentry->d_inode, S_IWUSR))
462 out_error: /* for debugging */
463 printk("[kernel] mmap perm check failed for %s for access %d\n",
464 file_name(file), prot);
468 /* Helper, maps in page at addr, but only if nothing is present there. Returns
469 * 0 on success. If this is called by non-PM code, we'll store your ref in the
471 static int map_page_at_addr(struct proc *p, struct page *page, uintptr_t addr,
475 spin_lock(&p->pte_lock); /* walking and changing PTEs */
476 /* find offending PTE (prob don't read this in). This might alloc an
477 * intermediate page table page. */
478 pte = pgdir_walk(p->env_pgdir, (void*)addr, TRUE);
480 spin_unlock(&p->pte_lock);
483 /* a spurious, valid PF is possible due to a legit race: the page might have
484 * been faulted in by another core already (and raced on the memory lock),
485 * in which case we should just return. */
486 if (PAGE_PRESENT(*pte)) {
487 spin_unlock(&p->pte_lock);
488 /* callers expect us to eat the ref if we succeed. */
492 /* preserve the dirty bit - pm removal could be looking concurrently */
493 prot |= (*pte & PTE_D ? PTE_D : 0);
494 /* We have a ref to page, which we are storing in the PTE */
495 *pte = PTE(page2ppn(page), PTE_P | prot);
496 spin_unlock(&p->pte_lock);
500 /* Helper: copies *pp's contents to a new page, replacing your page pointer. If
501 * this succeeds, you'll have a non-PM page, which matters for how you put it.*/
502 static int __copy_and_swap_pmpg(struct proc *p, struct page **pp)
504 struct page *new_page, *old_page = *pp;
505 if (upage_alloc(p, &new_page, FALSE))
507 memcpy(page2kva(new_page), page2kva(old_page), PGSIZE);
508 pm_put_page(old_page);
513 /* Hold the VMR lock when you call this - it'll assume the entire VA range is
514 * mappable, which isn't true if there are concurrent changes to the VMRs. */
515 static int populate_anon_va(struct proc *p, uintptr_t va, unsigned long nr_pgs,
520 for (long i = 0; i < nr_pgs; i++) {
521 if (upage_alloc(p, &page, TRUE))
523 /* could imagine doing a memwalk instead of a for loop */
524 ret = map_page_at_addr(p, page, va + i * PGSIZE, pte_prot);
533 /* This will periodically unlock the vmr lock. */
534 static int populate_pm_va(struct proc *p, uintptr_t va, unsigned long nr_pgs,
535 int pte_prot, struct page_map *pm, size_t offset,
536 int flags, bool exec)
539 unsigned long pm_idx0 = offset >> PGSHIFT;
540 int vmr_history = ACCESS_ONCE(p->vmr_history);
543 /* locking rules: start the loop holding the vmr lock, enter and exit the
544 * entire func holding the lock. */
545 for (long i = 0; i < nr_pgs; i++) {
546 ret = pm_load_page_nowait(pm, pm_idx0 + i, &page);
550 spin_unlock(&p->vmr_lock);
551 /* might block here, can't hold the spinlock */
552 ret = pm_load_page(pm, pm_idx0 + i, &page);
553 spin_lock(&p->vmr_lock);
556 /* while we were sleeping, the VMRs could have changed on us. */
557 if (vmr_history != ACCESS_ONCE(p->vmr_history)) {
559 printk("[kernel] FYI: VMR changed during populate\n");
563 if (flags & MAP_PRIVATE) {
564 ret = __copy_and_swap_pmpg(p, &page);
570 /* if this is an executable page, we might have to flush the
571 * instruction cache if our HW requires it.
572 * TODO: is this still needed? andrew put this in a while ago*/
574 icache_flush_page(0, page2kva(page));
575 ret = map_page_at_addr(p, page, va + i * PGSIZE, pte_prot);
576 if (atomic_read(&page->pg_flags) & PG_PAGEMAP)
584 void *do_mmap(struct proc *p, uintptr_t addr, size_t len, int prot, int flags,
585 struct file *file, size_t offset)
587 len = ROUNDUP(len, PGSIZE);
588 struct vm_region *vmr, *vmr_temp;
590 /* read/write vmr lock (will change the tree) */
591 spin_lock(&p->vmr_lock);
593 /* Sanity check, for callers that bypass mmap(). We want addr for anon
594 * memory to start above the break limit (BRK_END), but not 0. Keep this in
595 * sync with BRK_END in mmap(). */
598 assert(!PGOFF(offset));
600 /* MCPs will need their code and data pinned. This check will start to fail
601 * after uthread_slim_init(), at which point userspace should have enough
602 * control over its mmaps (i.e. no longer done by LD or load_elf) that it
603 * can ask for pinned and populated pages. Except for dl_opens(). */
604 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
605 if (file && (atomic_read(&vcpd->flags) & VC_SCP_NOVCCTX))
606 flags |= MAP_POPULATE | MAP_LOCKED;
607 /* Need to make sure nothing is in our way when we want a FIXED location.
608 * We just need to split on the end points (if they exist), and then remove
609 * everything in between. __do_munmap() will do this. Careful, this means
610 * an mmap can be an implied munmap() (not my call...). */
611 if (flags & MAP_FIXED)
612 __do_munmap(p, addr, len);
613 vmr = create_vmr(p, addr, len);
615 printk("[kernel] do_mmap() aborted for %p + %d!\n", addr, len);
617 spin_unlock(&p->vmr_lock);
622 vmr->vm_flags = flags;
624 if (!check_file_perms(vmr, file, prot)) {
625 assert(!vmr->vm_file);
628 spin_unlock(&p->vmr_lock);
631 /* TODO: consider locking the file while checking (not as manadatory as
632 * in handle_page_fault() */
633 if (nr_pages(offset + len) > nr_pages(file->f_dentry->d_inode->i_size)) {
634 /* We're allowing them to set up the VMR, though if they attempt to
635 * fault in any pages beyond the file's limit, they'll fail. Since
636 * they might not access the region, we need to make sure POPULATE
637 * is off. FYI, 64 bit glibc shared libs map in an extra 2MB of
638 * unaligned space between their RO and RW sections, but then
639 * immediately mprotect it to PROT_NONE. */
640 flags &= ~MAP_POPULATE;
642 /* Prep the FS to make sure it can mmap the file. Slightly weird
643 * semantics: if we fail and had munmapped the space, they will have a
644 * hole in their VM now. */
645 if (file->f_op->mmap(file, vmr)) {
646 assert(!vmr->vm_file);
648 set_errno(EACCES); /* not quite */
649 spin_unlock(&p->vmr_lock);
652 kref_get(&file->f_kref, 1);
653 pm_add_vmr(file2pm(file), vmr);
656 vmr->vm_foff = offset;
657 vmr = merge_me(vmr); /* attempts to merge with neighbors */
659 if (flags & MAP_POPULATE && prot != PROT_NONE) {
660 int pte_prot = (prot & PROT_WRITE) ? PTE_USER_RW :
661 (prot & (PROT_READ|PROT_EXEC)) ? PTE_USER_RO : 0;
662 unsigned long nr_pgs = len >> PGSHIFT;
665 ret = populate_anon_va(p, addr, nr_pgs, pte_prot);
667 /* Note: this will unlock if it blocks. our refcnt on the file
668 * keeps the pm alive when we unlock */
669 ret = populate_pm_va(p, addr, nr_pgs, pte_prot, file->f_mapping,
670 offset, flags, prot & PROT_EXEC);
672 if (ret == -ENOMEM) {
673 spin_unlock(&p->vmr_lock);
674 printk("[kernel] ENOMEM, killing %d\n", p->pid);
676 return MAP_FAILED; /* will never make it back to userspace */
679 spin_unlock(&p->vmr_lock);
683 int mprotect(struct proc *p, uintptr_t addr, size_t len, int prot)
685 printd("mprotect: (addr %p, len %p, prot 0x%x)\n", addr, len, prot);
688 if ((addr % PGSIZE) || (addr < MMAP_LOWEST_VA)) {
692 uintptr_t end = ROUNDUP(addr + len, PGSIZE);
693 if (end > UMAPTOP || addr > end) {
697 /* read/write lock, will probably change the tree and settings */
698 spin_lock(&p->vmr_lock);
700 int ret = __do_mprotect(p, addr, len, prot);
701 spin_unlock(&p->vmr_lock);
705 /* This does not care if the region is not mapped. POSIX says you should return
706 * ENOMEM if any part of it is unmapped. Can do this later if we care, based on
707 * the VMRs, not the actual page residency. */
708 int __do_mprotect(struct proc *p, uintptr_t addr, size_t len, int prot)
710 struct vm_region *vmr, *next_vmr;
712 bool shootdown_needed = FALSE;
713 int pte_prot = (prot & PROT_WRITE) ? PTE_USER_RW :
714 (prot & (PROT_READ|PROT_EXEC)) ? PTE_USER_RO : 0;
715 /* TODO: this is aggressively splitting, when we might not need to if the
716 * prots are the same as the previous. Plus, there are three excessive
717 * scans. Finally, we might be able to merge when we are done. */
718 isolate_vmrs(p, addr, len);
719 vmr = find_first_vmr(p, addr);
720 while (vmr && vmr->vm_base < addr + len) {
721 if (vmr->vm_prot == prot)
723 if (vmr->vm_file && !check_file_perms(vmr, vmr->vm_file, prot)) {
728 spin_lock(&p->pte_lock); /* walking and changing PTEs */
729 /* TODO: use a memwalk */
730 for (uintptr_t va = vmr->vm_base; va < vmr->vm_end; va += PGSIZE) {
731 pte = pgdir_walk(p->env_pgdir, (void*)va, 0);
732 if (pte && PAGE_PRESENT(*pte)) {
733 *pte = (*pte & ~PTE_PERM) | pte_prot;
734 shootdown_needed = TRUE;
737 spin_unlock(&p->pte_lock);
738 next_vmr = TAILQ_NEXT(vmr, vm_link);
741 if (shootdown_needed)
742 proc_tlbshootdown(p, addr, addr + len);
746 int munmap(struct proc *p, uintptr_t addr, size_t len)
748 printd("munmap(addr %x, len %x)\n", addr, len);
751 len = ROUNDUP(len, PGSIZE);
753 if ((addr % PGSIZE) || (addr < MMAP_LOWEST_VA)) {
757 uintptr_t end = ROUNDUP(addr + len, PGSIZE);
758 if (end > UMAPTOP || addr > end) {
762 /* read/write: changing the vmrs (trees, properties, and whatnot) */
763 spin_lock(&p->vmr_lock);
765 int ret = __do_munmap(p, addr, len);
766 spin_unlock(&p->vmr_lock);
770 static int __munmap_mark_not_present(struct proc *p, pte_t *pte, void *va,
773 bool *shootdown_needed = (bool*)arg;
775 /* could put in some checks here for !P and also !0 */
776 if (!PAGE_PRESENT(*pte)) /* unmapped (== 0) *ptes are also not PTE_P */
778 page = ppn2page(PTE2PPN(*pte));
780 *shootdown_needed = TRUE;
784 /* If our page is actually in the PM, we don't do anything. All a page map
785 * really needs is for our VMR to no longer track it (vmr being in the pm's
786 * list) and to not point at its pages (mark it 0, dude).
788 * But private mappings mess with that a bit. Luckily, we can tell by looking
789 * at a page whether the specific page is in the PM or not. If it isn't, we
790 * still need to free our "VMR local" copy.
792 * For pages in a PM, we're racing with PM removers. Both of us sync with the
793 * mm lock, so once we hold the lock, it's a matter of whether or not the PTE is
794 * 0 or not. If it isn't, then we're still okay to look at the page. Consider
795 * the PTE a weak ref on the page. So long as you hold the mm lock, you can
796 * look at the PTE and know the page isn't being freed. */
797 static int __vmr_free_pgs(struct proc *p, pte_t *pte, void *va, void *arg)
802 page = ppn2page(PTE2PPN(*pte));
804 if (!(atomic_read(&page->pg_flags) & PG_PAGEMAP))
809 int __do_munmap(struct proc *p, uintptr_t addr, size_t len)
811 struct vm_region *vmr, *next_vmr, *first_vmr;
813 bool shootdown_needed = FALSE;
815 /* TODO: this will be a bit slow, since we end up doing three linear
816 * searches (two in isolate, one in find_first). */
817 isolate_vmrs(p, addr, len);
818 first_vmr = find_first_vmr(p, addr);
820 spin_lock(&p->pte_lock); /* changing PTEs */
821 while (vmr && vmr->vm_base < addr + len) {
822 env_user_mem_walk(p, (void*)vmr->vm_base, vmr->vm_end - vmr->vm_base,
823 __munmap_mark_not_present, &shootdown_needed);
824 vmr = TAILQ_NEXT(vmr, vm_link);
826 spin_unlock(&p->pte_lock);
827 /* we haven't freed the pages yet; still using the PTEs to store the them.
828 * There should be no races with inserts/faults, since we still hold the mm
829 * lock since the previous CB. */
830 if (shootdown_needed)
831 proc_tlbshootdown(p, addr, addr + len);
833 while (vmr && vmr->vm_base < addr + len) {
834 /* there is rarely more than one VMR in this loop. o/w, we'll need to
835 * gather up the vmrs and destroy outside the pte_lock. */
836 spin_lock(&p->pte_lock); /* changing PTEs */
837 env_user_mem_walk(p, (void*)vmr->vm_base, vmr->vm_end - vmr->vm_base,
839 spin_unlock(&p->pte_lock);
840 next_vmr = TAILQ_NEXT(vmr, vm_link);
847 /* Helper - drop the page differently based on where it is from */
848 static void __put_page(struct page *page)
850 if (atomic_read(&page->pg_flags) & PG_PAGEMAP)
856 static int __hpf_load_page(struct proc *p, struct page_map *pm,
857 unsigned long idx, struct page **page, bool first)
860 int coreid = core_id();
861 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
862 bool wake_scp = FALSE;
863 spin_lock(&p->proc_lock);
865 case (PROC_RUNNING_S):
867 __proc_set_state(p, PROC_WAITING);
868 /* it's possible for HPF to loop a few times; we can only save the
869 * first time, o/w we could clobber. */
871 __proc_save_context_s(p, pcpui->cur_ctx);
872 __proc_save_fpu_s(p);
873 /* We clear the owner, since userspace doesn't run here
874 * anymore, but we won't abandon since the fault handler
875 * still runs in our process. */
876 clear_owning_proc(coreid);
878 /* other notes: we don't currently need to tell the ksched
879 * we switched from running to waiting, though we probably
880 * will later for more generic scheds. */
882 case (PROC_RUNNABLE_M):
883 case (PROC_RUNNING_M):
884 spin_unlock(&p->proc_lock);
885 return -EAGAIN; /* will get reflected back to userspace */
887 spin_unlock(&p->proc_lock);
890 /* shouldn't have any waitings, under the current yield style. if
891 * this becomes an issue, we can branch on is_mcp(). */
892 printk("HPF unexpectecd state(%s)", procstate2str(p->state));
893 spin_unlock(&p->proc_lock);
896 spin_unlock(&p->proc_lock);
897 ret = pm_load_page(pm, idx, page);
901 printk("load failed with ret %d\n", ret);
904 /* need to put our old ref, next time around HPF will get another. */
909 /* Returns 0 on success, or an appropriate -error code.
911 * Notes: if your TLB caches negative results, you'll need to flush the
912 * appropriate tlb entry. Also, you could have a weird race where a present PTE
913 * faulted for a different reason (was mprotected on another core), and the
914 * shootdown is on its way. Userspace should have waited for the mprotect to
915 * return before trying to write (or whatever), so we don't care and will fault
917 int handle_page_fault(struct proc *p, uintptr_t va, int prot)
919 struct vm_region *vmr;
921 unsigned int f_idx; /* index of the missing page in the file */
925 va = ROUNDDOWN(va,PGSIZE);
927 if (prot != PROT_READ && prot != PROT_WRITE && prot != PROT_EXEC)
930 /* read access to the VMRs TODO: RCU */
931 spin_lock(&p->vmr_lock);
932 /* Check the vmr's protection */
933 vmr = find_vmr(p, va);
934 if (!vmr) { /* not mapped at all */
938 if (!(vmr->vm_prot & prot)) { /* wrong prots for this vmr */
943 /* No file - just want anonymous memory */
944 if (upage_alloc(p, &a_page, TRUE)) {
949 /* If this fails, either something got screwed up with the VMR, or the
950 * permissions changed after mmap/mprotect. Either way, I want to know
951 * (though it's not critical). */
952 if (!check_file_perms(vmr, vmr->vm_file, prot))
953 printk("[kernel] possible issue with VMR prots on file %s!\n",
954 file_name(vmr->vm_file));
955 /* Load the file's page in the page cache.
956 * TODO: (BLK) Note, we are holding the mem lock! We need to rewrite
957 * this stuff so we aren't hold the lock as excessively as we are, and
958 * such that we can block and resume later. */
959 assert(!PGOFF(va - vmr->vm_base + vmr->vm_foff));
960 f_idx = (va - vmr->vm_base + vmr->vm_foff) >> PGSHIFT;
961 /* TODO: need some sort of lock on the file to deal with someone
962 * concurrently shrinking it. Adding 1 to f_idx, since it is
964 if (f_idx + 1 > nr_pages(vmr->vm_file->f_dentry->d_inode->i_size)) {
965 /* We're asking for pages that don't exist in the file */
966 /* TODO: unlock the file */
967 ret = -ESPIPE; /* linux sends a SIGBUS at access time */
970 ret = pm_load_page_nowait(vmr->vm_file->f_mapping, f_idx, &a_page);
974 /* keep the file alive after we unlock */
975 kref_get(&vmr->vm_file->f_kref, 1);
976 spin_unlock(&p->vmr_lock);
977 ret = __hpf_load_page(p, vmr->vm_file->f_mapping, f_idx, &a_page,
980 kref_put(&vmr->vm_file->f_kref);
985 /* If we want a private map, we'll preemptively give you a new page. We
986 * used to just care if it was private and writable, but were running
987 * into issues with libc changing its mapping (map private, then
988 * mprotect to writable...) In the future, we want to CoW this anyway,
989 * so it's not a big deal. */
990 if ((vmr->vm_flags & MAP_PRIVATE)) {
991 ret = __copy_and_swap_pmpg(p, &a_page);
995 /* if this is an executable page, we might have to flush the instruction
996 * cache if our HW requires it. */
997 if (vmr->vm_prot & PROT_EXEC)
998 icache_flush_page((void*)va, page2kva(a_page));
1000 /* update the page table TODO: careful with MAP_PRIVATE etc. might do this
1001 * separately (file, no file) */
1002 int pte_prot = (vmr->vm_prot & PROT_WRITE) ? PTE_USER_RW :
1003 (vmr->vm_prot & (PROT_READ|PROT_EXEC)) ? PTE_USER_RO : 0;
1004 ret = map_page_at_addr(p, a_page, va, pte_prot);
1005 /* fall through, even for errors */
1007 /* the VMR's existence in the PM (via the mmap) allows us to have PTE point
1008 * to a_page without it magically being reallocated. For non-PM memory
1009 * (anon memory or private pages) we transferred the ref to the PTE. */
1010 if (atomic_read(&a_page->pg_flags) & PG_PAGEMAP)
1011 pm_put_page(a_page);
1013 spin_unlock(&p->vmr_lock);
1017 /* Attempts to populate the pages, as if there was a page faults. Bails on
1018 * errors, and returns the number of pages populated. */
1019 unsigned long populate_va(struct proc *p, uintptr_t va, unsigned long nr_pgs)
1021 struct vm_region *vmr, vmr_copy;
1022 unsigned long nr_pgs_this_vmr;
1023 unsigned long nr_filled = 0;
1027 /* we can screw around with ways to limit the find_vmr calls (can do the
1028 * next in line if we didn't unlock, etc., but i don't expect us to do this
1029 * for more than a single VMR in most cases. */
1030 spin_lock(&p->vmr_lock);
1032 vmr = find_vmr(p, va);
1035 if (vmr->vm_prot == PROT_NONE)
1037 pte_prot = (vmr->vm_prot & PROT_WRITE) ? PTE_USER_RW :
1038 (vmr->vm_prot & (PROT_READ|PROT_EXEC)) ? PTE_USER_RO : 0;
1039 nr_pgs_this_vmr = MIN(nr_pgs, (vmr->vm_end - va) >> PGSHIFT);
1040 if (!vmr->vm_file) {
1041 if (populate_anon_va(p, va, nr_pgs_this_vmr, pte_prot)) {
1042 /* on any error, we can just bail. we might be underestimating
1047 /* need to keep the file alive in case we unlock/block */
1048 kref_get(&vmr->vm_file->f_kref, 1);
1049 if (populate_pm_va(p, va, nr_pgs_this_vmr, pte_prot,
1050 vmr->vm_file->f_mapping,
1051 vmr->vm_foff - (va - vmr->vm_base),
1052 vmr->vm_flags, vmr->vm_prot & PROT_EXEC)) {
1053 /* we might have failed if the underlying file doesn't cover the
1054 * mmap window, depending on how we'll deal with truncation. */
1057 kref_put(&vmr->vm_file->f_kref);
1059 nr_filled += nr_pgs_this_vmr;
1060 va += nr_pgs_this_vmr << PGSHIFT;
1061 nr_pgs -= nr_pgs_this_vmr;
1063 spin_unlock(&p->vmr_lock);
1067 /* Kernel Dynamic Memory Mappings */
1068 uintptr_t dyn_vmap_llim = KERN_DYN_TOP;
1069 spinlock_t dyn_vmap_lock = SPINLOCK_INITIALIZER;
1071 /* Reserve space in the kernel dynamic memory map area */
1072 uintptr_t get_vmap_segment(unsigned long num_pages)
1075 spin_lock(&dyn_vmap_lock);
1076 retval = dyn_vmap_llim - num_pages * PGSIZE;
1077 if ((retval > ULIM) && (retval < KERN_DYN_TOP)) {
1078 dyn_vmap_llim = retval;
1080 warn("[kernel] dynamic mapping failed!");
1083 spin_unlock(&dyn_vmap_lock);
1087 /* Give up your space. Note this isn't supported yet */
1088 uintptr_t put_vmap_segment(uintptr_t vaddr, unsigned long num_pages)
1090 /* TODO: use vmem regions for adjustable vmap segments */
1091 warn("Not implemented, leaking vmem space.\n");
1095 /* Map a virtual address chunk to physical addresses. Make sure you got a vmap
1096 * segment before actually trying to do the mapping.
1098 * Careful with more than one 'page', since it will assume your physical pages
1099 * are also contiguous. Most callers will only use one page.
1101 * Finally, note that this does not care whether or not there are real pages
1102 * being mapped, and will not attempt to incref your page (if there is such a
1103 * thing). Handle your own refcnting for pages. */
1104 int map_vmap_segment(uintptr_t vaddr, uintptr_t paddr, unsigned long num_pages,
1107 /* For now, we only handle the root pgdir, and not any of the other ones
1108 * (like for processes). To do so, we'll need to insert into every pgdir,
1109 * and send tlb shootdowns to those that are active (which we don't track
1114 /* TODO: (MM) you should lock on boot pgdir modifications. A vm region lock
1115 * isn't enough, since there might be a race on outer levels of page tables.
1116 * For now, we'll just use the dyn_vmap_lock (which technically works). */
1117 spin_lock(&dyn_vmap_lock);
1122 for (int i = 0; i < num_pages; i++) {
1123 pte = pgdir_walk(boot_pgdir, (void*)(vaddr + i * PGSIZE), 1);
1125 spin_unlock(&dyn_vmap_lock);
1128 /* You probably should have unmapped first */
1130 warn("Existing PTE value %p\n", *pte);
1131 *pte = PTE(pa2ppn(paddr + i * PGSIZE), perm);
1133 spin_unlock(&dyn_vmap_lock);
1137 /* Unmaps / 0's the PTEs of a chunk of vaddr space */
1138 int unmap_vmap_segment(uintptr_t vaddr, unsigned long num_pages)
1140 /* Not a big deal - won't need this til we do something with kthreads */
1141 warn("Incomplete, don't call this yet.");
1142 spin_lock(&dyn_vmap_lock);
1143 /* TODO: For all pgdirs */
1145 for (int i = 0; i < num_pages; i++) {
1146 pte = pgdir_walk(boot_pgdir, (void*)(vaddr + i * PGSIZE), 1);
1149 /* TODO: TLB shootdown. Also note that the global flag is set on the PTE
1150 * (for x86 for now), which requires a global shootdown. bigger issue is
1151 * the TLB shootdowns for multiple pgdirs. We'll need to remove from every
1152 * pgdir, and send tlb shootdowns to those that are active (which we don't
1154 spin_unlock(&dyn_vmap_lock);
1158 /* This can handle unaligned paddrs */
1159 static uintptr_t vmap_pmem_flags(uintptr_t paddr, size_t nr_bytes, int flags)
1162 unsigned long nr_pages;
1163 assert(nr_bytes && paddr);
1164 nr_bytes += PGOFF(paddr);
1165 nr_pages = ROUNDUP(nr_bytes, PGSIZE) >> PGSHIFT;
1166 vaddr = get_vmap_segment(nr_pages);
1168 warn("Unable to get a vmap segment"); /* probably a bug */
1171 /* it's not strictly necessary to drop paddr's pgoff, but it might save some
1172 * vmap heartache in the future. */
1173 if (map_vmap_segment(vaddr, PG_ADDR(paddr), nr_pages,
1174 PTE_P | PTE_KERN_RW | flags)) {
1175 warn("Unable to map a vmap segment"); /* probably a bug */
1178 return vaddr + PGOFF(paddr);
1181 uintptr_t vmap_pmem(uintptr_t paddr, size_t nr_bytes)
1183 return vmap_pmem_flags(paddr, nr_bytes, 0);
1186 uintptr_t vmap_pmem_nocache(uintptr_t paddr, size_t nr_bytes)
1188 return vmap_pmem_flags(paddr, nr_bytes, PTE_NOCACHE);
1191 int vunmap_vmem(uintptr_t vaddr, size_t nr_bytes)
1193 unsigned long nr_pages = ROUNDUP(nr_bytes, PGSIZE) >> PGSHIFT;
1194 unmap_vmap_segment(vaddr, nr_pages);
1195 put_vmap_segment(vaddr, nr_pages);