1 /*
2 * Copyright (c) 2022 Intel Corporation
3 * SPDX-License-Identifier: Apache-2.0
4 */
5 #include <zephyr/kernel.h>
6 #include <zephyr/cache.h>
7 #include <zephyr/arch/xtensa/arch.h>
8 #include <zephyr/arch/xtensa/xtensa_mmu.h>
9 #include <zephyr/linker/linker-defs.h>
10 #include <zephyr/logging/log.h>
11 #include <zephyr/kernel/mm.h>
12 #include <zephyr/toolchain.h>
13 #include <xtensa/corebits.h>
14 #include <xtensa_mmu_priv.h>
15
16 #include <kernel_arch_func.h>
17 #include <mmu.h>
18
19 /* Skip TLB IPI when updating page tables.
20 * This allows us to send IPI only after the last
21 * changes of a series.
22 */
23 #define OPTION_NO_TLB_IPI BIT(0)
24
25 /* Level 1 contains page table entries
26 * necessary to map the page table itself.
27 */
28 #define XTENSA_L1_PAGE_TABLE_ENTRIES 1024U
29
30 /* Size of level 1 page table.
31 */
32 #define XTENSA_L1_PAGE_TABLE_SIZE (XTENSA_L1_PAGE_TABLE_ENTRIES * sizeof(uint32_t))
33
34 /* Level 2 contains page table entries
35 * necessary to map the page table itself.
36 */
37 #define XTENSA_L2_PAGE_TABLE_ENTRIES 1024U
38
39 /* Size of level 2 page table.
40 */
41 #define XTENSA_L2_PAGE_TABLE_SIZE (XTENSA_L2_PAGE_TABLE_ENTRIES * sizeof(uint32_t))
42
43 LOG_MODULE_DECLARE(os, CONFIG_KERNEL_LOG_LEVEL);
44
45 BUILD_ASSERT(CONFIG_MMU_PAGE_SIZE == 0x1000,
46 "MMU_PAGE_SIZE value is invalid, only 4 kB pages are supported\n");
47
48 /*
49 * Level 1 page table has to be 4Kb to fit into one of the wired entries.
50 * All entries are initialized as INVALID, so an attempt to read an unmapped
51 * area will cause a double exception.
52 *
53 * Each memory domain contains its own l1 page table. The kernel l1 page table is
54 * located at the index 0.
55 */
56 static uint32_t l1_page_table[CONFIG_XTENSA_MMU_NUM_L1_TABLES][XTENSA_L1_PAGE_TABLE_ENTRIES]
57 __aligned(KB(4));
58
59
60 /*
61 * That is an alias for the page tables set used by the kernel.
62 */
63 uint32_t *xtensa_kernel_ptables = (uint32_t *)l1_page_table[0];
64
65 /*
66 * Each table in the level 2 maps a 4Mb memory range. It consists of 1024 entries each one
67 * covering a 4Kb page.
68 */
69 static uint32_t l2_page_tables[CONFIG_XTENSA_MMU_NUM_L2_TABLES][XTENSA_L2_PAGE_TABLE_ENTRIES]
70 __aligned(KB(4));
71
72 /*
73 * This additional variable tracks which l1 tables are in use. This is kept separated from
74 * the tables to keep alignment easier.
75 *
76 * @note: The first bit is set because it is used for the kernel page tables.
77 */
78 static ATOMIC_DEFINE(l1_page_table_track, CONFIG_XTENSA_MMU_NUM_L1_TABLES);
79
80 /*
81 * This additional variable tracks which l2 tables are in use. This is kept separated from
82 * the tables to keep alignment easier.
83 */
84 static ATOMIC_DEFINE(l2_page_tables_track, CONFIG_XTENSA_MMU_NUM_L2_TABLES);
85
86 /*
87 * Protects xtensa_domain_list and serializes access to page tables.
88 */
89 static struct k_spinlock xtensa_mmu_lock;
90
91 #ifdef CONFIG_USERSPACE
92
93 /*
94 * Each domain has its own ASID. ASID can go through 1 (kernel) to 255.
95 * When a TLB entry matches, the hw will check the ASID in the entry and finds
96 * the correspondent position in the RASID register. This position will then be
97 * compared with the current ring (CRING) to check the permission.
98 */
99 static uint8_t asid_count = 3;
100
101 /*
102 * List with all active and initialized memory domains.
103 */
104 static sys_slist_t xtensa_domain_list;
105 #endif /* CONFIG_USERSPACE */
106
107 extern char _heap_end[];
108 extern char _heap_start[];
109 /*
110 * Static definition of all code & data memory regions of the
111 * current Zephyr image. This information must be available &
112 * processed upon MMU initialization.
113 */
114
115 static const struct xtensa_mmu_range mmu_zephyr_ranges[] = {
116 /*
117 * Mark the zephyr execution regions (data, bss, noinit, etc.)
118 * cacheable, read / write and non-executable
119 */
120 {
121 /* This includes .data, .bss and various kobject sections. */
122 .start = (uint32_t)_image_ram_start,
123 .end = (uint32_t)_image_ram_end,
124 #ifdef CONFIG_XTENSA_RPO_CACHE
125 .attrs = XTENSA_MMU_PERM_W,
126 #else
127 .attrs = XTENSA_MMU_PERM_W | XTENSA_MMU_CACHED_WB,
128 #endif
129 .name = "data",
130 },
131 #if K_HEAP_MEM_POOL_SIZE > 0
132 /* System heap memory */
133 {
134 .start = (uint32_t)_heap_start,
135 .end = (uint32_t)_heap_end,
136 #ifdef CONFIG_XTENSA_RPO_CACHE
137 .attrs = XTENSA_MMU_PERM_W,
138 #else
139 .attrs = XTENSA_MMU_PERM_W | XTENSA_MMU_CACHED_WB,
140 #endif
141 .name = "heap",
142 },
143 #endif
144 /* Mark text segment cacheable, read only and executable */
145 {
146 .start = (uint32_t)__text_region_start,
147 .end = (uint32_t)__text_region_end,
148 .attrs = XTENSA_MMU_PERM_X | XTENSA_MMU_CACHED_WB | XTENSA_MMU_MAP_SHARED,
149 .name = "text",
150 },
151 /* Mark rodata segment cacheable, read only and non-executable */
152 {
153 .start = (uint32_t)__rodata_region_start,
154 .end = (uint32_t)__rodata_region_end,
155 .attrs = XTENSA_MMU_CACHED_WB | XTENSA_MMU_MAP_SHARED,
156 .name = "rodata",
157 },
158 };
159
thread_page_tables_get(const struct k_thread * thread)160 static inline uint32_t *thread_page_tables_get(const struct k_thread *thread)
161 {
162 #ifdef CONFIG_USERSPACE
163 if ((thread->base.user_options & K_USER) != 0U) {
164 return thread->arch.ptables;
165 }
166 #endif
167
168 return xtensa_kernel_ptables;
169 }
170
171 /**
172 * @brief Check if the page table entry is illegal.
173 *
174 * @param[in] Page table entry.
175 */
is_pte_illegal(uint32_t pte)176 static inline bool is_pte_illegal(uint32_t pte)
177 {
178 uint32_t attr = pte & XTENSA_MMU_PTE_ATTR_MASK;
179
180 /*
181 * The ISA manual states only 12 and 14 are illegal values.
182 * 13 and 15 are not. So we need to be specific than simply
183 * testing if bits 2 and 3 are set.
184 */
185 return (attr == 12) || (attr == 14);
186 }
187
188 /*
189 * @brief Initialize all page table entries to be illegal.
190 *
191 * @param[in] Pointer to page table.
192 * @param[in] Number of page table entries in the page table.
193 */
init_page_table(uint32_t * ptable,size_t num_entries)194 static void init_page_table(uint32_t *ptable, size_t num_entries)
195 {
196 int i;
197
198 for (i = 0; i < num_entries; i++) {
199 ptable[i] = XTENSA_MMU_PTE_ILLEGAL;
200 }
201 }
202
alloc_l2_table(void)203 static inline uint32_t *alloc_l2_table(void)
204 {
205 uint16_t idx;
206
207 for (idx = 0; idx < CONFIG_XTENSA_MMU_NUM_L2_TABLES; idx++) {
208 if (!atomic_test_and_set_bit(l2_page_tables_track, idx)) {
209 return (uint32_t *)&l2_page_tables[idx];
210 }
211 }
212
213 return NULL;
214 }
215
map_memory_range(const uint32_t start,const uint32_t end,const uint32_t attrs)216 static void map_memory_range(const uint32_t start, const uint32_t end,
217 const uint32_t attrs)
218 {
219 uint32_t page, *table;
220 bool shared = !!(attrs & XTENSA_MMU_MAP_SHARED);
221 uint32_t sw_attrs = (attrs & XTENSA_MMU_PTE_ATTR_ORIGINAL) == XTENSA_MMU_PTE_ATTR_ORIGINAL ?
222 attrs : 0;
223
224 for (page = start; page < end; page += CONFIG_MMU_PAGE_SIZE) {
225 uint32_t pte = XTENSA_MMU_PTE(page,
226 shared ? XTENSA_MMU_SHARED_RING :
227 XTENSA_MMU_KERNEL_RING,
228 sw_attrs, attrs);
229 uint32_t l2_pos = XTENSA_MMU_L2_POS(page);
230 uint32_t l1_pos = XTENSA_MMU_L1_POS(page);
231
232 if (is_pte_illegal(xtensa_kernel_ptables[l1_pos])) {
233 table = alloc_l2_table();
234
235 __ASSERT(table != NULL, "There is no l2 page table available to "
236 "map 0x%08x\n", page);
237
238 init_page_table(table, XTENSA_L2_PAGE_TABLE_ENTRIES);
239
240 xtensa_kernel_ptables[l1_pos] =
241 XTENSA_MMU_PTE((uint32_t)table, XTENSA_MMU_KERNEL_RING,
242 sw_attrs, XTENSA_MMU_PAGE_TABLE_ATTR);
243 }
244
245 table = (uint32_t *)(xtensa_kernel_ptables[l1_pos] & XTENSA_MMU_PTE_PPN_MASK);
246 table[l2_pos] = pte;
247 }
248 }
249
map_memory(const uint32_t start,const uint32_t end,const uint32_t attrs)250 static void map_memory(const uint32_t start, const uint32_t end,
251 const uint32_t attrs)
252 {
253 map_memory_range(start, end, attrs);
254
255 #ifdef CONFIG_XTENSA_MMU_DOUBLE_MAP
256 if (sys_cache_is_ptr_uncached((void *)start)) {
257 map_memory_range(POINTER_TO_UINT(sys_cache_cached_ptr_get((void *)start)),
258 POINTER_TO_UINT(sys_cache_cached_ptr_get((void *)end)),
259 attrs | XTENSA_MMU_CACHED_WB);
260 } else if (sys_cache_is_ptr_cached((void *)start)) {
261 map_memory_range(POINTER_TO_UINT(sys_cache_uncached_ptr_get((void *)start)),
262 POINTER_TO_UINT(sys_cache_uncached_ptr_get((void *)end)), attrs);
263 }
264 #endif
265 }
266
xtensa_init_page_tables(void)267 static void xtensa_init_page_tables(void)
268 {
269 volatile uint8_t entry;
270 static bool already_inited;
271
272 if (already_inited) {
273 return;
274 }
275 already_inited = true;
276
277 init_page_table(xtensa_kernel_ptables, XTENSA_L1_PAGE_TABLE_ENTRIES);
278 atomic_set_bit(l1_page_table_track, 0);
279
280 for (entry = 0; entry < ARRAY_SIZE(mmu_zephyr_ranges); entry++) {
281 const struct xtensa_mmu_range *range = &mmu_zephyr_ranges[entry];
282
283 map_memory(range->start, range->end, range->attrs | XTENSA_MMU_PTE_ATTR_ORIGINAL);
284 }
285
286 for (entry = 0; entry < xtensa_soc_mmu_ranges_num; entry++) {
287 const struct xtensa_mmu_range *range = &xtensa_soc_mmu_ranges[entry];
288
289 map_memory(range->start, range->end, range->attrs | XTENSA_MMU_PTE_ATTR_ORIGINAL);
290 }
291
292 /* Finally, the direct-mapped pages used in the page tables
293 * must be fixed up to use the same cache attribute (but these
294 * must be writable, obviously). They shouldn't be left at
295 * the default.
296 */
297 map_memory_range((uint32_t) &l1_page_table[0],
298 (uint32_t) &l1_page_table[CONFIG_XTENSA_MMU_NUM_L1_TABLES],
299 XTENSA_MMU_PAGE_TABLE_ATTR | XTENSA_MMU_PERM_W);
300 map_memory_range((uint32_t) &l2_page_tables[0],
301 (uint32_t) &l2_page_tables[CONFIG_XTENSA_MMU_NUM_L2_TABLES],
302 XTENSA_MMU_PAGE_TABLE_ATTR | XTENSA_MMU_PERM_W);
303
304 sys_cache_data_flush_all();
305 }
306
arch_xtensa_mmu_post_init(bool is_core0)307 __weak void arch_xtensa_mmu_post_init(bool is_core0)
308 {
309 ARG_UNUSED(is_core0);
310 }
311
xtensa_mmu_init(void)312 void xtensa_mmu_init(void)
313 {
314 xtensa_init_page_tables();
315
316 xtensa_init_paging(xtensa_kernel_ptables);
317
318 /*
319 * This is used to determine whether we are faulting inside double
320 * exception if this is not zero. Sometimes SoC starts with this not
321 * being set to zero. So clear it during boot.
322 */
323 XTENSA_WSR(ZSR_DEPC_SAVE_STR, 0);
324
325 arch_xtensa_mmu_post_init(_current_cpu->id == 0);
326 }
327
xtensa_mmu_reinit(void)328 void xtensa_mmu_reinit(void)
329 {
330 /* First initialize the hardware */
331 xtensa_init_paging(xtensa_kernel_ptables);
332
333 #ifdef CONFIG_USERSPACE
334 struct k_thread *thread = _current_cpu->current;
335 struct arch_mem_domain *domain =
336 &(thread->mem_domain_info.mem_domain->arch);
337
338
339 /* Set the page table for current context */
340 xtensa_set_paging(domain->asid, domain->ptables);
341 #endif /* CONFIG_USERSPACE */
342
343 arch_xtensa_mmu_post_init(_current_cpu->id == 0);
344 }
345
346 #ifdef CONFIG_ARCH_HAS_RESERVED_PAGE_FRAMES
347 /* Zephyr's linker scripts for Xtensa usually puts
348 * something before z_mapped_start (aka .text),
349 * i.e. vecbase, so that we need to reserve those
350 * space or else k_mem_map() would be mapping those,
351 * resulting in faults.
352 */
arch_reserved_pages_update(void)353 __weak void arch_reserved_pages_update(void)
354 {
355 uintptr_t page;
356 int idx;
357
358 for (page = CONFIG_SRAM_BASE_ADDRESS, idx = 0;
359 page < (uintptr_t)z_mapped_start;
360 page += CONFIG_MMU_PAGE_SIZE, idx++) {
361 k_mem_page_frame_set(&k_mem_page_frames[idx], K_MEM_PAGE_FRAME_RESERVED);
362 }
363 }
364 #endif /* CONFIG_ARCH_HAS_RESERVED_PAGE_FRAMES */
365
l2_page_table_map(uint32_t * l1_table,void * vaddr,uintptr_t phys,uint32_t flags,bool is_user)366 static bool l2_page_table_map(uint32_t *l1_table, void *vaddr, uintptr_t phys,
367 uint32_t flags, bool is_user)
368 {
369 uint32_t l1_pos = XTENSA_MMU_L1_POS((uint32_t)vaddr);
370 uint32_t l2_pos = XTENSA_MMU_L2_POS((uint32_t)vaddr);
371 uint32_t *table;
372
373 sys_cache_data_invd_range((void *)&l1_table[l1_pos], sizeof(l1_table[0]));
374
375 if (is_pte_illegal(l1_table[l1_pos])) {
376 table = alloc_l2_table();
377
378 if (table == NULL) {
379 return false;
380 }
381
382 init_page_table(table, XTENSA_L2_PAGE_TABLE_ENTRIES);
383
384 l1_table[l1_pos] = XTENSA_MMU_PTE((uint32_t)table, XTENSA_MMU_KERNEL_RING,
385 0, XTENSA_MMU_PAGE_TABLE_ATTR);
386
387 sys_cache_data_flush_range((void *)&l1_table[l1_pos], sizeof(l1_table[0]));
388 }
389
390 table = (uint32_t *)(l1_table[l1_pos] & XTENSA_MMU_PTE_PPN_MASK);
391 table[l2_pos] = XTENSA_MMU_PTE(phys, is_user ? XTENSA_MMU_USER_RING :
392 XTENSA_MMU_KERNEL_RING,
393 0, flags);
394
395 sys_cache_data_flush_range((void *)&table[l2_pos], sizeof(table[0]));
396 xtensa_tlb_autorefill_invalidate();
397
398 return true;
399 }
400
__arch_mem_map(void * va,uintptr_t pa,uint32_t xtensa_flags,bool is_user)401 static inline void __arch_mem_map(void *va, uintptr_t pa, uint32_t xtensa_flags, bool is_user)
402 {
403 bool ret;
404 void *vaddr, *vaddr_uc;
405 uintptr_t paddr, paddr_uc;
406 uint32_t flags, flags_uc;
407
408 if (IS_ENABLED(CONFIG_XTENSA_MMU_DOUBLE_MAP)) {
409 if (sys_cache_is_ptr_cached(va)) {
410 vaddr = va;
411 vaddr_uc = sys_cache_uncached_ptr_get(va);
412 } else {
413 vaddr = sys_cache_cached_ptr_get(va);
414 vaddr_uc = va;
415 }
416
417 if (sys_cache_is_ptr_cached((void *)pa)) {
418 paddr = pa;
419 paddr_uc = (uintptr_t)sys_cache_uncached_ptr_get((void *)pa);
420 } else {
421 paddr = (uintptr_t)sys_cache_cached_ptr_get((void *)pa);
422 paddr_uc = pa;
423 }
424
425 flags_uc = (xtensa_flags & ~XTENSA_MMU_PTE_ATTR_CACHED_MASK);
426 flags = flags_uc | XTENSA_MMU_CACHED_WB;
427 } else {
428 vaddr = va;
429 paddr = pa;
430 flags = xtensa_flags;
431 }
432
433 ret = l2_page_table_map(xtensa_kernel_ptables, (void *)vaddr, paddr,
434 flags, is_user);
435 __ASSERT(ret, "Virtual address (%p) already mapped", va);
436
437 if (IS_ENABLED(CONFIG_XTENSA_MMU_DOUBLE_MAP) && ret) {
438 ret = l2_page_table_map(xtensa_kernel_ptables, (void *)vaddr_uc, paddr_uc,
439 flags_uc, is_user);
440 __ASSERT(ret, "Virtual address (%p) already mapped", vaddr_uc);
441 }
442
443 #ifndef CONFIG_USERSPACE
444 ARG_UNUSED(ret);
445 #else
446 if (ret) {
447 sys_snode_t *node;
448 struct arch_mem_domain *domain;
449 k_spinlock_key_t key;
450
451 key = k_spin_lock(&z_mem_domain_lock);
452 SYS_SLIST_FOR_EACH_NODE(&xtensa_domain_list, node) {
453 domain = CONTAINER_OF(node, struct arch_mem_domain, node);
454
455 ret = l2_page_table_map(domain->ptables, (void *)vaddr, paddr,
456 flags, is_user);
457 __ASSERT(ret, "Virtual address (%p) already mapped for domain %p",
458 vaddr, domain);
459
460 if (IS_ENABLED(CONFIG_XTENSA_MMU_DOUBLE_MAP) && ret) {
461 ret = l2_page_table_map(domain->ptables,
462 (void *)vaddr_uc, paddr_uc,
463 flags_uc, is_user);
464 __ASSERT(ret, "Virtual address (%p) already mapped for domain %p",
465 vaddr_uc, domain);
466 }
467 }
468 k_spin_unlock(&z_mem_domain_lock, key);
469 }
470 #endif /* CONFIG_USERSPACE */
471 }
472
arch_mem_map(void * virt,uintptr_t phys,size_t size,uint32_t flags)473 void arch_mem_map(void *virt, uintptr_t phys, size_t size, uint32_t flags)
474 {
475 uint32_t va = (uint32_t)virt;
476 uint32_t pa = (uint32_t)phys;
477 uint32_t rem_size = (uint32_t)size;
478 uint32_t xtensa_flags = 0;
479 k_spinlock_key_t key;
480 bool is_user;
481
482 if (size == 0) {
483 LOG_ERR("Cannot map physical memory at 0x%08X: invalid "
484 "zero size", (uint32_t)phys);
485 k_panic();
486 }
487
488 switch (flags & K_MEM_CACHE_MASK) {
489
490 case K_MEM_CACHE_WB:
491 xtensa_flags |= XTENSA_MMU_CACHED_WB;
492 break;
493 case K_MEM_CACHE_WT:
494 xtensa_flags |= XTENSA_MMU_CACHED_WT;
495 break;
496 case K_MEM_CACHE_NONE:
497 __fallthrough;
498 default:
499 break;
500 }
501
502 if ((flags & K_MEM_PERM_RW) == K_MEM_PERM_RW) {
503 xtensa_flags |= XTENSA_MMU_PERM_W;
504 }
505 if ((flags & K_MEM_PERM_EXEC) == K_MEM_PERM_EXEC) {
506 xtensa_flags |= XTENSA_MMU_PERM_X;
507 }
508
509 is_user = (flags & K_MEM_PERM_USER) == K_MEM_PERM_USER;
510
511 key = k_spin_lock(&xtensa_mmu_lock);
512
513 while (rem_size > 0) {
514 __arch_mem_map((void *)va, pa, xtensa_flags, is_user);
515
516 rem_size -= (rem_size >= KB(4)) ? KB(4) : rem_size;
517 va += KB(4);
518 pa += KB(4);
519 }
520
521 #if CONFIG_MP_MAX_NUM_CPUS > 1
522 xtensa_mmu_tlb_ipi();
523 #endif
524
525 sys_cache_data_flush_and_invd_all();
526 k_spin_unlock(&xtensa_mmu_lock, key);
527 }
528
529 /**
530 * @return True if page is executable (thus need to invalidate ITLB),
531 * false if not.
532 */
l2_page_table_unmap(uint32_t * l1_table,void * vaddr)533 static bool l2_page_table_unmap(uint32_t *l1_table, void *vaddr)
534 {
535 uint32_t l1_pos = XTENSA_MMU_L1_POS((uint32_t)vaddr);
536 uint32_t l2_pos = XTENSA_MMU_L2_POS((uint32_t)vaddr);
537 uint32_t *l2_table;
538 uint32_t table_pos;
539 bool exec;
540
541 sys_cache_data_invd_range((void *)&l1_table[l1_pos], sizeof(l1_table[0]));
542
543 if (is_pte_illegal(l1_table[l1_pos])) {
544 /* We shouldn't be unmapping an illegal entry.
545 * Return true so that we can invalidate ITLB too.
546 */
547 return true;
548 }
549
550 exec = l1_table[l1_pos] & XTENSA_MMU_PERM_X;
551
552 l2_table = (uint32_t *)(l1_table[l1_pos] & XTENSA_MMU_PTE_PPN_MASK);
553
554 sys_cache_data_invd_range((void *)&l2_table[l2_pos], sizeof(l2_table[0]));
555
556 l2_table[l2_pos] = XTENSA_MMU_PTE_ILLEGAL;
557
558 sys_cache_data_flush_range((void *)&l2_table[l2_pos], sizeof(l2_table[0]));
559
560 for (l2_pos = 0; l2_pos < XTENSA_L2_PAGE_TABLE_ENTRIES; l2_pos++) {
561 if (!is_pte_illegal(l2_table[l2_pos])) {
562 goto end;
563 }
564 }
565
566 l1_table[l1_pos] = XTENSA_MMU_PTE_ILLEGAL;
567 sys_cache_data_flush_range((void *)&l1_table[l1_pos], sizeof(l1_table[0]));
568
569 table_pos = (l2_table - (uint32_t *)l2_page_tables) / (XTENSA_L2_PAGE_TABLE_ENTRIES);
570 atomic_clear_bit(l2_page_tables_track, table_pos);
571
572 end:
573 /* Need to invalidate L2 page table as it is no longer valid. */
574 xtensa_tlb_autorefill_invalidate();
575 return exec;
576 }
577
__arch_mem_unmap(void * va)578 static inline void __arch_mem_unmap(void *va)
579 {
580 bool is_exec;
581 void *vaddr, *vaddr_uc;
582
583 if (IS_ENABLED(CONFIG_XTENSA_MMU_DOUBLE_MAP)) {
584 if (sys_cache_is_ptr_cached(va)) {
585 vaddr = va;
586 vaddr_uc = sys_cache_uncached_ptr_get(va);
587 } else {
588 vaddr = sys_cache_cached_ptr_get(va);
589 vaddr_uc = va;
590 }
591 } else {
592 vaddr = va;
593 }
594
595 is_exec = l2_page_table_unmap(xtensa_kernel_ptables, (void *)vaddr);
596
597 if (IS_ENABLED(CONFIG_XTENSA_MMU_DOUBLE_MAP)) {
598 (void)l2_page_table_unmap(xtensa_kernel_ptables, (void *)vaddr_uc);
599 }
600
601 #ifdef CONFIG_USERSPACE
602 sys_snode_t *node;
603 struct arch_mem_domain *domain;
604 k_spinlock_key_t key;
605
606 key = k_spin_lock(&z_mem_domain_lock);
607 SYS_SLIST_FOR_EACH_NODE(&xtensa_domain_list, node) {
608 domain = CONTAINER_OF(node, struct arch_mem_domain, node);
609
610 (void)l2_page_table_unmap(domain->ptables, (void *)vaddr);
611
612 if (IS_ENABLED(CONFIG_XTENSA_MMU_DOUBLE_MAP)) {
613 (void)l2_page_table_unmap(domain->ptables, (void *)vaddr_uc);
614 }
615 }
616 k_spin_unlock(&z_mem_domain_lock, key);
617 #endif /* CONFIG_USERSPACE */
618 }
619
arch_mem_unmap(void * addr,size_t size)620 void arch_mem_unmap(void *addr, size_t size)
621 {
622 uint32_t va = (uint32_t)addr;
623 uint32_t rem_size = (uint32_t)size;
624 k_spinlock_key_t key;
625
626 if (addr == NULL) {
627 LOG_ERR("Cannot unmap NULL pointer");
628 return;
629 }
630
631 if (size == 0) {
632 LOG_ERR("Cannot unmap virtual memory with zero size");
633 return;
634 }
635
636 key = k_spin_lock(&xtensa_mmu_lock);
637
638 while (rem_size > 0) {
639 __arch_mem_unmap((void *)va);
640
641 rem_size -= (rem_size >= KB(4)) ? KB(4) : rem_size;
642 va += KB(4);
643 }
644
645 #if CONFIG_MP_MAX_NUM_CPUS > 1
646 xtensa_mmu_tlb_ipi();
647 #endif
648
649 sys_cache_data_flush_and_invd_all();
650 k_spin_unlock(&xtensa_mmu_lock, key);
651 }
652
653 /* This should be implemented in the SoC layer.
654 * This weak version is here to avoid build errors.
655 */
xtensa_mmu_tlb_ipi(void)656 void __weak xtensa_mmu_tlb_ipi(void)
657 {
658 }
659
xtensa_mmu_tlb_shootdown(void)660 void xtensa_mmu_tlb_shootdown(void)
661 {
662 unsigned int key;
663
664 /* Need to lock interrupts to prevent any context
665 * switching until all the page tables are updated.
666 * Or else we would be switching to another thread
667 * and running that with incorrect page tables
668 * which would result in permission issues.
669 */
670 key = arch_irq_lock();
671
672 K_SPINLOCK(&xtensa_mmu_lock) {
673 /* We don't have information on which page tables have changed,
674 * so we just invalidate the cache for all L1 page tables.
675 */
676 sys_cache_data_invd_range((void *)l1_page_table, sizeof(l1_page_table));
677 sys_cache_data_invd_range((void *)l2_page_tables, sizeof(l2_page_tables));
678 }
679
680 #ifdef CONFIG_USERSPACE
681 struct k_thread *thread = _current_cpu->current;
682
683 /* If current thread is a user thread, we need to see if it has
684 * been migrated to another memory domain as the L1 page table
685 * is different from the currently used one.
686 */
687 if ((thread->base.user_options & K_USER) == K_USER) {
688 uint32_t ptevaddr_entry, ptevaddr,
689 thread_ptables, current_ptables;
690
691 /* Need to read the currently used L1 page table.
692 * We know that L1 page table is always mapped at way
693 * MMU_PTE_WAY, so we can skip the probing step by
694 * generating the query entry directly.
695 */
696 ptevaddr = (uint32_t)xtensa_ptevaddr_get();
697 ptevaddr_entry = XTENSA_MMU_PTE_ENTRY_VADDR(ptevaddr, ptevaddr)
698 | XTENSA_MMU_PTE_WAY;
699 current_ptables = xtensa_dtlb_paddr_read(ptevaddr_entry);
700 thread_ptables = (uint32_t)thread->arch.ptables;
701
702 if (thread_ptables != current_ptables) {
703 /* Need to remap the thread page tables if the ones
704 * indicated by the current thread are different
705 * than the current mapped page table.
706 */
707 struct arch_mem_domain *domain =
708 &(thread->mem_domain_info.mem_domain->arch);
709 xtensa_set_paging(domain->asid, (uint32_t *)thread_ptables);
710 }
711
712 }
713 #endif /* CONFIG_USERSPACE */
714
715 /* L2 are done via autofill, so invalidate autofill TLBs
716 * would refresh the L2 page tables.
717 *
718 * L1 will be refreshed during context switch so no need
719 * to do anything here.
720 */
721 xtensa_tlb_autorefill_invalidate();
722
723 arch_irq_unlock(key);
724 }
725
726 #ifdef CONFIG_USERSPACE
727
alloc_l1_table(void)728 static inline uint32_t *alloc_l1_table(void)
729 {
730 uint16_t idx;
731
732 for (idx = 0; idx < CONFIG_XTENSA_MMU_NUM_L1_TABLES; idx++) {
733 if (!atomic_test_and_set_bit(l1_page_table_track, idx)) {
734 return (uint32_t *)&l1_page_table[idx];
735 }
736 }
737
738 return NULL;
739 }
740
dup_table(void)741 static uint32_t *dup_table(void)
742 {
743 uint16_t i, j;
744 uint32_t *dst_table = alloc_l1_table();
745
746 if (!dst_table) {
747 return NULL;
748 }
749
750 for (i = 0; i < XTENSA_L1_PAGE_TABLE_ENTRIES; i++) {
751 uint32_t *l2_table, *src_l2_table;
752
753 if (is_pte_illegal(xtensa_kernel_ptables[i]) ||
754 (i == XTENSA_MMU_L1_POS(XTENSA_MMU_PTEVADDR))) {
755 dst_table[i] = XTENSA_MMU_PTE_ILLEGAL;
756 continue;
757 }
758
759 src_l2_table = (uint32_t *)(xtensa_kernel_ptables[i] & XTENSA_MMU_PTE_PPN_MASK);
760 l2_table = alloc_l2_table();
761 if (l2_table == NULL) {
762 goto err;
763 }
764
765 for (j = 0; j < XTENSA_L2_PAGE_TABLE_ENTRIES; j++) {
766 uint32_t original_attr = XTENSA_MMU_PTE_SW_GET(src_l2_table[j]);
767
768 l2_table[j] = src_l2_table[j];
769 if (original_attr != 0x0) {
770 uint8_t ring;
771
772 ring = XTENSA_MMU_PTE_RING_GET(l2_table[j]);
773 l2_table[j] = XTENSA_MMU_PTE_ATTR_SET(l2_table[j], original_attr);
774 l2_table[j] = XTENSA_MMU_PTE_RING_SET(l2_table[j],
775 ring == XTENSA_MMU_SHARED_RING ?
776 XTENSA_MMU_SHARED_RING : XTENSA_MMU_KERNEL_RING);
777 }
778 }
779
780 /* The page table is using kernel ASID because we don't
781 * user thread manipulate it.
782 */
783 dst_table[i] = XTENSA_MMU_PTE((uint32_t)l2_table, XTENSA_MMU_KERNEL_RING,
784 0, XTENSA_MMU_PAGE_TABLE_ATTR);
785
786 sys_cache_data_flush_range((void *)l2_table, XTENSA_L2_PAGE_TABLE_SIZE);
787 }
788
789 sys_cache_data_flush_range((void *)dst_table, XTENSA_L1_PAGE_TABLE_SIZE);
790
791 return dst_table;
792
793 err:
794 /* TODO: Cleanup failed allocation*/
795 return NULL;
796 }
797
arch_mem_domain_init(struct k_mem_domain * domain)798 int arch_mem_domain_init(struct k_mem_domain *domain)
799 {
800 uint32_t *ptables;
801 k_spinlock_key_t key;
802 int ret;
803
804 /*
805 * For now, lets just assert if we have reached the maximum number
806 * of asid we assert.
807 */
808 __ASSERT(asid_count < (XTENSA_MMU_SHARED_ASID), "Reached maximum of ASID available");
809
810 key = k_spin_lock(&xtensa_mmu_lock);
811 /* If this is the default domain, we don't need
812 * to create a new set of page tables. We can just
813 * use the kernel page tables and save memory.
814 */
815
816 if (domain == &k_mem_domain_default) {
817 domain->arch.ptables = xtensa_kernel_ptables;
818 domain->arch.asid = asid_count;
819 goto end;
820 }
821
822
823 ptables = dup_table();
824
825 if (ptables == NULL) {
826 ret = -ENOMEM;
827 goto err;
828 }
829
830 domain->arch.ptables = ptables;
831 domain->arch.asid = ++asid_count;
832
833 sys_slist_append(&xtensa_domain_list, &domain->arch.node);
834
835 end:
836 ret = 0;
837
838 err:
839 k_spin_unlock(&xtensa_mmu_lock, key);
840
841 return ret;
842 }
843
region_map_update(uint32_t * ptables,uintptr_t start,size_t size,uint32_t ring,uint32_t flags)844 static int region_map_update(uint32_t *ptables, uintptr_t start,
845 size_t size, uint32_t ring, uint32_t flags)
846 {
847 int ret = 0;
848
849 for (size_t offset = 0; offset < size; offset += CONFIG_MMU_PAGE_SIZE) {
850 uint32_t *l2_table, pte;
851 uint32_t page = start + offset;
852 uint32_t l1_pos = XTENSA_MMU_L1_POS(page);
853 uint32_t l2_pos = XTENSA_MMU_L2_POS(page);
854 /* Make sure we grab a fresh copy of L1 page table */
855 sys_cache_data_invd_range((void *)&ptables[l1_pos], sizeof(ptables[0]));
856
857 l2_table = (uint32_t *)(ptables[l1_pos] & XTENSA_MMU_PTE_PPN_MASK);
858
859 sys_cache_data_invd_range((void *)&l2_table[l2_pos], sizeof(l2_table[0]));
860
861 pte = XTENSA_MMU_PTE_RING_SET(l2_table[l2_pos], ring);
862 pte = XTENSA_MMU_PTE_ATTR_SET(pte, flags);
863
864 l2_table[l2_pos] = pte;
865
866 sys_cache_data_flush_range((void *)&l2_table[l2_pos], sizeof(l2_table[0]));
867
868 xtensa_dtlb_vaddr_invalidate((void *)page);
869 }
870
871 return ret;
872 }
873
update_region(uint32_t * ptables,uintptr_t start,size_t size,uint32_t ring,uint32_t flags,uint32_t option)874 static inline int update_region(uint32_t *ptables, uintptr_t start,
875 size_t size, uint32_t ring, uint32_t flags,
876 uint32_t option)
877 {
878 int ret;
879 k_spinlock_key_t key;
880
881 key = k_spin_lock(&xtensa_mmu_lock);
882
883 #ifdef CONFIG_XTENSA_MMU_DOUBLE_MAP
884 uintptr_t va, va_uc;
885 uint32_t new_flags, new_flags_uc;
886
887 if (sys_cache_is_ptr_cached((void *)start)) {
888 va = start;
889 va_uc = (uintptr_t)sys_cache_uncached_ptr_get((void *)start);
890 } else {
891 va = (uintptr_t)sys_cache_cached_ptr_get((void *)start);
892 va_uc = start;
893 }
894
895 new_flags_uc = (flags & ~XTENSA_MMU_PTE_ATTR_CACHED_MASK);
896 new_flags = new_flags_uc | XTENSA_MMU_CACHED_WB;
897
898 ret = region_map_update(ptables, va, size, ring, new_flags);
899
900 if (ret == 0) {
901 ret = region_map_update(ptables, va_uc, size, ring, new_flags_uc);
902 }
903 #else
904 ret = region_map_update(ptables, start, size, ring, flags);
905 #endif /* CONFIG_XTENSA_MMU_DOUBLE_MAP */
906
907 #if CONFIG_MP_MAX_NUM_CPUS > 1
908 if ((option & OPTION_NO_TLB_IPI) != OPTION_NO_TLB_IPI) {
909 xtensa_mmu_tlb_ipi();
910 }
911 #endif
912
913 sys_cache_data_flush_and_invd_all();
914 k_spin_unlock(&xtensa_mmu_lock, key);
915
916 return ret;
917 }
918
reset_region(uint32_t * ptables,uintptr_t start,size_t size,uint32_t option)919 static inline int reset_region(uint32_t *ptables, uintptr_t start, size_t size, uint32_t option)
920 {
921 return update_region(ptables, start, size,
922 XTENSA_MMU_KERNEL_RING, XTENSA_MMU_PERM_W, option);
923 }
924
xtensa_user_stack_perms(struct k_thread * thread)925 void xtensa_user_stack_perms(struct k_thread *thread)
926 {
927 (void)memset((void *)thread->stack_info.start,
928 (IS_ENABLED(CONFIG_INIT_STACKS)) ? 0xAA : 0x00,
929 thread->stack_info.size - thread->stack_info.delta);
930
931 update_region(thread_page_tables_get(thread),
932 thread->stack_info.start, thread->stack_info.size,
933 XTENSA_MMU_USER_RING, XTENSA_MMU_PERM_W | XTENSA_MMU_CACHED_WB, 0);
934 }
935
arch_mem_domain_max_partitions_get(void)936 int arch_mem_domain_max_partitions_get(void)
937 {
938 return CONFIG_MAX_DOMAIN_PARTITIONS;
939 }
940
arch_mem_domain_partition_remove(struct k_mem_domain * domain,uint32_t partition_id)941 int arch_mem_domain_partition_remove(struct k_mem_domain *domain,
942 uint32_t partition_id)
943 {
944 struct k_mem_partition *partition = &domain->partitions[partition_id];
945
946 /* Reset the partition's region back to defaults */
947 return reset_region(domain->arch.ptables, partition->start,
948 partition->size, 0);
949 }
950
arch_mem_domain_partition_add(struct k_mem_domain * domain,uint32_t partition_id)951 int arch_mem_domain_partition_add(struct k_mem_domain *domain,
952 uint32_t partition_id)
953 {
954 struct k_mem_partition *partition = &domain->partitions[partition_id];
955 uint32_t ring = K_MEM_PARTITION_IS_USER(partition->attr) ? XTENSA_MMU_USER_RING :
956 XTENSA_MMU_KERNEL_RING;
957
958 return update_region(domain->arch.ptables, partition->start,
959 partition->size, ring, partition->attr, 0);
960 }
961
962 /* These APIs don't need to do anything */
arch_mem_domain_thread_add(struct k_thread * thread)963 int arch_mem_domain_thread_add(struct k_thread *thread)
964 {
965 int ret = 0;
966 bool is_user, is_migration;
967 uint32_t *old_ptables;
968 struct k_mem_domain *domain;
969
970 old_ptables = thread->arch.ptables;
971 domain = thread->mem_domain_info.mem_domain;
972 thread->arch.ptables = domain->arch.ptables;
973
974 is_user = (thread->base.user_options & K_USER) != 0;
975 is_migration = (old_ptables != NULL) && is_user;
976
977 if (is_migration) {
978 /* Give access to the thread's stack in its new
979 * memory domain if it is migrating.
980 */
981 update_region(thread_page_tables_get(thread),
982 thread->stack_info.start, thread->stack_info.size,
983 XTENSA_MMU_USER_RING,
984 XTENSA_MMU_PERM_W | XTENSA_MMU_CACHED_WB,
985 OPTION_NO_TLB_IPI);
986 /* and reset thread's stack permission in
987 * the old page tables.
988 */
989 ret = reset_region(old_ptables,
990 thread->stack_info.start,
991 thread->stack_info.size, 0);
992 }
993
994 /* Need to switch to new page tables if this is
995 * the current thread running.
996 */
997 if (thread == _current_cpu->current) {
998 xtensa_set_paging(domain->arch.asid, thread->arch.ptables);
999 }
1000
1001 #if CONFIG_MP_MAX_NUM_CPUS > 1
1002 /* Need to tell other CPUs to switch to the new page table
1003 * in case the thread is running on one of them.
1004 *
1005 * Note that there is no need to send TLB IPI if this is
1006 * migration as it was sent above during reset_region().
1007 */
1008 if ((thread != _current_cpu->current) && !is_migration) {
1009 xtensa_mmu_tlb_ipi();
1010 }
1011 #endif
1012
1013 return ret;
1014 }
1015
arch_mem_domain_thread_remove(struct k_thread * thread)1016 int arch_mem_domain_thread_remove(struct k_thread *thread)
1017 {
1018 struct k_mem_domain *domain = thread->mem_domain_info.mem_domain;
1019
1020 if ((thread->base.user_options & K_USER) == 0) {
1021 return 0;
1022 }
1023
1024 if ((thread->base.thread_state & _THREAD_DEAD) == 0) {
1025 /* Thread is migrating to another memory domain and not
1026 * exiting for good; we weren't called from
1027 * z_thread_abort(). Resetting the stack region will
1028 * take place in the forthcoming thread_add() call.
1029 */
1030 return 0;
1031 }
1032
1033 /* Restore permissions on the thread's stack area since it is no
1034 * longer a member of the domain.
1035 *
1036 * Note that, since every thread must have an associated memory
1037 * domain, removing a thread from domain will be followed by
1038 * adding it back to another. So there is no need to send TLB IPI
1039 * at this point.
1040 */
1041 return reset_region(domain->arch.ptables,
1042 thread->stack_info.start,
1043 thread->stack_info.size, OPTION_NO_TLB_IPI);
1044 }
1045
page_validate(uint32_t * ptables,uint32_t page,uint8_t ring,bool write)1046 static bool page_validate(uint32_t *ptables, uint32_t page, uint8_t ring, bool write)
1047 {
1048 uint8_t asid_ring;
1049 uint32_t rasid, pte, *l2_table;
1050 uint32_t l1_pos = XTENSA_MMU_L1_POS(page);
1051 uint32_t l2_pos = XTENSA_MMU_L2_POS(page);
1052
1053 if (is_pte_illegal(ptables[l1_pos])) {
1054 return false;
1055 }
1056
1057 l2_table = (uint32_t *)(ptables[l1_pos] & XTENSA_MMU_PTE_PPN_MASK);
1058 pte = l2_table[l2_pos];
1059
1060 if (is_pte_illegal(pte)) {
1061 return false;
1062 }
1063
1064 asid_ring = 0;
1065 rasid = xtensa_rasid_get();
1066 for (uint32_t i = 0; i < 4; i++) {
1067 if (XTENSA_MMU_PTE_ASID_GET(pte, rasid) == XTENSA_MMU_RASID_ASID_GET(rasid, i)) {
1068 asid_ring = i;
1069 break;
1070 }
1071 }
1072
1073 if (ring > asid_ring) {
1074 return false;
1075 }
1076
1077 if (write) {
1078 return (XTENSA_MMU_PTE_ATTR_GET((pte)) & XTENSA_MMU_PERM_W) != 0;
1079 }
1080
1081 return true;
1082 }
1083
mem_buffer_validate(const void * addr,size_t size,int write,int ring)1084 static int mem_buffer_validate(const void *addr, size_t size, int write, int ring)
1085 {
1086 int ret = 0;
1087 uint8_t *virt;
1088 size_t aligned_size;
1089 const struct k_thread *thread = arch_current_thread();
1090 uint32_t *ptables = thread_page_tables_get(thread);
1091
1092 /* addr/size arbitrary, fix this up into an aligned region */
1093 k_mem_region_align((uintptr_t *)&virt, &aligned_size,
1094 (uintptr_t)addr, size, CONFIG_MMU_PAGE_SIZE);
1095
1096 for (size_t offset = 0; offset < aligned_size;
1097 offset += CONFIG_MMU_PAGE_SIZE) {
1098 if (!page_validate(ptables, (uint32_t)(virt + offset), ring, write)) {
1099 ret = -1;
1100 break;
1101 }
1102 }
1103
1104 return ret;
1105 }
1106
xtensa_mem_kernel_has_access(void * addr,size_t size,int write)1107 bool xtensa_mem_kernel_has_access(void *addr, size_t size, int write)
1108 {
1109 return mem_buffer_validate(addr, size, write, XTENSA_MMU_KERNEL_RING) == 0;
1110 }
1111
arch_buffer_validate(const void * addr,size_t size,int write)1112 int arch_buffer_validate(const void *addr, size_t size, int write)
1113 {
1114 return mem_buffer_validate(addr, size, write, XTENSA_MMU_USER_RING);
1115 }
1116
xtensa_swap_update_page_tables(struct k_thread * incoming)1117 void xtensa_swap_update_page_tables(struct k_thread *incoming)
1118 {
1119 uint32_t *ptables = incoming->arch.ptables;
1120 struct arch_mem_domain *domain =
1121 &(incoming->mem_domain_info.mem_domain->arch);
1122
1123 xtensa_set_paging(domain->asid, ptables);
1124
1125 #ifdef CONFIG_XTENSA_INVALIDATE_MEM_DOMAIN_TLB_ON_SWAP
1126 struct k_mem_domain *mem_domain = incoming->mem_domain_info.mem_domain;
1127
1128 for (int idx = 0; idx < mem_domain->num_partitions; idx++) {
1129 struct k_mem_partition *part = &mem_domain->partitions[idx];
1130 uintptr_t end = part->start + part->size;
1131
1132 for (uintptr_t addr = part->start; addr < end; addr += CONFIG_MMU_PAGE_SIZE) {
1133 xtensa_dtlb_vaddr_invalidate((void *)addr);
1134 }
1135 }
1136 #endif
1137 }
1138
1139 #endif /* CONFIG_USERSPACE */
1140