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>
29 struct kmem_cache *vmr_kcache;
31 static int __vmr_free_pgs(struct proc *p, pte_t pte, void *va, void *arg);
32 static int populate_pm_va(struct proc *p, uintptr_t va, unsigned long nr_pgs,
33 int pte_prot, struct page_map *pm, size_t offset,
34 int flags, bool exec);
36 /* minor helper, will ease the file->chan transition */
37 static struct page_map *file2pm(struct file *file)
39 return file->f_mapping;
44 vmr_kcache = kmem_cache_create("vm_regions", sizeof(struct vm_region),
45 __alignof__(struct dentry), 0, 0, 0);
48 /* For now, the caller will set the prot, flags, file, and offset. In the
49 * future, we may put those in here, to do clever things with merging vm_regions
52 * TODO: take a look at solari's vmem alloc. And consider keeping these in a
53 * tree of some sort for easier lookups. */
54 struct vm_region *create_vmr(struct proc *p, uintptr_t va, size_t len)
56 struct vm_region *vmr = 0, *vm_i, *vm_next;
61 assert(va + len <= UMAPTOP);
62 /* Is there room before the first one: */
63 vm_i = TAILQ_FIRST(&p->vm_regions);
64 /* This works for now, but if all we have is BRK_END ones, we'll start
65 * growing backwards (TODO) */
66 if (!vm_i || (va + len <= vm_i->vm_base)) {
67 vmr = kmem_cache_alloc(vmr_kcache, 0);
70 memset(vmr, 0, sizeof(struct vm_region));
72 TAILQ_INSERT_HEAD(&p->vm_regions, vmr, vm_link);
74 TAILQ_FOREACH(vm_i, &p->vm_regions, vm_link) {
75 vm_next = TAILQ_NEXT(vm_i, vm_link);
76 gap_end = vm_next ? vm_next->vm_base : UMAPTOP;
77 /* skip til we get past the 'hint' va */
80 /* Find a gap that is big enough */
81 if (gap_end - vm_i->vm_end >= len) {
82 vmr = kmem_cache_alloc(vmr_kcache, 0);
85 memset(vmr, 0, sizeof(struct vm_region));
86 /* if we can put it at va, let's do that. o/w, put it so it
88 if ((gap_end >= va + len) && (va >= vm_i->vm_end))
91 vmr->vm_base = vm_i->vm_end;
92 TAILQ_INSERT_AFTER(&p->vm_regions, vm_i, vmr, vm_link);
97 /* Finalize the creation, if we got one */
100 vmr->vm_end = vmr->vm_base + len;
103 warn("Not making a VMR, wanted %p, + %p = %p", va, len, va + len);
107 /* Split a VMR at va, returning the new VMR. It is set up the same way, with
108 * file offsets fixed accordingly. 'va' is the beginning of the new one, and
109 * must be page aligned. */
110 struct vm_region *split_vmr(struct vm_region *old_vmr, uintptr_t va)
112 struct vm_region *new_vmr;
115 if ((old_vmr->vm_base >= va) || (old_vmr->vm_end <= va))
117 new_vmr = kmem_cache_alloc(vmr_kcache, 0);
118 TAILQ_INSERT_AFTER(&old_vmr->vm_proc->vm_regions, old_vmr, new_vmr,
120 new_vmr->vm_proc = old_vmr->vm_proc;
121 new_vmr->vm_base = va;
122 new_vmr->vm_end = old_vmr->vm_end;
123 old_vmr->vm_end = va;
124 new_vmr->vm_prot = old_vmr->vm_prot;
125 new_vmr->vm_flags = old_vmr->vm_flags;
126 if (old_vmr->vm_file) {
127 kref_get(&old_vmr->vm_file->f_kref, 1);
128 new_vmr->vm_file = old_vmr->vm_file;
129 new_vmr->vm_foff = old_vmr->vm_foff +
130 old_vmr->vm_end - old_vmr->vm_base;
131 pm_add_vmr(file2pm(old_vmr->vm_file), new_vmr);
133 new_vmr->vm_file = 0;
134 new_vmr->vm_foff = 0;
139 /* Merges two vm regions. For now, it will check to make sure they are the
140 * same. The second one will be destroyed. */
141 int merge_vmr(struct vm_region *first, struct vm_region *second)
143 assert(first->vm_proc == second->vm_proc);
144 if ((first->vm_end != second->vm_base) ||
145 (first->vm_prot != second->vm_prot) ||
146 (first->vm_flags != second->vm_flags) ||
147 (first->vm_file != second->vm_file))
149 if ((first->vm_file) && (second->vm_foff != first->vm_foff +
150 first->vm_end - first->vm_base))
152 first->vm_end = second->vm_end;
157 /* Attempts to merge vmr with adjacent VMRs, returning a ptr to be used for vmr.
158 * It could be the same struct vmr, or possibly another one (usually lower in
159 * the address space. */
160 struct vm_region *merge_me(struct vm_region *vmr)
162 struct vm_region *vmr_temp;
163 /* Merge will fail if it cannot do it. If it succeeds, the second VMR is
164 * destroyed, so we need to be a bit careful. */
165 vmr_temp = TAILQ_PREV(vmr, vmr_tailq, vm_link);
167 if (!merge_vmr(vmr_temp, vmr))
169 vmr_temp = TAILQ_NEXT(vmr, vm_link);
171 merge_vmr(vmr, vmr_temp);
175 /* Grows the vm region up to (and not including) va. Fails if another is in the
177 int grow_vmr(struct vm_region *vmr, uintptr_t va)
180 struct vm_region *next = TAILQ_NEXT(vmr, vm_link);
181 if (next && next->vm_base < va)
183 if (va <= vmr->vm_end)
189 /* Shrinks the vm region down to (and not including) va. Whoever calls this
190 * will need to sort out the page table entries. */
191 int shrink_vmr(struct vm_region *vmr, uintptr_t va)
194 if ((va < vmr->vm_base) || (va > vmr->vm_end))
200 /* Called by the unmapper, just cleans up. Whoever calls this will need to sort
201 * out the page table entries. */
202 void destroy_vmr(struct vm_region *vmr)
205 pm_remove_vmr(file2pm(vmr->vm_file), vmr);
206 kref_put(&vmr->vm_file->f_kref);
208 TAILQ_REMOVE(&vmr->vm_proc->vm_regions, vmr, vm_link);
209 kmem_cache_free(vmr_kcache, vmr);
212 /* Given a va and a proc (later an mm, possibly), returns the owning vmr, or 0
213 * if there is none. */
214 struct vm_region *find_vmr(struct proc *p, uintptr_t va)
216 struct vm_region *vmr;
217 /* ugly linear seach */
218 TAILQ_FOREACH(vmr, &p->vm_regions, vm_link) {
219 if ((vmr->vm_base <= va) && (vmr->vm_end > va))
225 /* Finds the first vmr after va (including the one holding va), or 0 if there is
227 struct vm_region *find_first_vmr(struct proc *p, uintptr_t va)
229 struct vm_region *vmr;
230 /* ugly linear seach */
231 TAILQ_FOREACH(vmr, &p->vm_regions, vm_link) {
232 if ((vmr->vm_base <= va) && (vmr->vm_end > va))
234 if (vmr->vm_base > va)
240 /* Makes sure that no VMRs cross either the start or end of the given region
241 * [va, va + len), splitting any VMRs that are on the endpoints. */
242 void isolate_vmrs(struct proc *p, uintptr_t va, size_t len)
244 struct vm_region *vmr;
245 if ((vmr = find_vmr(p, va)))
247 /* TODO: don't want to do another find (linear search) */
248 if ((vmr = find_vmr(p, va + len)))
249 split_vmr(vmr, va + len);
252 void unmap_and_destroy_vmrs(struct proc *p)
254 struct vm_region *vmr_i, *vmr_temp;
255 /* this only gets called from __proc_free, so there should be no sync
256 * concerns. still, better safe than sorry. */
257 spin_lock(&p->vmr_lock);
259 spin_lock(&p->pte_lock);
260 TAILQ_FOREACH(vmr_i, &p->vm_regions, vm_link) {
261 /* note this CB sets the PTE = 0, regardless of if it was P or not */
262 env_user_mem_walk(p, (void*)vmr_i->vm_base,
263 vmr_i->vm_end - vmr_i->vm_base, __vmr_free_pgs, 0);
265 spin_unlock(&p->pte_lock);
266 /* need the safe style, since destroy_vmr modifies the list. also, we want
267 * to do this outside the pte lock, since it grabs the pm lock. */
268 TAILQ_FOREACH_SAFE(vmr_i, &p->vm_regions, vm_link, vmr_temp)
270 spin_unlock(&p->vmr_lock);
273 /* Helper: copies the contents of pages from p to new p. For pages that aren't
274 * present, once we support swapping or CoW, we can do something more
275 * intelligent. 0 on success, -ERROR on failure. Can't handle jumbos. */
276 static int copy_pages(struct proc *p, struct proc *new_p, uintptr_t va_start,
279 /* Sanity checks. If these fail, we had a screwed up VMR.
280 * Check for: alignment, wraparound, or userspace addresses */
281 if ((PGOFF(va_start)) ||
283 (va_end < va_start) || /* now, start > UMAPTOP -> end > UMAPTOP */
284 (va_end > UMAPTOP)) {
285 warn("VMR mapping is probably screwed up (%p - %p)", va_start,
289 int copy_page(struct proc *p, pte_t pte, void *va, void *arg) {
290 struct proc *new_p = (struct proc*)arg;
292 if (pte_is_unmapped(pte))
294 /* pages could be !P, but right now that's only for file backed VMRs
295 * undergoing page removal, which isn't the caller of copy_pages. */
296 if (pte_is_mapped(pte)) {
297 /* TODO: check for jumbos */
298 if (upage_alloc(new_p, &pp, 0))
300 memcpy(page2kva(pp), KADDR(pte_get_paddr(pte)), PGSIZE);
301 if (page_insert(new_p->env_pgdir, pp, va, pte_get_settings(pte))) {
305 } else if (pte_is_paged_out(pte)) {
306 /* TODO: (SWAP) will need to either make a copy or CoW/refcnt the
307 * backend store. For now, this PTE will be the same as the
309 panic("Swapping not supported!");
311 panic("Weird PTE %p in %s!", pte_print(pte), __FUNCTION__);
315 return env_user_mem_walk(p, (void*)va_start, va_end - va_start, ©_page,
319 static int fill_vmr(struct proc *p, struct proc *new_p, struct vm_region *vmr)
323 if ((!vmr->vm_file) || (vmr->vm_flags & MAP_PRIVATE)) {
324 assert(!(vmr->vm_flags & MAP_SHARED));
325 ret = copy_pages(p, new_p, vmr->vm_base, vmr->vm_end);
327 /* non-private file, i.e. page cacheable. we have to honor MAP_LOCKED,
328 * (but we might be able to ignore MAP_POPULATE). */
329 if (vmr->vm_flags & MAP_LOCKED) {
330 /* need to keep the file alive in case we unlock/block */
331 kref_get(&vmr->vm_file->f_kref, 1);
332 /* math is a bit nasty if vm_base isn't page aligned */
333 assert(!PGOFF(vmr->vm_base));
334 ret = populate_pm_va(new_p, vmr->vm_base,
335 (vmr->vm_end - vmr->vm_base) >> PGSHIFT,
336 vmr->vm_prot, vmr->vm_file->f_mapping,
337 vmr->vm_foff, vmr->vm_flags,
338 vmr->vm_prot & PROT_EXEC);
339 kref_put(&vmr->vm_file->f_kref);
345 /* This will make new_p have the same VMRs as p, and it will make sure all
346 * physical pages are copied over, with the exception of MAP_SHARED files.
347 * MAP_SHARED files that are also MAP_LOCKED will be attached to the process -
348 * presumably they are in the page cache since the parent locked them. This is
351 * This is used by fork().
353 * Note that if you are working on a VMR that is a file, you'll want to be
354 * careful about how it is mapped (SHARED, PRIVATE, etc). */
355 int duplicate_vmrs(struct proc *p, struct proc *new_p)
358 struct vm_region *vmr, *vm_i;
360 TAILQ_FOREACH(vm_i, &p->vm_regions, vm_link) {
361 vmr = kmem_cache_alloc(vmr_kcache, 0);
364 vmr->vm_proc = new_p;
365 vmr->vm_base = vm_i->vm_base;
366 vmr->vm_end = vm_i->vm_end;
367 vmr->vm_prot = vm_i->vm_prot;
368 vmr->vm_flags = vm_i->vm_flags;
369 vmr->vm_file = vm_i->vm_file;
370 vmr->vm_foff = vm_i->vm_foff;
372 kref_get(&vm_i->vm_file->f_kref, 1);
373 pm_add_vmr(file2pm(vm_i->vm_file), vmr);
375 ret = fill_vmr(p, new_p, vmr);
378 pm_remove_vmr(file2pm(vm_i->vm_file), vmr);
379 kref_put(&vm_i->vm_file->f_kref);
381 kmem_cache_free(vmr_kcache, vm_i);
384 TAILQ_INSERT_TAIL(&new_p->vm_regions, vmr, vm_link);
389 void print_vmrs(struct proc *p)
392 struct vm_region *vmr;
393 printk("VM Regions for proc %d\n", p->pid);
400 TAILQ_FOREACH(vmr, &p->vm_regions, vm_link)
401 printk("%02d: (%p - %p): 0x%08x, 0x%08x, %p, %p\n", count++,
402 vmr->vm_base, vmr->vm_end, vmr->vm_prot, vmr->vm_flags,
403 vmr->vm_file, vmr->vm_foff);
406 void enumerate_vmrs(struct proc *p,
407 void (*func)(struct vm_region *vmr, void *opaque),
410 struct vm_region *vmr;
412 spin_lock(&p->vmr_lock);
413 TAILQ_FOREACH(vmr, &p->vm_regions, vm_link)
415 spin_unlock(&p->vmr_lock);
418 /* Error values aren't quite comprehensive - check man mmap() once we do better
421 * The mmap call's offset is in units of PGSIZE (like Linux's mmap2()), but
422 * internally, the offset is tracked in bytes. The reason for the PGSIZE is for
423 * 32bit apps to enumerate large files, but a full 64bit system won't need that.
424 * We track things internally in bytes since that is how file pointers work, vmr
425 * bases and ends, and similar math. While it's not a hard change, there's no
426 * need for it, and ideally we'll be a fully 64bit system before we deal with
427 * files that large. */
428 void *mmap(struct proc *p, uintptr_t addr, size_t len, int prot, int flags,
429 int fd, size_t offset)
431 struct file *file = NULL;
433 printd("mmap(addr %x, len %x, prot %x, flags %x, fd %x, off %x)\n", addr,
434 len, prot, flags, fd, offset);
435 if (fd >= 0 && (flags & MAP_ANON)) {
444 file = get_file_from_fd(&p->open_files, fd);
450 /* Check for overflow. This helps do_mmap and populate_va, among others. */
451 if (offset + len < offset) {
455 /* If they don't care where to put it, we'll start looking after the break.
456 * We could just have userspace handle this (in glibc's mmap), so we don't
457 * need to know about BRK_END, but this will work for now (and may avoid
458 * bugs). Note that this limits mmap(0) a bit. Keep this in sync with
459 * __do_mmap()'s check. (Both are necessary). */
462 /* Still need to enforce this: */
463 addr = MAX(addr, MMAP_LOWEST_VA);
464 /* Need to check addr + len, after we do our addr adjustments */
465 if ((addr + len > UMAPTOP) || (PGOFF(addr))) {
469 void *result = do_mmap(p, addr, len, prot, flags, file, offset);
471 kref_put(&file->f_kref);
475 /* Helper: returns TRUE if the VMR is allowed to access the file with prot.
476 * This is a bit ghetto still: messes with the file mode and assumes it can walk
477 * the dentry/inode paths without locking. It also ignores the CoW stuff we'll
478 * need to do eventually. */
479 static bool check_file_perms(struct vm_region *vmr, struct file *file, int prot)
482 if (prot & PROT_READ) {
483 if (check_perms(file->f_dentry->d_inode, S_IRUSR))
486 if (prot & PROT_WRITE) {
487 /* if vmr maps a file as MAP_SHARED, then we need to make sure the
488 * protection change is in compliance with the open mode of the
490 if (vmr->vm_flags & MAP_SHARED) {
491 if (!(file->f_mode & S_IWUSR)) {
492 /* at this point, we have a file opened in the wrong mode,
493 * but we may be allowed to access it still. */
494 if (check_perms(file->f_dentry->d_inode, S_IWUSR)) {
497 /* it is okay, though we need to change the file mode. (note
498 * the lack of a lock/protection (TODO) */
499 file->f_mode |= S_IWUSR;
502 } else { /* PRIVATE mapping */
503 /* TODO: we want a CoW mapping (like we want in handle_page_fault()),
504 * since there is a concern of a process having the page already
505 * mapped in to a file it does not have permissions to, and then
506 * mprotecting it so it can access it. So we can't just change
507 * the prot, and we don't know yet if a page is mapped in. To
508 * handle this, we ought to sort out the CoW bit, and then this
509 * will be easy. Til then, just do a permissions check. If we
510 * start having weird issues with libc overwriting itself (since
511 * procs mprotect that W), then change this. */
512 if (check_perms(file->f_dentry->d_inode, S_IWUSR))
517 out_error: /* for debugging */
518 printk("[kernel] mmap perm check failed for %s for access %d\n",
519 file_name(file), prot);
523 /* Helper, maps in page at addr, but only if nothing is mapped there. Returns
524 * 0 on success. If this is called by non-PM code, we'll store your ref in the
526 static int map_page_at_addr(struct proc *p, struct page *page, uintptr_t addr,
530 spin_lock(&p->pte_lock); /* walking and changing PTEs */
531 /* find offending PTE (prob don't read this in). This might alloc an
532 * intermediate page table page. */
533 pte = pgdir_walk(p->env_pgdir, (void*)addr, TRUE);
534 if (!pte_walk_okay(pte)) {
535 spin_unlock(&p->pte_lock);
538 /* a spurious, valid PF is possible due to a legit race: the page might have
539 * been faulted in by another core already (and raced on the memory lock),
540 * in which case we should just return. */
541 if (pte_is_present(pte)) {
542 spin_unlock(&p->pte_lock);
543 /* non-PM callers expect us to eat the ref if we succeed. */
544 if (!page_is_pagemap(page))
548 if (pte_is_mapped(pte)) {
549 /* we're clobbering an old entry. if we're just updating the prot, then
550 * it's no big deal. o/w, there might be an issue. */
551 if (page2pa(page) != pte_get_paddr(pte)) {
552 warn_once("Clobbered a PTE mapping (%p -> %p)\n", pte_print(pte),
553 page2pa(page) | prot);
555 if (!page_is_pagemap(pa2page(pte_get_paddr(pte))))
556 page_decref(pa2page(pte_get_paddr(pte)));
558 /* preserve the dirty bit - pm removal could be looking concurrently */
559 prot |= (pte_is_dirty(pte) ? PTE_D : 0);
560 /* We have a ref to page, which we are storing in the PTE */
561 pte_write(pte, page2pa(page), prot);
562 spin_unlock(&p->pte_lock);
566 /* Helper: copies *pp's contents to a new page, replacing your page pointer. If
567 * this succeeds, you'll have a non-PM page, which matters for how you put it.*/
568 static int __copy_and_swap_pmpg(struct proc *p, struct page **pp)
570 struct page *new_page, *old_page = *pp;
571 if (upage_alloc(p, &new_page, FALSE))
573 memcpy(page2kva(new_page), page2kva(old_page), PGSIZE);
574 pm_put_page(old_page);
579 /* Hold the VMR lock when you call this - it'll assume the entire VA range is
580 * mappable, which isn't true if there are concurrent changes to the VMRs. */
581 static int populate_anon_va(struct proc *p, uintptr_t va, unsigned long nr_pgs,
586 for (long i = 0; i < nr_pgs; i++) {
587 if (upage_alloc(p, &page, TRUE))
589 /* could imagine doing a memwalk instead of a for loop */
590 ret = map_page_at_addr(p, page, va + i * PGSIZE, pte_prot);
599 /* This will periodically unlock the vmr lock. */
600 static int populate_pm_va(struct proc *p, uintptr_t va, unsigned long nr_pgs,
601 int pte_prot, struct page_map *pm, size_t offset,
602 int flags, bool exec)
605 unsigned long pm_idx0 = offset >> PGSHIFT;
606 int vmr_history = ACCESS_ONCE(p->vmr_history);
609 /* locking rules: start the loop holding the vmr lock, enter and exit the
610 * entire func holding the lock. */
611 for (long i = 0; i < nr_pgs; i++) {
612 ret = pm_load_page_nowait(pm, pm_idx0 + i, &page);
616 spin_unlock(&p->vmr_lock);
617 /* might block here, can't hold the spinlock */
618 ret = pm_load_page(pm, pm_idx0 + i, &page);
619 spin_lock(&p->vmr_lock);
622 /* while we were sleeping, the VMRs could have changed on us. */
623 if (vmr_history != ACCESS_ONCE(p->vmr_history)) {
625 printk("[kernel] FYI: VMR changed during populate\n");
629 if (flags & MAP_PRIVATE) {
630 ret = __copy_and_swap_pmpg(p, &page);
636 /* if this is an executable page, we might have to flush the
637 * instruction cache if our HW requires it.
638 * TODO: is this still needed? andrew put this in a while ago*/
640 icache_flush_page(0, page2kva(page));
641 ret = map_page_at_addr(p, page, va + i * PGSIZE, pte_prot);
642 if (page_is_pagemap(page))
650 void *do_mmap(struct proc *p, uintptr_t addr, size_t len, int prot, int flags,
651 struct file *file, size_t offset)
653 len = ROUNDUP(len, PGSIZE);
654 struct vm_region *vmr, *vmr_temp;
656 /* read/write vmr lock (will change the tree) */
657 spin_lock(&p->vmr_lock);
659 /* Sanity check, for callers that bypass mmap(). We want addr for anon
660 * memory to start above the break limit (BRK_END), but not 0. Keep this in
661 * sync with BRK_END in mmap(). */
664 assert(!PGOFF(offset));
666 /* MCPs will need their code and data pinned. This check will start to fail
667 * after uthread_slim_init(), at which point userspace should have enough
668 * control over its mmaps (i.e. no longer done by LD or load_elf) that it
669 * can ask for pinned and populated pages. Except for dl_opens(). */
670 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
671 if (file && (atomic_read(&vcpd->flags) & VC_SCP_NOVCCTX))
672 flags |= MAP_POPULATE | MAP_LOCKED;
673 /* Need to make sure nothing is in our way when we want a FIXED location.
674 * We just need to split on the end points (if they exist), and then remove
675 * everything in between. __do_munmap() will do this. Careful, this means
676 * an mmap can be an implied munmap() (not my call...). */
677 if (flags & MAP_FIXED)
678 __do_munmap(p, addr, len);
679 vmr = create_vmr(p, addr, len);
681 printk("[kernel] do_mmap() aborted for %p + %d!\n", addr, len);
683 spin_unlock(&p->vmr_lock);
688 vmr->vm_flags = flags;
689 vmr->vm_foff = offset;
691 if (!check_file_perms(vmr, file, prot)) {
692 assert(!vmr->vm_file);
695 spin_unlock(&p->vmr_lock);
698 /* TODO: consider locking the file while checking (not as manadatory as
699 * in handle_page_fault() */
700 if (nr_pages(offset + len) > nr_pages(file->f_dentry->d_inode->i_size)) {
701 /* We're allowing them to set up the VMR, though if they attempt to
702 * fault in any pages beyond the file's limit, they'll fail. Since
703 * they might not access the region, we need to make sure POPULATE
704 * is off. FYI, 64 bit glibc shared libs map in an extra 2MB of
705 * unaligned space between their RO and RW sections, but then
706 * immediately mprotect it to PROT_NONE. */
707 flags &= ~MAP_POPULATE;
709 /* Prep the FS to make sure it can mmap the file. Slightly weird
710 * semantics: if we fail and had munmapped the space, they will have a
711 * hole in their VM now. */
712 if (file->f_op->mmap(file, vmr)) {
713 assert(!vmr->vm_file);
715 set_errno(EACCES); /* not quite */
716 spin_unlock(&p->vmr_lock);
719 kref_get(&file->f_kref, 1);
720 pm_add_vmr(file2pm(file), vmr);
723 vmr = merge_me(vmr); /* attempts to merge with neighbors */
725 if (flags & MAP_POPULATE && prot != PROT_NONE) {
726 int pte_prot = (prot & PROT_WRITE) ? PTE_USER_RW :
727 (prot & (PROT_READ|PROT_EXEC)) ? PTE_USER_RO : 0;
728 unsigned long nr_pgs = len >> PGSHIFT;
731 ret = populate_anon_va(p, addr, nr_pgs, pte_prot);
733 /* Note: this will unlock if it blocks. our refcnt on the file
734 * keeps the pm alive when we unlock */
735 ret = populate_pm_va(p, addr, nr_pgs, pte_prot, file->f_mapping,
736 offset, flags, prot & PROT_EXEC);
738 if (ret == -ENOMEM) {
739 spin_unlock(&p->vmr_lock);
740 printk("[kernel] ENOMEM, killing %d\n", p->pid);
742 return MAP_FAILED; /* will never make it back to userspace */
745 spin_unlock(&p->vmr_lock);
747 profiler_notify_mmap(p, addr, len, prot, flags, file, offset);
752 int mprotect(struct proc *p, uintptr_t addr, size_t len, int prot)
754 printd("mprotect: (addr %p, len %p, prot 0x%x)\n", addr, len, prot);
757 if ((addr % PGSIZE) || (addr < MMAP_LOWEST_VA)) {
761 uintptr_t end = ROUNDUP(addr + len, PGSIZE);
762 if (end > UMAPTOP || addr > end) {
766 /* read/write lock, will probably change the tree and settings */
767 spin_lock(&p->vmr_lock);
769 int ret = __do_mprotect(p, addr, len, prot);
770 spin_unlock(&p->vmr_lock);
774 /* This does not care if the region is not mapped. POSIX says you should return
775 * ENOMEM if any part of it is unmapped. Can do this later if we care, based on
776 * the VMRs, not the actual page residency. */
777 int __do_mprotect(struct proc *p, uintptr_t addr, size_t len, int prot)
779 struct vm_region *vmr, *next_vmr;
781 bool shootdown_needed = FALSE;
782 int pte_prot = (prot & PROT_WRITE) ? PTE_USER_RW :
783 (prot & (PROT_READ|PROT_EXEC)) ? PTE_USER_RO : PTE_NONE;
784 /* TODO: this is aggressively splitting, when we might not need to if the
785 * prots are the same as the previous. Plus, there are three excessive
786 * scans. Finally, we might be able to merge when we are done. */
787 isolate_vmrs(p, addr, len);
788 vmr = find_first_vmr(p, addr);
789 while (vmr && vmr->vm_base < addr + len) {
790 if (vmr->vm_prot == prot)
792 if (vmr->vm_file && !check_file_perms(vmr, vmr->vm_file, prot)) {
797 spin_lock(&p->pte_lock); /* walking and changing PTEs */
798 /* TODO: use a memwalk. At a minimum, we need to change every existing
799 * PTE that won't trigger a PF (meaning, present PTEs) to have the new
800 * prot. The others will fault on access, and we'll change the PTE
801 * then. In the off chance we have a mapped but not present PTE, we
802 * might as well change it too, since we're already here. */
803 for (uintptr_t va = vmr->vm_base; va < vmr->vm_end; va += PGSIZE) {
804 pte = pgdir_walk(p->env_pgdir, (void*)va, 0);
805 if (pte_walk_okay(pte) && pte_is_mapped(pte)) {
806 pte_replace_perm(pte, pte_prot);
807 shootdown_needed = TRUE;
810 spin_unlock(&p->pte_lock);
812 next_vmr = TAILQ_NEXT(vmr, vm_link);
815 if (shootdown_needed)
816 proc_tlbshootdown(p, addr, addr + len);
820 int munmap(struct proc *p, uintptr_t addr, size_t len)
822 printd("munmap(addr %x, len %x)\n", addr, len);
825 len = ROUNDUP(len, PGSIZE);
827 if ((addr % PGSIZE) || (addr < MMAP_LOWEST_VA)) {
831 uintptr_t end = ROUNDUP(addr + len, PGSIZE);
832 if (end > UMAPTOP || addr > end) {
836 /* read/write: changing the vmrs (trees, properties, and whatnot) */
837 spin_lock(&p->vmr_lock);
839 int ret = __do_munmap(p, addr, len);
840 spin_unlock(&p->vmr_lock);
844 static int __munmap_mark_not_present(struct proc *p, pte_t pte, void *va,
847 bool *shootdown_needed = (bool*)arg;
848 /* could put in some checks here for !P and also !0 */
849 if (!pte_is_present(pte)) /* unmapped (== 0) *ptes are also not PTE_P */
851 pte_clear_present(pte);
852 *shootdown_needed = TRUE;
856 /* If our page is actually in the PM, we don't do anything. All a page map
857 * really needs is for our VMR to no longer track it (vmr being in the pm's
858 * list) and to not point at its pages (mark it 0, dude).
860 * But private mappings mess with that a bit. Luckily, we can tell by looking
861 * at a page whether the specific page is in the PM or not. If it isn't, we
862 * still need to free our "VMR local" copy.
864 * For pages in a PM, we're racing with PM removers. Both of us sync with the
865 * mm lock, so once we hold the lock, it's a matter of whether or not the PTE is
866 * 0 or not. If it isn't, then we're still okay to look at the page. Consider
867 * the PTE a weak ref on the page. So long as you hold the mm lock, you can
868 * look at the PTE and know the page isn't being freed. */
869 static int __vmr_free_pgs(struct proc *p, pte_t pte, void *va, void *arg)
872 if (pte_is_unmapped(pte))
874 page = pa2page(pte_get_paddr(pte));
876 if (!page_is_pagemap(page))
881 int __do_munmap(struct proc *p, uintptr_t addr, size_t len)
883 struct vm_region *vmr, *next_vmr, *first_vmr;
884 bool shootdown_needed = FALSE;
886 /* TODO: this will be a bit slow, since we end up doing three linear
887 * searches (two in isolate, one in find_first). */
888 isolate_vmrs(p, addr, len);
889 first_vmr = find_first_vmr(p, addr);
891 spin_lock(&p->pte_lock); /* changing PTEs */
892 while (vmr && vmr->vm_base < addr + len) {
893 env_user_mem_walk(p, (void*)vmr->vm_base, vmr->vm_end - vmr->vm_base,
894 __munmap_mark_not_present, &shootdown_needed);
895 vmr = TAILQ_NEXT(vmr, vm_link);
897 spin_unlock(&p->pte_lock);
898 /* we haven't freed the pages yet; still using the PTEs to store the them.
899 * There should be no races with inserts/faults, since we still hold the mm
900 * lock since the previous CB. */
901 if (shootdown_needed)
902 proc_tlbshootdown(p, addr, addr + len);
904 while (vmr && vmr->vm_base < addr + len) {
905 /* there is rarely more than one VMR in this loop. o/w, we'll need to
906 * gather up the vmrs and destroy outside the pte_lock. */
907 spin_lock(&p->pte_lock); /* changing PTEs */
908 env_user_mem_walk(p, (void*)vmr->vm_base, vmr->vm_end - vmr->vm_base,
910 spin_unlock(&p->pte_lock);
911 next_vmr = TAILQ_NEXT(vmr, vm_link);
918 /* Helper - drop the page differently based on where it is from */
919 static void __put_page(struct page *page)
921 if (page_is_pagemap(page))
927 static int __hpf_load_page(struct proc *p, struct page_map *pm,
928 unsigned long idx, struct page **page, bool first)
931 int coreid = core_id();
932 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
933 bool wake_scp = FALSE;
934 spin_lock(&p->proc_lock);
936 case (PROC_RUNNING_S):
938 __proc_set_state(p, PROC_WAITING);
939 /* it's possible for HPF to loop a few times; we can only save the
940 * first time, o/w we could clobber. */
942 __proc_save_context_s(p);
943 __proc_save_fpu_s(p);
944 /* We clear the owner, since userspace doesn't run here
945 * anymore, but we won't abandon since the fault handler
946 * still runs in our process. */
947 clear_owning_proc(coreid);
949 /* other notes: we don't currently need to tell the ksched
950 * we switched from running to waiting, though we probably
951 * will later for more generic scheds. */
953 case (PROC_RUNNABLE_M):
954 case (PROC_RUNNING_M):
955 spin_unlock(&p->proc_lock);
956 return -EAGAIN; /* will get reflected back to userspace */
958 case (PROC_DYING_ABORT):
959 spin_unlock(&p->proc_lock);
962 /* shouldn't have any waitings, under the current yield style. if
963 * this becomes an issue, we can branch on is_mcp(). */
964 printk("HPF unexpectecd state(%s)", procstate2str(p->state));
965 spin_unlock(&p->proc_lock);
968 spin_unlock(&p->proc_lock);
969 ret = pm_load_page(pm, idx, page);
973 printk("load failed with ret %d\n", ret);
976 /* need to put our old ref, next time around HPF will get another. */
981 /* Returns 0 on success, or an appropriate -error code.
983 * Notes: if your TLB caches negative results, you'll need to flush the
984 * appropriate tlb entry. Also, you could have a weird race where a present PTE
985 * faulted for a different reason (was mprotected on another core), and the
986 * shootdown is on its way. Userspace should have waited for the mprotect to
987 * return before trying to write (or whatever), so we don't care and will fault
989 static int __hpf(struct proc *p, uintptr_t va, int prot, bool file_ok)
991 struct vm_region *vmr;
993 unsigned int f_idx; /* index of the missing page in the file */
996 va = ROUNDDOWN(va,PGSIZE);
999 /* read access to the VMRs TODO: RCU */
1000 spin_lock(&p->vmr_lock);
1001 /* Check the vmr's protection */
1002 vmr = find_vmr(p, va);
1003 if (!vmr) { /* not mapped at all */
1004 printd("fault: %p not mapped\n", va);
1008 if (!(vmr->vm_prot & prot)) { /* wrong prots for this vmr */
1012 if (!vmr->vm_file) {
1013 /* No file - just want anonymous memory */
1014 if (upage_alloc(p, &a_page, TRUE)) {
1021 /* If this fails, either something got screwed up with the VMR, or the
1022 * permissions changed after mmap/mprotect. Either way, I want to know
1023 * (though it's not critical). */
1024 if (!check_file_perms(vmr, vmr->vm_file, prot))
1025 printk("[kernel] possible issue with VMR prots on file %s!\n",
1026 file_name(vmr->vm_file));
1027 /* Load the file's page in the page cache.
1028 * TODO: (BLK) Note, we are holding the mem lock! We need to rewrite
1029 * this stuff so we aren't hold the lock as excessively as we are, and
1030 * such that we can block and resume later. */
1031 assert(!PGOFF(va - vmr->vm_base + vmr->vm_foff));
1032 f_idx = (va - vmr->vm_base + vmr->vm_foff) >> PGSHIFT;
1033 /* TODO: need some sort of lock on the file to deal with someone
1034 * concurrently shrinking it. Adding 1 to f_idx, since it is
1036 if (f_idx + 1 > nr_pages(vmr->vm_file->f_dentry->d_inode->i_size)) {
1037 /* We're asking for pages that don't exist in the file */
1038 /* TODO: unlock the file */
1039 ret = -ESPIPE; /* linux sends a SIGBUS at access time */
1042 ret = pm_load_page_nowait(vmr->vm_file->f_mapping, f_idx, &a_page);
1046 /* keep the file alive after we unlock */
1047 kref_get(&vmr->vm_file->f_kref, 1);
1048 spin_unlock(&p->vmr_lock);
1049 ret = __hpf_load_page(p, vmr->vm_file->f_mapping, f_idx, &a_page,
1052 kref_put(&vmr->vm_file->f_kref);
1057 /* If we want a private map, we'll preemptively give you a new page. We
1058 * used to just care if it was private and writable, but were running
1059 * into issues with libc changing its mapping (map private, then
1060 * mprotect to writable...) In the future, we want to CoW this anyway,
1061 * so it's not a big deal. */
1062 if ((vmr->vm_flags & MAP_PRIVATE)) {
1063 ret = __copy_and_swap_pmpg(p, &a_page);
1067 /* if this is an executable page, we might have to flush the instruction
1068 * cache if our HW requires it. */
1069 if (vmr->vm_prot & PROT_EXEC)
1070 icache_flush_page((void*)va, page2kva(a_page));
1072 /* update the page table TODO: careful with MAP_PRIVATE etc. might do this
1073 * separately (file, no file) */
1074 int pte_prot = (vmr->vm_prot & PROT_WRITE) ? PTE_USER_RW :
1075 (vmr->vm_prot & (PROT_READ|PROT_EXEC)) ? PTE_USER_RO : 0;
1076 ret = map_page_at_addr(p, a_page, va, pte_prot);
1078 printd("map_page_at for %p fails with %d\n", va, ret);
1080 /* fall through, even for errors */
1082 /* the VMR's existence in the PM (via the mmap) allows us to have PTE point
1083 * to a_page without it magically being reallocated. For non-PM memory
1084 * (anon memory or private pages) we transferred the ref to the PTE. */
1085 if (page_is_pagemap(a_page))
1086 pm_put_page(a_page);
1088 spin_unlock(&p->vmr_lock);
1092 int handle_page_fault(struct proc *p, uintptr_t va, int prot)
1094 return __hpf(p, va, prot, TRUE);
1097 int handle_page_fault_nofile(struct proc *p, uintptr_t va, int prot)
1099 return __hpf(p, va, prot, FALSE);
1102 /* Attempts to populate the pages, as if there was a page faults. Bails on
1103 * errors, and returns the number of pages populated. */
1104 unsigned long populate_va(struct proc *p, uintptr_t va, unsigned long nr_pgs)
1106 struct vm_region *vmr, vmr_copy;
1107 unsigned long nr_pgs_this_vmr;
1108 unsigned long nr_filled = 0;
1113 /* we can screw around with ways to limit the find_vmr calls (can do the
1114 * next in line if we didn't unlock, etc., but i don't expect us to do this
1115 * for more than a single VMR in most cases. */
1116 spin_lock(&p->vmr_lock);
1118 vmr = find_vmr(p, va);
1121 if (vmr->vm_prot == PROT_NONE)
1123 pte_prot = (vmr->vm_prot & PROT_WRITE) ? PTE_USER_RW :
1124 (vmr->vm_prot & (PROT_READ|PROT_EXEC)) ? PTE_USER_RO : 0;
1125 nr_pgs_this_vmr = MIN(nr_pgs, (vmr->vm_end - va) >> PGSHIFT);
1126 if (!vmr->vm_file) {
1127 if (populate_anon_va(p, va, nr_pgs_this_vmr, pte_prot)) {
1128 /* on any error, we can just bail. we might be underestimating
1133 /* need to keep the file alive in case we unlock/block */
1134 kref_get(&vmr->vm_file->f_kref, 1);
1135 /* Regarding foff + (va - base): va - base < len, and foff + len
1136 * does not over flow */
1137 ret = populate_pm_va(p, va, nr_pgs_this_vmr, pte_prot,
1138 vmr->vm_file->f_mapping,
1139 vmr->vm_foff + (va - vmr->vm_base),
1140 vmr->vm_flags, vmr->vm_prot & PROT_EXEC);
1141 kref_put(&vmr->vm_file->f_kref);
1143 /* we might have failed if the underlying file doesn't cover the
1144 * mmap window, depending on how we'll deal with truncation. */
1148 nr_filled += nr_pgs_this_vmr;
1149 va += nr_pgs_this_vmr << PGSHIFT;
1150 nr_pgs -= nr_pgs_this_vmr;
1152 spin_unlock(&p->vmr_lock);
1156 /* Kernel Dynamic Memory Mappings */
1157 uintptr_t dyn_vmap_llim = KERN_DYN_TOP;
1158 spinlock_t dyn_vmap_lock = SPINLOCK_INITIALIZER;
1160 /* Reserve space in the kernel dynamic memory map area */
1161 uintptr_t get_vmap_segment(unsigned long num_pages)
1164 spin_lock(&dyn_vmap_lock);
1165 retval = dyn_vmap_llim - num_pages * PGSIZE;
1166 if ((retval > ULIM) && (retval < KERN_DYN_TOP)) {
1167 dyn_vmap_llim = retval;
1169 warn("[kernel] dynamic mapping failed!");
1172 spin_unlock(&dyn_vmap_lock);
1176 /* Give up your space. Note this isn't supported yet */
1177 uintptr_t put_vmap_segment(uintptr_t vaddr, unsigned long num_pages)
1179 /* TODO: use vmem regions for adjustable vmap segments */
1180 warn("Not implemented, leaking vmem space.\n");
1184 /* Map a virtual address chunk to physical addresses. Make sure you got a vmap
1185 * segment before actually trying to do the mapping.
1187 * Careful with more than one 'page', since it will assume your physical pages
1188 * are also contiguous. Most callers will only use one page.
1190 * Finally, note that this does not care whether or not there are real pages
1191 * being mapped, and will not attempt to incref your page (if there is such a
1192 * thing). Handle your own refcnting for pages. */
1193 int map_vmap_segment(uintptr_t vaddr, uintptr_t paddr, unsigned long num_pages,
1196 /* For now, we only handle the root pgdir, and not any of the other ones
1197 * (like for processes). To do so, we'll need to insert into every pgdir,
1198 * and send tlb shootdowns to those that are active (which we don't track
1203 /* TODO: (MM) you should lock on boot pgdir modifications. A vm region lock
1204 * isn't enough, since there might be a race on outer levels of page tables.
1205 * For now, we'll just use the dyn_vmap_lock (which technically works). */
1206 spin_lock(&dyn_vmap_lock);
1211 for (int i = 0; i < num_pages; i++) {
1212 pte = pgdir_walk(boot_pgdir, (void*)(vaddr + i * PGSIZE), 1);
1213 if (!pte_walk_okay(pte)) {
1214 spin_unlock(&dyn_vmap_lock);
1217 /* You probably should have unmapped first */
1218 if (pte_is_mapped(pte))
1219 warn("Existing PTE value %p\n", pte_print(pte));
1220 pte_write(pte, paddr + i * PGSIZE, perm);
1222 spin_unlock(&dyn_vmap_lock);
1226 /* Unmaps / 0's the PTEs of a chunk of vaddr space */
1227 int unmap_vmap_segment(uintptr_t vaddr, unsigned long num_pages)
1229 /* Not a big deal - won't need this til we do something with kthreads */
1230 warn("Incomplete, don't call this yet.");
1231 spin_lock(&dyn_vmap_lock);
1232 /* TODO: For all pgdirs */
1234 for (int i = 0; i < num_pages; i++) {
1235 pte = pgdir_walk(boot_pgdir, (void*)(vaddr + i * PGSIZE), 1);
1236 if (pte_walk_okay(pte))
1239 /* TODO: TLB shootdown. Also note that the global flag is set on the PTE
1240 * (for x86 for now), which requires a global shootdown. bigger issue is
1241 * the TLB shootdowns for multiple pgdirs. We'll need to remove from every
1242 * pgdir, and send tlb shootdowns to those that are active (which we don't
1244 spin_unlock(&dyn_vmap_lock);
1248 /* This can handle unaligned paddrs */
1249 static uintptr_t vmap_pmem_flags(uintptr_t paddr, size_t nr_bytes, int flags)
1252 unsigned long nr_pages;
1253 assert(nr_bytes && paddr);
1254 nr_bytes += PGOFF(paddr);
1255 nr_pages = ROUNDUP(nr_bytes, PGSIZE) >> PGSHIFT;
1256 vaddr = get_vmap_segment(nr_pages);
1258 warn("Unable to get a vmap segment"); /* probably a bug */
1261 /* it's not strictly necessary to drop paddr's pgoff, but it might save some
1262 * vmap heartache in the future. */
1263 if (map_vmap_segment(vaddr, PG_ADDR(paddr), nr_pages,
1264 PTE_KERN_RW | flags)) {
1265 warn("Unable to map a vmap segment"); /* probably a bug */
1268 return vaddr + PGOFF(paddr);
1271 uintptr_t vmap_pmem(uintptr_t paddr, size_t nr_bytes)
1273 return vmap_pmem_flags(paddr, nr_bytes, 0);
1276 uintptr_t vmap_pmem_nocache(uintptr_t paddr, size_t nr_bytes)
1278 return vmap_pmem_flags(paddr, nr_bytes, PTE_NOCACHE);
1281 uintptr_t vmap_pmem_writecomb(uintptr_t paddr, size_t nr_bytes)
1283 return vmap_pmem_flags(paddr, nr_bytes, PTE_WRITECOMB);
1286 int vunmap_vmem(uintptr_t vaddr, size_t nr_bytes)
1288 unsigned long nr_pages = ROUNDUP(nr_bytes, PGSIZE) >> PGSHIFT;
1289 unmap_vmap_segment(vaddr, nr_pages);
1290 put_vmap_segment(vaddr, nr_pages);