1 /* Copyright (c) 2009,13 The Regents of the University of California
2 * Barret Rhoden <brho@cs.berkeley.edu>
3 * See LICENSE for details.
5 * Arch independent physical memory and page table management.
7 * For page allocation, check out the family of page_alloc files. */
23 #include <multiboot.h>
27 physaddr_t max_pmem = 0; /* Total amount of physical memory (bytes) */
28 physaddr_t max_paddr = 0; /* Maximum addressable physical address */
29 size_t max_nr_pages = 0; /* Number of addressable physical memory pages */
30 struct page *pages = 0;
31 struct multiboot_info *multiboot_kaddr = 0;
32 uintptr_t boot_freemem = 0;
33 uintptr_t boot_freelimit = 0;
35 static size_t sizeof_mboot_mmentry(struct multiboot_mmap_entry *entry)
37 /* Careful - len is a uint64 (need to cast down for 32 bit) */
38 return (size_t)(entry->len);
41 static void adjust_max_pmem(struct multiboot_mmap_entry *entry, void *data)
43 if (entry->type != MULTIBOOT_MEMORY_AVAILABLE)
45 /* Careful - addr + len is a uint64 (need to cast down for 32 bit) */
46 max_pmem = MAX(max_pmem, (size_t)(entry->addr + entry->len));
49 static void kpages_arena_init(void)
53 kpages_pg = arena_alloc(base_arena, PGSIZE, MEM_WAIT);
54 kpages_arena = arena_builder(kpages_pg, "kpages", PGSIZE, arena_alloc,
55 arena_free, base_arena, 8 * PGSIZE);
59 * @brief Initializes physical memory. Determines the pmem layout, sets up the
60 * base and kpages arenas, and turns on virtual memory/page tables.
62 * Regarding max_pmem vs max_paddr and max_nr_pages: max_pmem is the largest
63 * physical address that is in a FREE region. It includes RESERVED regions that
64 * are below this point. max_paddr is the largest physical address, <=
65 * max_pmem, that the KERNBASE mapping can map. It too may include reserved
66 * ranges. The 'pages' array will track all physical pages up to max_paddr.
67 * There are max_nr_pages of them. On 64 bit systems, max_pmem == max_paddr. */
68 void pmem_init(struct multiboot_info *mbi)
70 mboot_detect_memory(mbi);
71 mboot_print_mmap(mbi);
72 /* adjust the max memory based on the mmaps, since the old detection doesn't
73 * help much on 64 bit systems */
74 mboot_foreach_mmap(mbi, adjust_max_pmem, 0);
75 /* KERN_VMAP_TOP - KERNBASE is the max amount of virtual addresses we can
76 * use for the physical memory mapping (aka - the KERNBASE mapping).
77 * Should't be an issue on 64b, but is usually for 32 bit. */
78 max_paddr = MIN(max_pmem, KERN_VMAP_TOP - KERNBASE);
79 /* Note not all of this memory is free. */
80 max_nr_pages = max_paddr / PGSIZE;
81 printk("Max physical RAM (appx, bytes): %lu\n", max_pmem);
82 printk("Max addressable physical RAM (appx): %lu\n", max_paddr);
83 printk("Highest page number (including reserved): %lu\n", max_nr_pages);
84 /* We should init the page structs, but zeroing happens to work, since the
85 * sems are not irqsave. */
86 pages = (struct page*)boot_zalloc(max_nr_pages * sizeof(struct page),
89 /* kpages will use some of the basic slab caches. kmem_cache_init needs to
90 * not do memory allocations (which it doesn't, and it can base_alloc()). */
93 printk("Base arena total mem: %lu\n", arena_amt_total(base_arena));
96 static_assert(PROCINFO_NUM_PAGES*PGSIZE <= PTSIZE);
97 static_assert(PROCDATA_NUM_PAGES*PGSIZE <= PTSIZE);
100 static void set_largest_freezone(struct multiboot_mmap_entry *entry, void *data)
102 struct multiboot_mmap_entry **boot_zone =
103 (struct multiboot_mmap_entry**)data;
105 if (entry->type != MULTIBOOT_MEMORY_AVAILABLE)
107 if (!*boot_zone || (sizeof_mboot_mmentry(entry) >
108 sizeof_mboot_mmentry(*boot_zone)))
112 /* Initialize boot freemem and its limit.
114 * "end" is a symbol marking the end of the kernel. This covers anything linked
115 * in with the kernel (KFS, etc). However, 'end' is a kernel load address,
116 * which differs from kernbase addrs in 64 bit. We need to use the kernbase
117 * mapping for anything dynamic (because it could go beyond 1 GB).
119 * Ideally, we'll use the largest mmap zone, as reported by multiboot. If we
120 * don't have one (riscv), we'll just use the memory after the kernel.
122 * If we do have a zone, there is a chance we've already used some of it (for
123 * the kernel, etc). We'll use the lowest address in the zone that is
124 * greater than "end" (and adjust the limit accordingly). */
125 static void boot_alloc_init(void)
128 uintptr_t boot_zone_start, boot_zone_end;
129 uintptr_t end_kva = (uintptr_t)KBASEADDR(end);
130 struct multiboot_mmap_entry *boot_zone = 0;
132 /* Find our largest mmap_entry; that will set bootzone */
133 mboot_foreach_mmap(multiboot_kaddr, set_largest_freezone, &boot_zone);
135 boot_zone_start = (uintptr_t)KADDR(boot_zone->addr);
136 /* one issue for 32b is that the boot_zone_end could be beyond max_paddr
137 * and even wrap-around. Do the min check as a uint64_t. The result
138 * should be a safe, unwrapped 32/64b when cast to physaddr_t. */
139 boot_zone_end = (uintptr_t)KADDR(MIN(boot_zone->addr + boot_zone->len,
140 (uint64_t)max_paddr));
141 /* using KERNBASE (kva, btw) which covers the kernel and anything before
142 * it (like the stuff below EXTPHYSMEM on x86) */
143 if (regions_collide_unsafe(KERNBASE, end_kva,
144 boot_zone_start, boot_zone_end))
145 boot_freemem = end_kva;
147 boot_freemem = boot_zone_start;
148 boot_freelimit = boot_zone_end;
150 boot_freemem = end_kva;
151 boot_freelimit = max_paddr + KERNBASE;
153 printd("boot_zone: %p, paddr base: 0x%llx, paddr len: 0x%llx\n", boot_zone,
154 boot_zone ? boot_zone->addr : 0,
155 boot_zone ? boot_zone->len : 0);
156 printd("boot_freemem: %p, boot_freelimit %p\n", boot_freemem,
160 /* Low-level allocator, used before page_alloc is on. Returns size bytes,
161 * aligned to align (should be a power of 2). Retval is a kernbase addr. Will
162 * panic on failure. */
163 void *boot_alloc(size_t amt, size_t align)
169 boot_freemem = ROUNDUP(boot_freemem, align);
170 retval = boot_freemem;
171 if (boot_freemem + amt > boot_freelimit){
172 printk("boot_alloc: boot_freemem is 0x%x\n", boot_freemem);
173 printk("boot_alloc: amt is %d\n", amt);
174 printk("boot_freelimit is 0x%x\n", boot_freelimit);
175 printk("boot_freemem + amt is > boot_freelimit\n");
176 panic("Out of memory in boot alloc, you fool!\n");
179 printd("boot alloc from %p to %p\n", retval, boot_freemem);
180 /* multiboot info probably won't ever conflict with our boot alloc */
181 if (mboot_region_collides(multiboot_kaddr, retval, boot_freemem))
182 panic("boot allocation could clobber multiboot info! Get help!");
183 return (void*)retval;
186 void *boot_zalloc(size_t amt, size_t align)
188 /* boot_alloc panics on failure */
189 void *v = boot_alloc(amt, align);
195 * @brief Map the physical page 'pp' into the virtual address 'va' in page
198 * Map the physical page 'pp' at virtual address 'va'.
199 * The permissions (the low 12 bits) of the page table
200 * entry should be set to 'perm|PTE_P'.
203 * - If there is already a page mapped at 'va', it is page_remove()d.
204 * - If necessary, on demand, allocates a page table and inserts it into
206 * - This saves your refcnt in the pgdir (refcnts going away soon).
207 * - The TLB must be invalidated if a page was formerly present at 'va'.
208 * (this is handled in page_remove)
210 * No support for jumbos here. We will need to be careful when trying to
211 * insert regular pages into something that was already jumbo. We will
212 * also need to be careful with our overloading of the PTE_PS and
215 * @param[in] pgdir the page directory to insert the page into
216 * @param[in] pp a pointr to the page struct representing the
217 * physical page that should be inserted.
218 * @param[in] va the virtual address where the page should be
220 * @param[in] perm the permition bits with which to set up the
223 * @return ESUCCESS on success
224 * @return -ENOMEM if a page table could not be allocated
225 * into which the page should be inserted
228 int page_insert(pgdir_t pgdir, struct page *page, void *va, int perm)
230 pte_t pte = pgdir_walk(pgdir, va, 1);
231 if (!pte_walk_okay(pte))
233 /* Leftover from older times, but we no longer suppor this: */
234 assert(!pte_is_mapped(pte));
235 pte_write(pte, page2pa(page), perm);
240 * @brief Return the page mapped at virtual address 'va' in
241 * page directory 'pgdir'.
243 * If pte_store is not NULL, then we store in it the address
244 * of the pte for this page. This is used by page_remove
245 * but should not be used by other callers.
247 * For jumbos, right now this returns the first Page* in the 4MB range
249 * @param[in] pgdir the page directory from which we should do the lookup
250 * @param[in] va the virtual address of the page we are looking up
251 * @param[out] pte_store the address of the page table entry for the returned page
253 * @return PAGE the page mapped at virtual address 'va'
254 * @return NULL No mapping exists at virtual address 'va', or it's paged out
256 page_t *page_lookup(pgdir_t pgdir, void *va, pte_t *pte_store)
258 pte_t pte = pgdir_walk(pgdir, va, 0);
259 if (!pte_walk_okay(pte) || !pte_is_mapped(pte))
263 return pa2page(pte_get_paddr(pte));
267 * @brief Unmaps the physical page at virtual address 'va' in page directory
270 * If there is no physical page at that address, this function silently
274 * - The ref count on the physical page is decrement when the page is removed
275 * - The physical page is freed if the refcount reaches 0.
276 * - The pg table entry corresponding to 'va' is set to 0.
277 * (if such a PTE exists)
278 * - The TLB is invalidated if an entry is removes from the pg dir/pg table.
280 * This may be wonky wrt Jumbo pages and decref.
282 * @param pgdir the page directory from with the page sholuld be removed
283 * @param va the virtual address at which the page we are trying to
285 * TODO: consider deprecating this, or at least changing how it works with TLBs.
286 * Might want to have the caller need to manage the TLB. Also note it is used
287 * in env_user_mem_free, minus the walk. */
288 void page_remove(pgdir_t pgdir, void *va)
293 pte = pgdir_walk(pgdir,va,0);
294 if (!pte_walk_okay(pte) || pte_is_unmapped(pte))
297 if (pte_is_mapped(pte)) {
298 /* TODO: (TLB) need to do a shootdown, inval sucks. And might want to
299 * manage the TLB / free pages differently. (like by the caller).
300 * Careful about the proc/memory lock here. */
301 page = pa2page(pte_get_paddr(pte));
303 tlb_invalidate(pgdir, va);
305 } else if (pte_is_paged_out(pte)) {
306 /* TODO: (SWAP) need to free this from the swap */
307 panic("Swapping not supported!");
313 * @brief Invalidate a TLB entry, but only if the page tables being
314 * edited are the ones currently in use by the processor.
316 * TODO: (TLB) Need to sort this for cross core lovin'
318 * @param pgdir the page directory assocaited with the tlb entry
319 * we are trying to invalidate
320 * @param va the virtual address associated with the tlb entry
321 * we are trying to invalidate
323 void tlb_invalidate(pgdir_t pgdir, void *va)
325 // Flush the entry only if we're modifying the current address space.
326 // For now, there is only one address space, so always invalidate.
330 static void __tlb_global(uint32_t srcid, long a0, long a1, long a2)
335 /* Does a global TLB flush on all cores. */
336 void tlb_shootdown_global(void)
341 /* TODO: consider a helper for broadcast messages, though note that we're
342 * doing our flush immediately, which our caller expects from us before it
344 for (int i = 0; i < num_cores; i++) {
347 send_kernel_message(i, __tlb_global, 0, 0, 0, KMSG_IMMEDIATE);
351 /* Helper, returns true if any part of (start1, end1) is within (start2, end2).
352 * Equality of endpoints (like end1 == start2) is okay.
353 * Assumes no wrap-around. */
354 bool regions_collide_unsafe(uintptr_t start1, uintptr_t end1,
355 uintptr_t start2, uintptr_t end2)
357 if (start1 <= start2) {