Skip to contentSkip to conversation

enable MMU for RISC-V

PATCH Superseded Oleksii Kurochko 3 participants 23 messages Apr 19, 2023 – May 2, 2023 RISC-V

v5 of 9 Superseded Latest is v9 →

lore
Share & tools
lore
#0 lore raw

v5 cover enable MMU for RISC-V

The patch series introduces the following things:
1. Functionality to build the page tables for Xen that map link-time to physical-time location.
2. Check that Xen is less then page size.
3. Check that load addresses don't overlap with linker addresses.
4. Prepare things for proper switch to virtual memory world.
5. Load the built page table into the SATP
6. Enable MMU.

---
Changes in V5:
* rebase the patch series on top of current staging
* Update cover letter: it was removed the info about the patches on which
MMU patch series is based as they were merged to staging
* add new patch with description of VM layout for RISC-V2
* Indent fields of pte_t struct
* Rename addr_to_pte() and ppn_to_paddr() to match their content
---
Changes in V4:
* use GB() macros instead of defining SZ_1G
* hardcode XEN_VIRT_START and add comment (ADDRESS_SPACE_END + 1 - GB(1))
* remove unnecessary 'asm' word at the end of #error
* encapsulate pte_t definition in a struct
* rename addr_to_ppn() to ppn_to_paddr().
* change type of paddr argument from const unsigned long to paddr_t
* pte_to_paddr() update prototype.
* calculate size of Xen binary based on an amount of page tables
* use unsgined int instead of 'uint32_t' instead of uint32_t as
their use isn't warranted.
* remove extern of bss_{start,end} as they aren't used in mm.c anymore
* fix code style
* add argument for HANDLE_PGTBL macros instead of curr_lvl_num variable
* make enable_mmu() as noinline to prevent under link-time optimization
because of the nature of enable_mmu()
* add function to check that SATP_MODE is supported.
* update the commit message
* update setup_initial_pagetables to set correct PTE flags in one pass
instead of calling setup_pte_permissions after setup_initial_pagetables()
as setup_initial_pagetables() isn't used to change permission flags.
---
Changes in V3:
* Update the cover letter message: the patch series isn't depend on
[ RISC-V basic exception handling implementation ] as it was decied
to enable MMU before implementation of exception handling. Also MMU
patch series is based on two other patches which weren't merged [1]
and [2]
- Update the commit message for [ [PATCH v3 1/3]
xen/riscv: introduce setup_initial_pages ].
- update definition of pte_t structure to have a proper size of pte_t in case of RV32.
- update asm/mm.h with new functions and remove unnecessary 'extern'.
- remove LEVEL_* macros as only XEN_PT_LEVEL_* are enough.
- update paddr_to_pte() to receive permissions as an argument.
- add check that map_start & pa_start is properly aligned.
- move defines PAGETABLE_ORDER, PAGETABLE_ENTRIES, PTE_PPN_SHIFT to <asm/page-bits.h>
- Rename PTE_SHIFT to PTE_PPN_SHIFT
- refactor setup_initial_pagetables: map all LINK addresses to LOAD addresses and after setup PTEs permission for sections; update check that linker and load addresses don't overlap.
- refactor setup_initial_mapping: allocate pagetable 'dynamically' if it is necessary.
- rewrite enable_mmu in C; add the check that map_start and pa_start are aligned on 4k boundary.
- update the comment for setup_initial_pagetable funcion
- Add RV_STAGE1_MODE to support different MMU modes.
- update the commit message that MMU is also enabled here
- set XEN_VIRT_START very high to not overlap with load address range
- align bss section
---
Changes in V2:
* Remove {ZEROETH,FIRST,...}_{SHIFT,MASK, SIZE,...} and
introduce instead of them XEN_PT_LEVEL_*() and LEVEL_*
* Rework pt_linear_offset() and pt_index based on XEN_PT_LEVEL_*()
* Remove clear_pagetables() functions as pagetables were zeroed during
.bss initialization
* Rename _setup_initial_pagetables() to setup_initial_mapping()
* Make PTE_DEFAULT equal to RX.
* Update prototype of setup_initial_mapping(..., bool writable) -> setup_initial_mapping(..., UL flags)
* Update calls of setup_initial_mapping according to new prototype
* Remove unnecessary call of:
_setup_initial_pagetables(..., load_addr_start, load_addr_end, load_addr_start, ...)
* Define index* in the loop of setup_initial_mapping
* Remove attribute "__attribute__((section(".entry")))" for setup_initial_pagetables() as we don't have such section
* make arguments of paddr_to_pte() and pte_is_valid() as const.
* use <xen/kernel.h> instead of declaring extern unsigned long _stext, 0etext, _srodata, _erodata
* update 'extern unsigned long __init_begin' to 'extern unsigned long __init_begin[]'
* use aligned() instead of "__attribute__((__aligned__(PAGE_SIZE)))"
* set __section(".bss.page_aligned") for page tables arrays
* fix identatations
* Change '__attribute__((section(".entry")))' to '__init'
* Remove alignment of {map, pa}_start &= XEN_PT_LEVEL_MAP_MASK(0); in setup_inital_mapping() as they should be already aligned.
* Remove clear_pagetables() as initial pagetables will be
zeroed during bss initialization
* Remove __attribute__((section(".entry")) for setup_initial_pagetables()
as there is no such section in xen.lds.S
* Update the argument of pte_is_valid() to "const pte_t *p"
* Remove patch "[PATCH v1 3/3] automation: update RISC-V smoke test" from the patch series as it was introduced simplified approach for RISC-V smoke test by Andrew Cooper
* Add patch [[xen/riscv: remove dummy_bss variable] as there is no any sense in dummy_bss variable after introduction of inittial page tables.
---

Oleksii Kurochko (4):
xen/riscv: add VM space layout
xen/riscv: introduce setup_initial_pages
xen/riscv: setup initial pagetables
xen/riscv: remove dummy_bss variable

 xen/arch/riscv/Makefile                |   1 +
 xen/arch/riscv/include/asm/config.h    |  43 +++-
 xen/arch/riscv/include/asm/mm.h        |   9 +
 xen/arch/riscv/include/asm/page-bits.h |  10 +
 xen/arch/riscv/include/asm/page.h      |  63 +++++
 xen/arch/riscv/mm.c                    | 319 +++++++++++++++++++++++++
 xen/arch/riscv/riscv64/head.S          |   2 +
 xen/arch/riscv/setup.c                 |  22 +-
 xen/arch/riscv/xen.lds.S               |   4 +
 9 files changed, 464 insertions(+), 9 deletions(-)
 create mode 100644 xen/arch/riscv/include/asm/mm.h
 create mode 100644 xen/arch/riscv/include/asm/page.h
 create mode 100644 xen/arch/riscv/mm.c
Signature · 1 line
2.39.2
#22 lore raw

PATCH v5 4/4 xen/riscv: remove dummy_bss variable

After introduction of initial pagetables there is no any sense in dummy_bss variable as bss section will not be empty anymore.

---
Changes in V5:
- Nothing changed. Only rebase
---
Changes in V4:
- Nothing changed. Only rebase
---
Changes in V3:
* patch was introduced in the current one patch series (v3).
---
Changes in V2:
* patch was introduced in the current one patch series (v2).

---
 xen/arch/riscv/setup.c | 8 --------
 1 file changed, 8 deletions(-)
xen/arch/riscv/setup.c +0 -8
index cf5dc5824e..845d18d86f 100644
@@ -8,14 +8,6 @@
 unsigned char __initdata cpu0_boot_stack[STACK_SIZE]
     __aligned(STACK_SIZE);
 
-/*  
- * To be sure that .bss isn't zero. It will simplify code of
- * .bss initialization.
- * TODO:
- *   To be deleted when the first real .bss user appears
- */
-int dummy_bss __attribute__((unused));
-
 void __init noreturn start_xen(unsigned long bootcpu_id,
                                paddr_t dtb_addr)
 {
Signature · 1 line
2.39.2
#1 lore raw

PATCH v5 1/4 xen/riscv: add VM space layout

In reply to Oleksii Kurochko

Also it was added explanation about ignoring of top VA bits

---
Changes in V5:
* the patch was introduced in the current patch series.

---
 xen/arch/riscv/include/asm/config.h | 31 +++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
xen/arch/riscv/include/asm/config.h +31 -0
index 763a922a04..0c860e88ce 100644
@@ -4,6 +4,37 @@
 #include <xen/const.h>
 #include <xen/page-size.h>
 
+/*
+ * RISC-V64 Layout:
+ *
+ * From the riscv-privileged doc:
+ *   When mapping between narrower and wider addresses,
+ *   RISC-V zero-extends a narrower physical address to a wider size.
+ *   The mapping between 64-bit virtual addresses and the 39-bit usable
+ *   address space of Sv39 is not based on zero-extension but instead
+ *   follows an entrenched convention that allows an OS to use one or
+ *   a few of the most-significant bits of a full-size (64-bit) virtual
+ *   address to quickly distinguish user and supervisor address regions.
+ *
+ * It means that:
+ *   top VA bits are simply ignored for the purpose of translating to PA.
+ *
+ * The similar is true for other Sv{32, 39, 48, 57}.
+ *
+ * ============================================================================
+ *    Start addr    |   End addr        |  Size  | VM area description
+ * ============================================================================
+ * FFFFFFFFC0000000 |  FFFFFFFFC0200000 |  2 MB  | Xen
+ * FFFFFFFFC0200000 |  FFFFFFFFC0600000 |  4 MB  | FDT
+ * FFFFFFFFC0600000 |  FFFFFFFFC0800000 |  2 MB  | Fixmap
+ *     .................. unused ..................
+ * 0000003200000000 |  0000007f40000000 | 331 GB | Direct map(L2 slot: 200-509)
+ * 0000003100000000 |  0000003140000000 |  1 GB  | Frametable(L2 slot: 196-197)
+ * 0000003080000000 |  00000030c0000000 |  1 GB  | VMAP (L2 slot: 194-195)
+ *     .................. unused ..................
+ * ============================================================================
+ */
+
 #if defined(CONFIG_RISCV_64)
 # define LONG_BYTEORDER 3
 # define ELFSIZE 64
Signature · 1 line
2.39.2
#21 lore raw

PATCH v5 3/4 xen/riscv: setup initial pagetables

In reply to Oleksii Kurochko

The patch does two thing:
1. Setup initial pagetables.
2. Enable MMU which end up with code in
cont_after_mmu_is_enabled()

---
Changes in V5:
- Nothing changed. Only rebase
---
Changes in V4:
- Nothing changed. Only rebase
---
Changes in V3:
- update the commit message that MMU is also enabled here
- remove early_printk("All set up\n") as it was moved to cont_after_mmu_is_enabled() function after MMU is enabled.
---
Changes in V2:
* Update the commit message

---
 xen/arch/riscv/setup.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
xen/arch/riscv/setup.c +4 -1
index 315804aa87..cf5dc5824e 100644
@@ -21,7 +21,10 @@ void __init noreturn start_xen(unsigned long bootcpu_id,
 {
     early_printk("Hello from C env\n");
 
-    early_printk("All set up\n");
+    setup_initial_pagetables();
+
+    enable_mmu();
+
     for ( ;; )
         asm volatile ("wfi");
 
Signature · 1 line
2.39.2
#13 lore raw

PATCH v5 2/4 xen/riscv: introduce setup_initial_pages

In reply to Oleksii Kurochko

The idea was taken from xvisor but the following changes
were done:
* Use only a minimal part of the code enough to enable MMU
* rename {_}setup_initial_pagetables functions
* add an argument for setup_initial_mapping to have
an opportunity to make set PTE flags.
* update setup_initial_pagetables function to map sections with correct PTE flags.
* Rewrite enable_mmu() to C.
* map linker addresses range to load addresses range without 1:1 mapping. It will be 1:1 only in case when load_start_addr is equal to linker_start_addr.
* add safety checks such as:
* Xen size is less than page size
* linker addresses range doesn't overlap load addresses range
* Rework macros {THIRD,SECOND,FIRST,ZEROETH}_{SHIFT,MASK}
* change PTE_LEAF_DEFAULT to RW instead of RWX.
* Remove phys_offset as it is not used now
* Remove alignment of {map, pa}_start &= XEN_PT_LEVEL_MAP_MASK(0); in setup_inital_mapping() as they should be already aligned. Make a check that {map_pa}_start are aligned.
* Remove clear_pagetables() as initial pagetables will be zeroed during bss initialization
* Remove __attribute__((section(".entry")) for setup_initial_pagetables() as there is no such section in xen.lds.S
* Update the argument of pte_is_valid() to "const pte_t *p"
* Add check that Xen's load address is aligned at 4k boundary
* Refactor setup_initial_pagetables() so it is mapping linker address range to load address range. After setup needed permissions for specific section ( such as .text, .rodata, etc ) otherwise RW permission will be set by default.
* Add function to check that requested SATP_MODE is supported

Origin: [email protected]:xvisor/xvisor.git 9be2fdd7

---
Changes in V5:
* Indent fields of pte_t struct
* Rename addr_to_pte() and ppn_to_paddr() to match their content
---
Changes in V4:
* use GB() macros instead of defining SZ_1G
* hardcode XEN_VIRT_START and add comment (ADDRESS_SPACE_END + 1 - GB(1))
* remove unnecessary 'asm' word at the end of #error
* encapsulate pte_t definition in a struct
* rename addr_to_ppn() to ppn_to_paddr().
* change type of paddr argument from const unsigned long to paddr_t
* pte_to_paddr() update prototype.
* calculate size of Xen binary based on an amount of page tables
* use unsgined int instead of 'uint32_t' instead of uint32_t as
their use isn't warranted.
* remove extern of bss_{start,end} as they aren't used in mm.c anymore
* fix code style
* add argument for HANDLE_PGTBL macros instead of curr_lvl_num variable
* make enable_mmu() as noinline to prevent under link-time optimization
because of the nature of enable_mmu()
* add function to check that SATP_MODE is supported.
* update the commit message
* update setup_initial_pagetables to set correct PTE flags in one pass
instead of calling setup_pte_permissions after setup_initial_pagetables()
as setup_initial_pagetables() isn't used to change permission flags.
---
Changes in V3:
- update definition of pte_t structure to have a proper size of pte_t
in case of RV32.
- update asm/mm.h with new functions and remove unnecessary 'extern'.
- remove LEVEL_* macros as only XEN_PT_LEVEL_* are enough.
- update paddr_to_pte() to receive permissions as an argument.
- add check that map_start & pa_start is properly aligned.
- move defines PAGETABLE_ORDER, PAGETABLE_ENTRIES, PTE_PPN_SHIFT to <asm/page-bits.h>
- Rename PTE_SHIFT to PTE_PPN_SHIFT
- refactor setup_initial_pagetables: map all LINK addresses to LOAD addresses
and after setup PTEs permission for sections; update check that linker
and load addresses don't overlap.
- refactor setup_initial_mapping: allocate pagetable 'dynamically' if it is necessary.
- rewrite enable_mmu in C; add the check that map_start and pa_start are
aligned on 4k boundary.
- update the comment for setup_initial_pagetable funcion
- Add RV_STAGE1_MODE to support different MMU modes
- set XEN_VIRT_START very high to not overlap with load address range
- align bss section
---
Changes in V2:
* update the commit message:
* Remove {ZEROETH,FIRST,...}_{SHIFT,MASK, SIZE,...} and
introduce instead of them XEN_PT_LEVEL_*() and LEVEL_*
* Rework pt_linear_offset() and pt_index based on XEN_PT_LEVEL_*()
* Remove clear_pagetables() functions as pagetables were zeroed during
.bss initialization
* Rename _setup_initial_pagetables() to setup_initial_mapping()
* Make PTE_DEFAULT equal to RX.
* Update prototype of setup_initial_mapping(..., bool writable) -> setup_initial_mapping(..., UL flags)
* Update calls of setup_initial_mapping according to new prototype
* Remove unnecessary call of:
_setup_initial_pagetables(..., load_addr_start, load_addr_end, load_addr_start, ...)
* Define index* in the loop of setup_initial_mapping
* Remove attribute "__attribute__((section(".entry")))" for setup_initial_pagetables() as we don't have such section
* make arguments of paddr_to_pte() and pte_is_valid() as const.
* make xen_second_pagetable static.
* use <xen/kernel.h> instead of declaring extern unsigned long _stext, 0etext, _srodata, _erodata
* update 'extern unsigned long __init_begin' to 'extern unsigned long __init_begin[]'
* use aligned() instead of "__attribute__((__aligned__(PAGE_SIZE)))"
* set __section(".bss.page_aligned") for page tables arrays
* fix identatations
* Change '__attribute__((section(".entry")))' to '__init'
* Remove phys_offset as it isn't used now.
* Remove alignment of {map, pa}_start &= XEN_PT_LEVEL_MAP_MASK(0); in setup_inital_mapping() as they should be already aligned.
* Remove clear_pagetables() as initial pagetables will be
zeroed during bss initialization
* Remove __attribute__((section(".entry")) for setup_initial_pagetables()
as there is no such section in xen.lds.S
* Update the argument of pte_is_valid() to "const pte_t *p"
---

 xen/arch/riscv/Makefile                |   1 +
 xen/arch/riscv/include/asm/config.h    |  12 +-
 xen/arch/riscv/include/asm/mm.h        |   9 +
 xen/arch/riscv/include/asm/page-bits.h |  10 +
 xen/arch/riscv/include/asm/page.h      |  63 +++++
 xen/arch/riscv/mm.c                    | 319 +++++++++++++++++++++++++
 xen/arch/riscv/riscv64/head.S          |   2 +
 xen/arch/riscv/setup.c                 |  11 +
 xen/arch/riscv/xen.lds.S               |   4 +
 9 files changed, 430 insertions(+), 1 deletion(-)
 create mode 100644 xen/arch/riscv/include/asm/mm.h
 create mode 100644 xen/arch/riscv/include/asm/page.h
 create mode 100644 xen/arch/riscv/mm.c
xen/arch/riscv/Makefile +1 -0
index 443f6bf15f..956ceb02df 100644
@@ -1,5 +1,6 @@
 obj-$(CONFIG_EARLY_PRINTK) += early_printk.o
 obj-y += entry.o
+obj-y += mm.o
 obj-$(CONFIG_RISCV_64) += riscv64/
 obj-y += sbi.o
 obj-y += setup.o
xen/arch/riscv/include/asm/config.h +11 -1
index 0c860e88ce..4cd4f7a701 100644
@@ -70,12 +70,22 @@
   name:
 #endif
 
-#define XEN_VIRT_START  _AT(UL, 0x80200000)
+#ifdef CONFIG_RISCV_64
+#define XEN_VIRT_START 0xFFFFFFFFC0000000 /* (_AC(-1, UL) + 1 - GB(1)) */
+#else
+#error "RV32 isn't supported"
+#endif
 
 #define SMP_CACHE_BYTES (1 << 6)
 
 #define STACK_SIZE PAGE_SIZE
 
+#ifdef CONFIG_RISCV_64
+#define RV_STAGE1_MODE SATP_MODE_SV39
+#else
+#define RV_STAGE1_MODE SATP_MODE_SV32
+#endif
+
 #endif /* __RISCV_CONFIG_H__ */
 /*
  * Local variables:
xen/arch/riscv/include/asm/mm.h new file +9 -0
new file mode 100644
index 0000000000..e16ce66fae
@@ -0,0 +1,9 @@
+#ifndef _ASM_RISCV_MM_H
+#define _ASM_RISCV_MM_H
+
+void setup_initial_pagetables(void);
+
+void enable_mmu(void);
+void cont_after_mmu_is_enabled(void);
+
+#endif /* _ASM_RISCV_MM_H */
xen/arch/riscv/include/asm/page-bits.h +10 -0
index 1801820294..0879a527f2 100644
@@ -1,6 +1,16 @@
 #ifndef __RISCV_PAGE_BITS_H__
 #define __RISCV_PAGE_BITS_H__
 
+#ifdef CONFIG_RISCV_64
+#define PAGETABLE_ORDER         (9)
+#else /* CONFIG_RISCV_32 */
+#define PAGETABLE_ORDER         (10)
+#endif
+
+#define PAGETABLE_ENTRIES       (1 << PAGETABLE_ORDER)
+
+#define PTE_PPN_SHIFT           10
+
 #define PAGE_SHIFT              12 /* 4 KiB Pages */
 #define PADDR_BITS              56 /* 44-bit PPN */
 
xen/arch/riscv/include/asm/page.h new file +63 -0

63 lines not on this page · raw message

xen/arch/riscv/mm.c new file +319 -0

319 lines not on this page · raw message

xen/arch/riscv/riscv64/head.S +2 -0
index 8887f0cbd4..b3309d902c 100644
@@ -1,4 +1,5 @@
 #include <asm/asm.h>
+#include <asm/asm-offsets.h>
 #include <asm/riscv_encoding.h>
 
         .section .text.header, "ax", %progbits
@@ -32,3 +33,4 @@ ENTRY(start)
         add     sp, sp, t0
 
         tail    start_xen
+
xen/arch/riscv/setup.c +11 -0
index 3786f337e0..315804aa87 100644
@@ -2,6 +2,7 @@
 #include <xen/init.h>
 
 #include <asm/early_printk.h>
+#include <asm/mm.h>
 
 /* Xen stack for bringing up the first CPU. */
 unsigned char __initdata cpu0_boot_stack[STACK_SIZE]
@@ -26,3 +27,13 @@ void __init noreturn start_xen(unsigned long bootcpu_id,
 
     unreachable();
 }
+
+void __init noreturn cont_after_mmu_is_enabled(void)
+{
+    early_printk("All set up\n");
+
+    for ( ;; )
+        asm volatile ("wfi");
+
+    unreachable();
+}
xen/arch/riscv/xen.lds.S +4 -0
index 31e0d3576c..2f7f76bee6 100644
@@ -136,6 +136,7 @@ SECTIONS
     . = ALIGN(POINTER_ALIGN);
     __init_end = .;
 
+    . = ALIGN(PAGE_SIZE);
     .bss : {                     /* BSS */
         __bss_start = .;
         *(.bss.stack_aligned)
@@ -172,3 +173,6 @@ ASSERT(IS_ALIGNED(__bss_end,        POINTER_ALIGN), "__bss_end is misaligned")
 
 ASSERT(!SIZEOF(.got),      ".got non-empty")
 ASSERT(!SIZEOF(.got.plt),  ".got.plt non-empty")
+
+ASSERT(_end - _start <= MB(2), "Xen too large for early-boot assumptions")
+
Signature · 1 line
2.39.2
#2 lore raw

Re: [PATCH v5 1/4] xen/riscv: add VM space layout

In reply to Oleksii Kurochko
Quoted 12 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/config.h +6 -0
@@ -4,6 +4,37 @@
 #include <xen/const.h>
 #include <xen/page-size.h>
 
+/*
+ * RISC-V64 Layout:
+ *
+ * From the riscv-privileged doc:
+ *   When mapping between narrower and wider addresses,
+ *   RISC-V zero-extends a narrower physical address to a wider size.

xen/arch/riscv/include/asm/config.h line 22

Quoted 10 lines
xen/arch/riscv/include/asm/config.h +10 -0
+ *   The mapping between 64-bit virtual addresses and the 39-bit usable
+ *   address space of Sv39 is not based on zero-extension but instead
+ *   follows an entrenched convention that allows an OS to use one or
+ *   a few of the most-significant bits of a full-size (64-bit) virtual
+ *   address to quickly distinguish user and supervisor address regions.
+ *
+ * It means that:
+ *   top VA bits are simply ignored for the purpose of translating to PA.
+ *
+ * The similar is true for other Sv{32, 39, 48, 57}.

Personally I find it odd that Sv32 is mentioned here (there's no truncation / aliasing there aiui), and that Sv39 is mentioned here again (when that's what the earlier paragraph talks about).

xen/arch/riscv/include/asm/config.h line 29

Quoted 6 lines
xen/arch/riscv/include/asm/config.h +6 -0
+ * ============================================================================
+ *    Start addr    |   End addr        |  Size  | VM area description
+ * ============================================================================
+ * FFFFFFFFC0000000 |  FFFFFFFFC0200000 |  2 MB  | Xen
+ * FFFFFFFFC0200000 |  FFFFFFFFC0600000 |  4 MB  | FDT
+ * FFFFFFFFC0600000 |  FFFFFFFFC0800000 |  2 MB  | Fixmap

These are all L2 slot 511 aiui, which may be worth mentioning especially since the top bits don't match the top bits further down in the table (because of the aliasing).

xen/arch/riscv/include/asm/config.h line 29

Quoted 1 line
xen/arch/riscv/include/asm/config.h +1 -0
+ *     .................. unused ..................

This is covering slot 510, which again may be worth mentioning.

xen/arch/riscv/include/asm/config.h line 32

Quoted 2 lines
xen/arch/riscv/include/asm/config.h +2 -0
+ * 0000003200000000 |  0000007f40000000 | 331 GB | Direct map(L2 slot: 200-509)
+ * 0000003100000000 |  0000003140000000 |  1 GB  | Frametable(L2 slot: 196-197)

1Gb is, if I'm not mistaken, a single L2 slot.

Also assuming a 32-byte struct page_info (I don't think you'll get away with less than that, when even Arm32 requires this much), there's a mismatch between direct map and frame table size: With 4k pages, the scaling factor would be 128 if I'm not mistaken. So perhaps you really mean 3Gb here to cover for (slightly more than) the 331Gb of memory you mean to be able to map?

xen/arch/riscv/include/asm/config.h line 34

Quoted 2 lines
xen/arch/riscv/include/asm/config.h +2 -0
+ * 0000003080000000 |  00000030c0000000 |  1 GB  | VMAP (L2 slot: 194-195)
+ *     .................. unused ..................

There are further unused regions between these three entries, while imo will want making explicit (for the avoidance of doubt, if nothing else).

Jan

#14 lore raw

Re: [PATCH v5 2/4] xen/riscv: introduce setup_initial_pages

In reply to Oleksii Kurochko
Quoted 8 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/page-bits.h +2 -0
@@ -1,6 +1,16 @@
 #ifndef __RISCV_PAGE_BITS_H__
 #define __RISCV_PAGE_BITS_H__
 
+#ifdef CONFIG_RISCV_64
+#define PAGETABLE_ORDER         (9)

xen/arch/riscv/include/asm/page-bits.h line 15

Quoted 10 lines
xen/arch/riscv/include/asm/page-bits.h +8 -0
+#else /* CONFIG_RISCV_32 */
+#define PAGETABLE_ORDER         (10)
+#endif
+
+#define PAGETABLE_ENTRIES       (1 << PAGETABLE_ORDER)
+
+#define PTE_PPN_SHIFT           10
+
 #define PAGE_SHIFT              12 /* 4 KiB Pages */
 #define PADDR_BITS              56 /* 44-bit PPN */

Personally I think these two would better remain at the top. But maybe that's just me ...

Quoted 35 lines
xen/arch/riscv/include/asm/page.h new file +32 -0
@@ -0,0 +1,63 @@
+#ifndef _ASM_RISCV_PAGE_H
+#define _ASM_RISCV_PAGE_H
+
+#include <xen/const.h>
+#include <xen/types.h>
+
+#define VPN_MASK                    ((unsigned long)(PAGETABLE_ENTRIES - 1))
+
+#define XEN_PT_LEVEL_ORDER(lvl)     ((lvl) * PAGETABLE_ORDER)
+#define XEN_PT_LEVEL_SHIFT(lvl)     (XEN_PT_LEVEL_ORDER(lvl) + PAGE_SHIFT)
+#define XEN_PT_LEVEL_SIZE(lvl)      (_AT(paddr_t, 1) << XEN_PT_LEVEL_SHIFT(lvl))
+#define XEN_PT_LEVEL_MAP_MASK(lvl)  (~(XEN_PT_LEVEL_SIZE(lvl) - 1))
+#define XEN_PT_LEVEL_MASK(lvl)      (VPN_MASK << XEN_PT_LEVEL_SHIFT(lvl))
+
+#define PTE_VALID                   BIT(0, UL)
+#define PTE_READABLE                BIT(1, UL)
+#define PTE_WRITABLE                BIT(2, UL)
+#define PTE_EXECUTABLE              BIT(3, UL)
+#define PTE_USER                    BIT(4, UL)
+#define PTE_GLOBAL                  BIT(5, UL)
+#define PTE_ACCESSED                BIT(6, UL)
+#define PTE_DIRTY                   BIT(7, UL)
+#define PTE_RSW                     (BIT(8, UL) | BIT(9, UL))
+
+#define PTE_LEAF_DEFAULT            (PTE_VALID | PTE_READABLE | PTE_WRITABLE)
+#define PTE_TABLE                   (PTE_VALID)
+
+/* Calculate the offsets into the pagetables for a given VA */
+#define pt_linear_offset(lvl, va)   ((va) >> XEN_PT_LEVEL_SHIFT(lvl))
+
+#define pt_index(lvl, va) pt_linear_offset(lvl, (va) & XEN_PT_LEVEL_MASK(lvl))
+

xen/arch/riscv/include/asm/page.h line 42

Quoted 10 lines
xen/arch/riscv/include/asm/page.h new file +10 -0
+/* Page Table entry */
+typedef struct {
+#ifdef CONFIG_RISCV_64
+    uint64_t pte;
+#else
+    uint32_t pte;
+#endif
+} pte_t;
+
+#define pte_to_addr(x) (((x) >> PTE_PPN_SHIFT) << PAGE_SHIFT)

This will be at risk of overflow for RV32 without a cast to paddr_t (which I expect would be a 64-bit type on RV32 just like it is on RV64).

Quoted 8 lines
xen/arch/riscv/include/asm/page.h new file +8 -0
+#define addr_to_pte(x) (((x) >> PAGE_SHIFT) << PTE_PPN_SHIFT)
+
+static inline pte_t paddr_to_pte(const paddr_t paddr,
+                                 const unsigned long permissions)
+{
+    unsigned long tmp = addr_to_pte(paddr);
+    return (pte_t) { .pte = tmp | permissions };
+}

xen/arch/riscv/include/asm/page.h line 61

Quoted 10 lines
xen/arch/riscv/include/asm/page.h new file +10 -0
+
+static inline paddr_t pte_to_paddr(const pte_t pte)
+{
+    return pte_to_addr(pte.pte);
+}
+
+static inline bool pte_is_valid(const pte_t p)
+{
+    return p.pte & PTE_VALID;
+}

A remark on all of the "const" here: It's fine if you want to keep them, but generally we care about const-correctness only for pointed-to types. Scalar and compound parameter values are owned by called function anyway, so all the "const" achieves is that the function can't alter its own argument(s).

Quoted 6 lines
xen/arch/riscv/mm.c new file +3 -0
@@ -0,0 +1,319 @@
+#include <xen/compiler.h>
+#include <xen/init.h>
+#include <xen/kernel.h>

xen/arch/riscv/mm.c line 13

Quoted 10 lines
xen/arch/riscv/mm.c new file +10 -0
+
+#include <asm/early_printk.h>
+#include <asm/config.h>
+#include <asm/csr.h>
+#include <asm/mm.h>
+#include <asm/page.h>
+#include <asm/processor.h>
+
+struct mmu_desc {
+    unsigned long num_levels;

Isn't "unsigned int" sufficient here?

Quoted 5 lines
xen/arch/riscv/mm.c new file +5 -0
+/*
+ * It is expected that Xen won't be more then 2 MB.
+ * The check in xen.lds.S guarantees that.
+ * At least 4 page (in case when Sv48 or Sv57 are used )
+ * tables are needed to cover 2 MB. One for each page level

xen/arch/riscv/mm.c line 40

Quoted 10 lines
xen/arch/riscv/mm.c new file +10 -0
+ * table with PAGE_SIZE = 4 Kb
+ *
+ * One L0 page table can cover 2 MB
+ * (512 entries of one page table * PAGE_SIZE).
+ *
+ * It might be needed one more page table in case when
+ * Xen load address isn't 2 MB aligned.
+ *
+ */
+#define PGTBL_INITIAL_COUNT     (5)

On x86 we have a CONFIG_PAGING_LEVELS constant. If you had something like this as well, this 5 would better match the comment as ((CONFIG_PAGING_LEVELS - 1) + 1), avoiding to make space for the two levels you won't need as long as only Sv39 is really meant to be used.

Quoted 26 lines
xen/arch/riscv/mm.c new file +25 -0
+#define PGTBL_ENTRY_AMOUNT  (PAGE_SIZE / sizeof(pte_t))
+
+pte_t __section(".bss.page_aligned") __aligned(PAGE_SIZE)
+stage1_pgtbl_root[PGTBL_ENTRY_AMOUNT];
+
+pte_t __section(".bss.page_aligned") __aligned(PAGE_SIZE)
+stage1_pgtbl_nonroot[PGTBL_INITIAL_COUNT * PGTBL_ENTRY_AMOUNT];
 
+#define HANDLE_PGTBL(curr_lvl_num)                                          \
+    index = pt_index(curr_lvl_num, page_addr);                              \
+    if ( pte_is_valid(pgtbl[index]) )                                       \
+    {                                                                       \
+        /* Find L{ 0-3 } table */                                           \
+        pgtbl = (pte_t *)pte_to_paddr(pgtbl[index]);                        \
+    }                                                                       \
+    else                                                                    \
+    {                                                                       \
+        /* Allocate new L{0-3} page table */                                \
+        if ( mmu_desc->pgtbl_count == PGTBL_INITIAL_COUNT )                 \
+        {                                                                   \
+            early_printk("(XEN) No initial table available\n");             \
+            /* panic(), BUG() or ASSERT() aren't ready now. */              \
+            die();                                                          \
+        }                                                                   \
+        mmu_desc->pgtbl_count++;                                            \
+        pgtbl[index] = paddr_to_pte((unsigned long)mmu_desc->next_pgtbl,    \

xen/arch/riscv/mm.c line 77

Quoted 10 lines
xen/arch/riscv/mm.c new file +10 -0
+                                    PTE_VALID);                             \
+        pgtbl = mmu_desc->next_pgtbl;                                       \
+        mmu_desc->next_pgtbl += PGTBL_ENTRY_AMOUNT;                         \
+    }
+
+static void __init setup_initial_mapping(struct mmu_desc *mmu_desc,
+                                         unsigned long map_start,
+                                         unsigned long map_end,
+                                         unsigned long pa_start,
+                                         unsigned long permissions)

Wouldn't the last one more sensibly be "unsigned int"?

Quoted 18 lines
xen/arch/riscv/mm.c new file +18 -0
+{
+    unsigned int index;
+    pte_t *pgtbl;
+    unsigned long page_addr;
+    pte_t pte_to_be_written;
+    unsigned long paddr;
+    unsigned long tmp_permissions;
+
+    if ( (unsigned long)_start % XEN_PT_LEVEL_SIZE(0) )
+    {
+        early_printk("(XEN) Xen should be loaded at 4k boundary\n");
+        die();
+    }
+
+    if ( map_start & ~XEN_PT_LEVEL_MAP_MASK(0) ||
+         pa_start & ~XEN_PT_LEVEL_MAP_MASK(0) )
+    {
+        early_printk("(XEN) map and pa start addresses should be aligned\n");

xen/arch/riscv/mm.c line 105

Quoted 10 lines
xen/arch/riscv/mm.c new file +10 -0
+        /* panic(), BUG() or ASSERT() aren't ready now. */
+        die();
+    }
+
+    page_addr = map_start;
+    while ( page_addr < map_end )
+    {
+        pgtbl = mmu_desc->pgtbl_base;
+
+        switch (mmu_desc->num_levels)

Nit: Style (missing blanks).

xen/arch/riscv/mm.c

Quoted 2 lines
xen/arch/riscv/mm.c new file +2 -0
+        {
+            case 4: /* Level 3 */

Nit: Indentation of case labels matches that of the opening brace in our style.

Quoted 23 lines
xen/arch/riscv/mm.c new file +23 -0
+                HANDLE_PGTBL(3);
+            case 3: /* Level 2 */
+                HANDLE_PGTBL(2);
+            case 2: /* Level 1 */
+                HANDLE_PGTBL(1);
+            case 1: /* Level 0 */
+                index = pt_index(0, page_addr);
+                paddr = (page_addr - map_start) + pa_start;
+
+                tmp_permissions = permissions;
+
+                if ( is_kernel_text(LINK_TO_LOAD(page_addr)) ||
+                     is_kernel_inittext(LINK_TO_LOAD(page_addr)) )
+                    tmp_permissions =
+                        PTE_EXECUTABLE | PTE_READABLE | PTE_VALID;
+
+                if ( is_kernel_rodata(LINK_TO_LOAD(page_addr)) )
+                    tmp_permissions = PTE_READABLE | PTE_VALID;
+
+                pte_to_be_written = paddr_to_pte(paddr, tmp_permissions);
+
+                if ( !pte_is_valid(pgtbl[index]) )
+                    pgtbl[index] = pte_to_be_written;

xen/arch/riscv/mm.c line 140

Quoted 10 lines
xen/arch/riscv/mm.c new file +10 -0
+                else
+                {
+                    /*
+                    * get an adresses of current pte and that one to
+                    * be written without permission flags
+                    */
+                    unsigned long curr_pte =
+                        pgtbl[index].pte & ~((1 << PTE_PPN_SHIFT) - 1);
+
+                    pte_to_be_written.pte &= ~((1 << PTE_PPN_SHIFT) - 1);

If you mean to only compare addresses, why don't you use pte_to_paddr()? Question though is whether it's correct to ignore permission differenes. I'd expect you only want to mask off PTE_ACCESSED and PTE_DIRTY.

xen/arch/riscv/mm.c line 145

Quoted 4 lines
xen/arch/riscv/mm.c new file +4 -0
+                    if ( curr_pte != pte_to_be_written.pte )
+                    {
+                        early_printk("PTE that is intended to write isn't the"
+                                    "same that the once are overwriting\n");

Nit: One-off indentation. As to the message text - I take it that's temporary only anyway, and hence there's little point thinking about improving it?

xen/arch/riscv/mm.c line 153

Quoted 8 lines
xen/arch/riscv/mm.c new file +8 -0
+                        /* panic(), <asm/bug.h> aren't ready now. */
+                        die();
+                    }
+                }
+        }
+
+        /* Point to next page */
+        page_addr += XEN_PT_LEVEL_SIZE(0);

Seeing this as well as the loop heading - maybe more suitable as a for(;;) loop?

xen/arch/riscv/mm.c

Quoted 2 lines
xen/arch/riscv/mm.c new file +2 -0
+    }
+}

Since HANDLE_PGTBL() is strictly for use above only, I think you'd better #undef it here.

Quoted 39 lines
xen/arch/riscv/mm.c new file +39 -0
+static void __init calc_pgtbl_lvls_num(struct  mmu_desc *mmu_desc)
+{
+    unsigned long satp_mode = RV_STAGE1_MODE;
+
+    /* Number of page table levels */
+    switch (satp_mode)
+    {
+        case SATP_MODE_SV32:
+            mmu_desc->num_levels = 2;
+            break;
+        case SATP_MODE_SV39:
+            mmu_desc->num_levels = 3;
+            break;
+        case SATP_MODE_SV48:
+            mmu_desc->num_levels = 4;
+            break;
+        default:
+            early_printk("(XEN) Unsupported SATP_MODE\n");
+            die();
+    }
+}
+
+static bool __init check_pgtbl_mode_support(struct mmu_desc *mmu_desc,
+                                            unsigned long load_start,
+                                            unsigned long satp_mode)
+{
+    bool is_mode_supported = false;
+    unsigned int index;
+    unsigned int page_table_level = (mmu_desc->num_levels - 1);
+    unsigned level_map_mask = XEN_PT_LEVEL_MAP_MASK(page_table_level);
+
+    unsigned long aligned_load_start = load_start & level_map_mask;
+    unsigned long aligned_page_size = XEN_PT_LEVEL_SIZE(page_table_level);
+    unsigned long xen_size = (unsigned long)(_end - start);
+
+    if ( (load_start + xen_size) > (aligned_load_start + aligned_page_size) )
+    {
+        early_printk("please place Xen to be in range of PAGE_SIZE "
+                     "where PAGE_SIZE is XEN_PT_LEVEL_SIZE( {L3 | L2 | L1} ) "

xen/arch/riscv/mm.c line 205

Quoted 10 lines
xen/arch/riscv/mm.c new file +10 -0
+                     "depending on expected SATP_MODE \n"
+                     "XEN_PT_LEVEL_SIZE is defined in <asm/page.h>\n");
+        die();
+    }
+
+    index = pt_index(page_table_level, aligned_load_start);
+    stage1_pgtbl_root[index] = paddr_to_pte(aligned_load_start,
+                                            PTE_LEAF_DEFAULT | PTE_EXECUTABLE);
+
+    asm volatile("sfence.vma");

Nit (here and several times again below): Style (missing three blanks, as "asm" is a keyword).

xen/arch/riscv/mm.c line 217

Quoted 12 lines
xen/arch/riscv/mm.c new file +12 -0
+    csr_write(CSR_SATP,
+              ((unsigned long)stage1_pgtbl_root >> PAGE_SHIFT) |
+              satp_mode << SATP_MODE_SHIFT);
+
+    if ( (csr_read(CSR_SATP) >> SATP_MODE_SHIFT) == satp_mode )
+        is_mode_supported = true;
+
+    /* Clean MMU root page table and disable MMU */
+    stage1_pgtbl_root[index] = paddr_to_pte(0x0, 0x0);
+
+    csr_write(CSR_SATP, 0);
+    asm volatile("sfence.vma");

I guess what you do in this function could do with some more comments. Looks like you're briefly enabling the MMU to check that what you wrote to SATP you can also read back. (Isn't there a register reporting whether the feature is available?)

If so, I think you cannot clear the stage1_pgtbl_root[] slot before you've disabled the MMU again.

(As a minor aspect, I'd like to encourage you to write plain zero just as 0, not as 0x0, unless used in contexts where other hex numbers nearby make this desirable.)

Quoted 10 lines
xen/arch/riscv/mm.c new file +10 -0
+    return is_mode_supported;
+}
+
+/*
+ * setup_initial_pagetables:
+ *
+ * Build the page tables for Xen that map the following:
+ *  1. Calculate page table's level numbers.
+ *  2. Init mmu description structure.
+ *  3. Check that linker addresses range doesn't overlap

xen/arch/riscv/mm.c line 238

Quoted 10 lines
xen/arch/riscv/mm.c new file +10 -0
+ *     with load addresses range
+ *  4. Map all linker addresses and load addresses ( it shouldn't
+ *     be 1:1 mapped and will be 1:1 mapped only in case if
+ *     linker address is equal to load address ) with
+ *     RW permissions by default.
+ *  5. Setup proper PTE permissions for each section.
+ */
+void __init setup_initial_pagetables(void)
+{
+    struct mmu_desc mmu_desc = { 0, 0, NULL, 0 };

Just {} ought to do as initializer, but if you want to spell things out, then please use 0 / NULL consistently for integral / pointer type fields.

xen/arch/riscv/mm.c

Quoted 2 lines
xen/arch/riscv/mm.c new file +2 -0
+    /*
+     * Access to _{stard, end } is always PC-relative

I guess you mean _start. For just a leading underscore I also don't think using this braced form is useful.

xen/arch/riscv/mm.c line 253

Quoted 12 lines
xen/arch/riscv/mm.c new file +12 -0
+     * thereby when access them we will get load adresses
+     * of start and end of Xen
+     * To get linker addresses LOAD_TO_LINK() is required
+     * to use
+     */
+    unsigned long load_start    = (unsigned long)_start;
+    unsigned long load_end      = (unsigned long)_end;
+    unsigned long linker_start  = LOAD_TO_LINK(load_start);
+    unsigned long linker_end    = LOAD_TO_LINK(load_end);
+
+    if ( (linker_start != load_start) &&
+         (linker_start <= load_end) && (load_start <= linker_end) ) {

Nit: Style (brace placement).

Quoted 33 lines
xen/arch/riscv/mm.c new file +33 -0
+        early_printk("(XEN) linker and load address ranges overlap\n");
+        die();
+    }
+
+    calc_pgtbl_lvls_num(&mmu_desc);
+
+    if ( !check_pgtbl_mode_support(&mmu_desc, load_start, RV_STAGE1_MODE) )
+    {
+        early_printk("requested MMU mode isn't supported by CPU\n"
+                     "Please choose different in <asm/config.h>\n");
+        die();
+    }
+
+    mmu_desc.pgtbl_base = stage1_pgtbl_root;
+    mmu_desc.next_pgtbl = stage1_pgtbl_nonroot;
+
+    setup_initial_mapping(&mmu_desc,
+                          linker_start,
+                          linker_end,
+                          load_start,
+                          PTE_LEAF_DEFAULT);
+}
+
+void __init noinline enable_mmu()
+{
+    /*
+     * Calculate a linker time address of the mmu_is_enabled
+     * label and update CSR_STVEC with it.
+     * MMU is configured in a way where linker addresses are mapped
+     * on load addresses so in a case when linker addresses are not equal
+     * to load addresses, after MMU is enabled, it will cause
+     * an exception and jump to linker time addresses.
+     * Otherwise if load addresses are equal to linker addresses the code

xen/arch/riscv/mm.c line 296

Quoted 10 lines
xen/arch/riscv/mm.c new file +10 -0
+     * after mmu_is_enabled label will be executed without exception.
+     */
+    csr_write(CSR_STVEC, LOAD_TO_LINK((unsigned long)&&mmu_is_enabled));
+
+    /* Ensure page table writes precede loading the SATP */
+    asm volatile("sfence.vma");
+
+    /* Enable the MMU and load the new pagetable for Xen */
+    csr_write(CSR_SATP,
+              ((unsigned long)stage1_pgtbl_root >> PAGE_SHIFT) |

Please try to avoid open-coding of existing constructs: Here you mean either PFN_DOWN() or paddr_to_pfn() (you see, we have even two). (As I notice I did overlook at least similar earlier instance.)

xen/arch/riscv/mm.c line 300

Quoted 4 lines
xen/arch/riscv/mm.c new file +4 -0
+              RV_STAGE1_MODE << SATP_MODE_SHIFT);
+
+    asm volatile(".align 2");
+      mmu_is_enabled:

How in the world is one to spot this label? Yes, it shouldn't be entirely unindented. But it also should be indented less than the surrounding code (with the exception of switch() statement case labels, where a non-case label might be intended the same as a case ones). Our rule of thumb is to indent such labels by a single space.

xen/arch/riscv/mm.c line 310

Quoted 10 lines
xen/arch/riscv/mm.c new file +10 -0
+    /*
+     * Stack should be re-inited as:
+     * 1. Right now an address of the stack is relative to load time
+     *    addresses what will cause an issue in case of load start address
+     *    isn't equal to linker start address.
+     * 2. Addresses in stack are all load time relative which can be an
+     *    issue in case when load start address isn't equal to linker
+     *    start address.
+     */
+    asm volatile ("mv sp, %0" : : "r"((unsigned long)cpu0_boot_stack + STACK_SIZE));

Nit: Style (overly long line).

What's worse - I don't think it is permitted to alter sp in the middle of a function. The compiler may maintain local variables on the stack which don't correspond to any programmer specified ones, including pointer ones which point into the stack frame. This is specifically why both x86 and Arm have switch_stack_and_jump() macros.

xen/arch/riscv/mm.c line 316

Quoted 5 lines
xen/arch/riscv/mm.c new file +5 -0
+    /*
+     * We can't return to the caller because the stack was reseted
+     * and it may have stash some variable on the stack.
+     * Jump to a brand new function as the stack was reseted
+    */

Nit: Style (indentation).

Quoted 14 lines
xen/arch/riscv/mm.c new file +3 -0
+    cont_after_mmu_is_enabled();
+}
+
xen/arch/riscv/riscv64/head.S +1 -0
index 8887f0cbd4..b3309d902c 100644
@@ -1,4 +1,5 @@
 #include <asm/asm.h>
+#include <asm/asm-offsets.h>
 #include <asm/riscv_encoding.h>
 
         .section .text.header, "ax", %progbits

xen/arch/riscv/riscv64/head.S ENTRY(start) · line 36

Quoted 4 lines
xen/arch/riscv/riscv64/head.S +1 -0
@@ -32,3 +33,4 @@ ENTRY(start)
         add     sp, sp, t0
 
         tail    start_xen
+

???

xen/arch/riscv/xen.lds.S SECTIONS · line 142

Quoted 10 lines
xen/arch/riscv/xen.lds.S +1 -0
@@ -136,6 +136,7 @@ SECTIONS
     . = ALIGN(POINTER_ALIGN);
     __init_end = .;
 
+    . = ALIGN(PAGE_SIZE);
     .bss : {                     /* BSS */
         __bss_start = .;
         *(.bss.stack_aligned)

Why do you need this? You properly use __aligned(PAGE_SIZE) for the page tables you define, and PAGE_SIZE wouldn't be enough here anyway if STACK_SIZE > PAGE_SIZE (as .bss.stack_aligned comes first). The only time you'd need such an ALIGN() is if the following label (__bss_start in this case) needed to be aligned at a certain boundary. (I'm a little puzzled though that __bss_start isn't [immediately] preceded by ". = ALIGN(POINTER_ALIGN);" - didn't .bss clearing rely on such alignment?)

Jan

author
#3 lore raw

Re: [PATCH v5 1/4] xen/riscv: add VM space layout

In reply to Jan Beulich
Quoted 28 lines · Jan Beulich
Quoted 27 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/config.h +0 -0
@@ -4,6 +4,37 @@
  #include <xen/const.h>
  #include <xen/page-size.h>


+/*
+ * RISC-V64 Layout:
+ *
+ * From the riscv-privileged doc:
+ *   When mapping between narrower and wider addresses,
+ *   RISC-V zero-extends a narrower physical address to a wider size.
+ *   The mapping between 64-bit virtual addresses and the 39-bit usable
+ *   address space of Sv39 is not based on zero-extension but instead
+ *   follows an entrenched convention that allows an OS to use one or
+ *   a few of the most-significant bits of a full-size (64-bit) virtual
+ *   address to quickly distinguish user and supervisor address regions.
+ *
+ * It means that:
+ *   top VA bits are simply ignored for the purpose of translating to PA.

Quoted 8 lines
Quoted 2 lines

+ *
+ * The similar is true for other Sv{32, 39, 48, 57}.

Personally I find it odd that Sv32 is mentioned here (there's no truncation /
aliasing there aiui), and that Sv39 is mentioned here again (when that's what
the earlier paragraph talks about).

It looks that I wrote bad explanation.

I meant that all the mentioned above ( that usable address space isn't based on zero-extension ) works for Sv{39, 48, 57} except size of usable address space ( 39-bit, 48-bit and 57-bit usable address space of 64-bit virtual address space ).

And I agree that this is not for Sv32 as it covers full 32-bit virtual address space

Quoted 13 lines
Quoted 9 lines

+ *
===================================================================
=========
+ *    Start addr    |   End addr        |  Size  | VM area description
+ *
===================================================================
=========

Quoted 3 lines
+ * FFFFFFFFC0000000 |  FFFFFFFFC0200000 |  2 MB  | Xen
+ * FFFFFFFFC0200000 |  FFFFFFFFC0600000 |  4 MB  | FDT
+ * FFFFFFFFC0600000 |  FFFFFFFFC0800000 |  2 MB  | Fixmap
Quoted 5 lines

These are all L2 slot 511 aiui, which may be worth mentioning especially since
the top bits don't match the top bits further down in the table (because of the
aliasing).

Than I'll add one more column where I'll put slot number

Quoted 11 lines
Quoted 2 lines

+ *     .................. unused ..................

This is covering slot 510, which again may be worth mentioning.

Quoted 4 lines

+ * 0000003200000000 |  0000007f40000000 | 331 GB | Direct map(L2
slot: 200-509)
+ * 0000003100000000 |  0000003140000000 |  1 GB  | Frametable(L2
slot: 196-197)

1Gb is, if I'm not mistaken, a single L2 slot.

Yeah, it can be misunderstood. I meant [196, 197), so 197 isn't included. I'll update the table.

Quoted 12 lines

Also assuming a 32-byte struct page_info (I don't think you'll get away with
less than that, when even Arm32 requires this much), there's a mismatch
between direct map and frame table size: With 4k pages, the scaling factor
would be 128 if I'm not mistaken. So perhaps you really mean 3Gb here to
cover for (slightly more than) the 331Gb of memory you mean to be able to
map?

For RV64 page_info size will be 56-byte and 32-byte for RV32 but you are right it should 3 Gb in that case what will be enough ( taking into account both available sizes of page_info structure ). Thanks for the catch.

Quoted 8 lines
Quoted 4 lines

+ * 0000003080000000 |  00000030c0000000 |  1 GB  | VMAP (L2 slot:
194-195)
+ *     .................. unused ..................

There are further unused regions between these three entries, while imo will
want making explicit (for the avoidance of doubt, if nothing else).

Yeah, there are some. I'll add them explicitly.

~ Oleksii

author
#15 lore raw

Re: [PATCH v5 2/4] xen/riscv: introduce setup_initial_pages

In reply to Jan Beulich
Quoted 15 lines · Jan Beulich
Quoted 14 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/page-bits.h +0 -0
@@ -1,6 +1,16 @@
  #ifndef __RISCV_PAGE_BITS_H__
  #define __RISCV_PAGE_BITS_H__

xen/arch/riscv/include/asm/page-bits.h +8 -0
+#ifdef CONFIG_RISCV_64
+#define PAGETABLE_ORDER         (9)
+#else /* CONFIG_RISCV_32 */
+#define PAGETABLE_ORDER         (10)
+#endif
+
+#define PAGETABLE_ENTRIES       (1 << PAGETABLE_ORDER)
+
Quoted 8 lines
Quoted 4 lines
xen/arch/riscv/include/asm/page-bits.h +2 -0
+#define PTE_PPN_SHIFT           10
+

 #define PAGE_SHIFT              12 /* 4 KiB Pages */ #define PADDR_BITS              56 /* 44-bit PPN */

Personally I think these two would better remain at the top. But maybe
that's just me ...

I'm ok to remain them at the top.

Quoted 50 lines
Quoted 50 lines
xen/arch/riscv/include/asm/page.h new file +7 -0
@@ -0,0 +1,63 @@
+#ifndef _ASM_RISCV_PAGE_H
+#define _ASM_RISCV_PAGE_H
+
+#include <xen/const.h>
+#include <xen/types.h>
+
+#define VPN_MASK                    ((unsigned

long)(PAGETABLE_ENTRIES - 1))

xen/arch/riscv/include/asm/page.h new file +3 -0
+
+#define XEN_PT_LEVEL_ORDER(lvl)     ((lvl) * PAGETABLE_ORDER)
+#define XEN_PT_LEVEL_SHIFT(lvl)     (XEN_PT_LEVEL_ORDER(lvl) +

PAGE_SHIFT)
+#define XEN_PT_LEVEL_SIZE(lvl)      (_AT(paddr_t, 1) << XEN_PT_LEVEL_SHIFT(lvl))
+#define XEN_PT_LEVEL_MAP_MASK(lvl)  (~(XEN_PT_LEVEL_SIZE(lvl) - 1))
+#define XEN_PT_LEVEL_MASK(lvl)      (VPN_MASK << XEN_PT_LEVEL_SHIFT(lvl))

xen/arch/riscv/include/asm/page.h new file +12 -0
+
+#define PTE_VALID                   BIT(0, UL)
+#define PTE_READABLE                BIT(1, UL)
+#define PTE_WRITABLE                BIT(2, UL)
+#define PTE_EXECUTABLE              BIT(3, UL)
+#define PTE_USER                    BIT(4, UL)
+#define PTE_GLOBAL                  BIT(5, UL)
+#define PTE_ACCESSED                BIT(6, UL)
+#define PTE_DIRTY                   BIT(7, UL)
+#define PTE_RSW                     (BIT(8, UL) | BIT(9, UL))
+
+#define PTE_LEAF_DEFAULT            (PTE_VALID | PTE_READABLE |

PTE_WRITABLE)

xen/arch/riscv/include/asm/page.h new file +4 -0
+#define PTE_TABLE                   (PTE_VALID)
+
+/* Calculate the offsets into the pagetables for a given VA */
+#define pt_linear_offset(lvl, va)   ((va) >>

XEN_PT_LEVEL_SHIFT(lvl))

xen/arch/riscv/include/asm/page.h new file +2 -0
+
+#define pt_index(lvl, va) pt_linear_offset(lvl, (va) &

XEN_PT_LEVEL_MASK(lvl))

xen/arch/riscv/include/asm/page.h new file +7 -0
+
+/* Page Table entry */
+typedef struct {
+#ifdef CONFIG_RISCV_64
+    uint64_t pte;
+#else
+    uint32_t pte;
Quoted 8 lines

xen/arch/riscv/include/asm/page.h line 42

Quoted 4 lines
xen/arch/riscv/include/asm/page.h new file +4 -0
+#endif
+} pte_t;
+
+#define pte_to_addr(x) (((x) >> PTE_PPN_SHIFT) << PAGE_SHIFT)

This will be at risk of overflow for RV32 without a cast to paddr_t (which
I expect would be a 64-bit type on RV32 just like it is on RV64).

Yeah, paddr_t is u64 for both RV32 and RV64.
I'll add cast to paddr_t to avoid possible risk of overflow.

Quoted 20 lines
Quoted 9 lines
xen/arch/riscv/include/asm/page.h new file +8 -0
+#define addr_to_pte(x) (((x) >> PAGE_SHIFT) << PTE_PPN_SHIFT)
+
+static inline pte_t paddr_to_pte(const paddr_t paddr,
+                                 const unsigned long permissions)
+{
+    unsigned long tmp = addr_to_pte(paddr);
+    return (pte_t) { .pte = tmp | permissions };
+}

xen/arch/riscv/include/asm/page.h line 61

Quoted 10 lines
xen/arch/riscv/include/asm/page.h new file +10 -0
+
+static inline paddr_t pte_to_paddr(const pte_t pte)
+{
+    return pte_to_addr(pte.pte);
+}
+
+static inline bool pte_is_valid(const pte_t p)
+{
+    return p.pte & PTE_VALID;
+}
Quoted 8 lines

A remark on all of the "const" here: It's fine if you want to keep them,
but generally we care about const-correctness only for pointed-to types.
Scalar and compound parameter values are owned by called function anyway,
so all the "const" achieves is that the function can't alter its own argument(s).

Then it doesn't make for the current case and removing them will simplify paddr_to_pte function. So I prefer to remove them.

Quoted 11 lines
Quoted 11 lines
xen/arch/riscv/mm.c new file +7 -0
@@ -0,0 +1,319 @@
+#include <xen/compiler.h>
+#include <xen/init.h>
+#include <xen/kernel.h>
+
+#include <asm/early_printk.h>
+#include <asm/config.h>
+#include <asm/csr.h>
Quoted 8 lines

xen/arch/riscv/mm.c line 13

Quoted 6 lines
xen/arch/riscv/mm.c new file +6 -0
+#include <asm/mm.h>
+#include <asm/page.h>
+#include <asm/processor.h>
+
+struct mmu_desc {
+    unsigned long num_levels;

Isn't "unsigned int" sufficient here?

Yes, it will be sufficient.

Quoted 14 lines
Quoted 14 lines
xen/arch/riscv/mm.c new file +13 -0
+/*
+ * It is expected that Xen won't be more then 2 MB.
+ * The check in xen.lds.S guarantees that.
+ * At least 4 page (in case when Sv48 or Sv57 are used )
+ * tables are needed to cover 2 MB. One for each page level
+ * table with PAGE_SIZE = 4 Kb
+ *
+ * One L0 page table can cover 2 MB
+ * (512 entries of one page table * PAGE_SIZE).
+ *
+ * It might be needed one more page table in case when
+ * Xen load address isn't 2 MB aligned.
+ *
Quoted 8 lines

xen/arch/riscv/mm.c line 40

Quoted 2 lines
xen/arch/riscv/mm.c new file +2 -0
+ */
+#define PGTBL_INITIAL_COUNT     (5)

On x86 we have a CONFIG_PAGING_LEVELS constant. If you had something like this as well, this 5 would better match the comment as ((CONFIG_PAGING_LEVELS - 1) + 1), avoiding to make space for the two levels you won't need as long as only Sv39 is really meant to be used.

Thanks for note. I'll use CONFIG_PAGING_LEVELS too.

Quoted 56 lines
Quoted 56 lines
xen/arch/riscv/mm.c new file +8 -0
+#define PGTBL_ENTRY_AMOUNT  (PAGE_SIZE / sizeof(pte_t))
+
+pte_t __section(".bss.page_aligned") __aligned(PAGE_SIZE)
+stage1_pgtbl_root[PGTBL_ENTRY_AMOUNT];
+
+pte_t __section(".bss.page_aligned") __aligned(PAGE_SIZE)
+stage1_pgtbl_nonroot[PGTBL_INITIAL_COUNT * PGTBL_ENTRY_AMOUNT];
 
+#define

HANDLE_PGTBL(curr_lvl_num)
\
+    index = pt_index(curr_lvl_num,
page_addr);                              \
+    if ( pte_is_valid(pgtbl[index])
)                                       \
+
{
     \
+        /* Find L{ 0-3 } table
*/                                           \
+        pgtbl = (pte_t
*)pte_to_paddr(pgtbl[index]);                        \
+
}
     \
+
else
     \
+
{
     \
+        /* Allocate new L{0-3} page table
*/                                \
+        if ( mmu_desc->pgtbl_count == PGTBL_INITIAL_COUNT )                 \
+
{
\
+            early_printk("(XEN) No initial table available\n");             \
+            /* panic(), BUG() or ASSERT() aren't ready now. */              \
+
die();                                                          \
+
}
\
+        mmu_desc-

Quoted 1 line

pgtbl_count++;                                            \

+        pgtbl[index] = paddr_to_pte((unsigned long)mmu_desc-

Quoted 1 line

next_pgtbl,    \

+
PTE_VALID);                             \
+        pgtbl = mmu_desc-

Quoted 1 line

next_pgtbl;                                       \

Quoted 13 lines
Quoted 11 lines

+        mmu_desc->next_pgtbl +=
PGTBL_ENTRY_AMOUNT;                         \
+    }

xen/arch/riscv/mm.c new file +2 -0
+
+static void __init setup_initial_mapping(struct mmu_desc

*mmu_desc,
+                                         unsigned long map_start, +                                         unsigned long map_end, +                                         unsigned long pa_start, +                                         unsigned long permissions)

Wouldn't the last one more sensibly be "unsigned int"?

It would. Thanks, I'll update the code.

Quoted 25 lines
Quoted 25 lines
xen/arch/riscv/mm.c new file +11 -0
+{
+    unsigned int index;
+    pte_t *pgtbl;
+    unsigned long page_addr;
+    pte_t pte_to_be_written;
+    unsigned long paddr;
+    unsigned long tmp_permissions;
+
+    if ( (unsigned long)_start % XEN_PT_LEVEL_SIZE(0) )
+    {
+        early_printk("(XEN) Xen should be loaded at 4k

boundary\n");
+        die();
+    }
+
+    if ( map_start & ~XEN_PT_LEVEL_MAP_MASK(0) ||
+         pa_start & ~XEN_PT_LEVEL_MAP_MASK(0) )
+    {
+        early_printk("(XEN) map and pa start addresses should be aligned\n");
+        /* panic(), BUG() or ASSERT() aren't ready now. */ +        die();
+    }
+

Quoted 8 lines
Quoted 6 lines

+    page_addr = map_start;
+    while ( page_addr < map_end )
+    {
+        pgtbl = mmu_desc->pgtbl_base;
+
+        switch (mmu_desc->num_levels)

Nit: Style (missing blanks).

Thanks. Ill update.

Quoted 7 lines
Quoted 3 lines

+        {
+            case 4: /* Level 3 */

Nit: Indentation of case labels matches that of the opening brace in our
style.

Sure. Missed that.

Quoted 33 lines
Quoted 33 lines

+                HANDLE_PGTBL(3);
+            case 3: /* Level 2 */
+                HANDLE_PGTBL(2);
+            case 2: /* Level 1 */
+                HANDLE_PGTBL(1);
+            case 1: /* Level 0 */
+                index = pt_index(0, page_addr);
+                paddr = (page_addr - map_start) + pa_start;

xen/arch/riscv/mm.c new file +12 -0
+
+                tmp_permissions = permissions;
+
+                if ( is_kernel_text(LINK_TO_LOAD(page_addr)) ||
+                     is_kernel_inittext(LINK_TO_LOAD(page_addr)) )
+                    tmp_permissions =
+                        PTE_EXECUTABLE | PTE_READABLE | PTE_VALID;
+
+                if ( is_kernel_rodata(LINK_TO_LOAD(page_addr)) )
+                    tmp_permissions = PTE_READABLE | PTE_VALID;
+
+                pte_to_be_written = paddr_to_pte(paddr,

tmp_permissions);
+
+                if ( !pte_is_valid(pgtbl[index]) )
+                    pgtbl[index] = pte_to_be_written; +                else
+                {
+                    /*
+                    * get an adresses of current pte and that one to
+                    * be written without permission flags +                    */
+                    unsigned long curr_pte =

Quoted 8 lines
Quoted 5 lines

+                        pgtbl[index].pte & ~((1 << PTE_PPN_SHIFT)
- 1);
+
+                    pte_to_be_written.pte &= ~((1 << PTE_PPN_SHIFT) - 1);

If you mean to only compare addresses, why don't you use pte_to_paddr()?

Yes, it will be better to use pte_to_paddr().

Quoted 3 lines

Question though is whether it's correct to ignore permission differenes.
I'd expect you only want to mask off PTE_ACCESSED and PTE_DIRTY.

Initially I would like to do rough check but probably you are right and it will be better to mask off only PTE_ACCESSED and PTE_DIRTY.

Quoted 11 lines
Quoted 7 lines

+                    if ( curr_pte != pte_to_be_written.pte ) +                    {
+                        early_printk("PTE that is intended to write isn't the"
+                                    "same that the once are overwriting\n");

Nit: One-off indentation. As to the message text - I take it that's temporary only anyway, and hence there's little point thinking about improving it?

Probably it would be more clear:
"PTE overridden has occurred"

Quoted 11 lines
Quoted 10 lines

+                        /* panic(), <asm/bug.h> aren't ready now. */
+                        die();
+                    }
+                }
+        }
+
+        /* Point to next page */
+        page_addr += XEN_PT_LEVEL_SIZE(0);

Quoted 2 lines

Seeing this as well as the loop heading - maybe more suitable as a for(;;) loop?

I am not sure that I understand the benefits of changing "while ( page_addr < map_end )" to "for(;;)".
Could you please explain me what the benefits are?

Quoted 64 lines
Quoted 3 lines

+    }
+}

Since HANDLE_PGTBL() is strictly for use above only, I think you'd better
#undef it here.

Quoted 56 lines
xen/arch/riscv/mm.c new file +23 -0
+static void __init calc_pgtbl_lvls_num(struct  mmu_desc *mmu_desc)
+{
+    unsigned long satp_mode = RV_STAGE1_MODE;
+
+    /* Number of page table levels */
+    switch (satp_mode)
+    {
+        case SATP_MODE_SV32:
+            mmu_desc->num_levels = 2;
+            break;
+        case SATP_MODE_SV39:
+            mmu_desc->num_levels = 3;
+            break;
+        case SATP_MODE_SV48:
+            mmu_desc->num_levels = 4;
+            break;
+        default:
+            early_printk("(XEN) Unsupported SATP_MODE\n");
+            die();
+    }
+}
+
+static bool __init check_pgtbl_mode_support(struct mmu_desc

*mmu_desc,
+                                            unsigned long load_start,
+                                            unsigned long satp_mode)
+{
+    bool is_mode_supported = false;
+    unsigned int index;
+    unsigned int page_table_level = (mmu_desc->num_levels - 1); +    unsigned level_map_mask = XEN_PT_LEVEL_MAP_MASK(page_table_level);
+
+    unsigned long aligned_load_start = load_start & level_map_mask;
+    unsigned long aligned_page_size = XEN_PT_LEVEL_SIZE(page_table_level);
+    unsigned long xen_size = (unsigned long)(_end - start); +
+    if ( (load_start + xen_size) > (aligned_load_start + aligned_page_size) )
+    {
+        early_printk("please place Xen to be in range of PAGE_SIZE "
+                     "where PAGE_SIZE is XEN_PT_LEVEL_SIZE( {L3 | L2 | L1} ) "
+                     "depending on expected SATP_MODE \n" +                     "XEN_PT_LEVEL_SIZE is defined in <asm/page.h>\n");
+        die();
+    }
+
+    index = pt_index(page_table_level, aligned_load_start); +    stage1_pgtbl_root[index] = paddr_to_pte(aligned_load_start,

Quoted 8 lines
Quoted 4 lines

+                                            PTE_LEAF_DEFAULT | PTE_EXECUTABLE);
+
+    asm volatile("sfence.vma");

Nit (here and several times again below): Style (missing three blanks, as
"asm" is a keyword).

Thanks. I'll add them

Quoted 12 lines
Quoted 12 lines

+    csr_write(CSR_SATP,
+              ((unsigned long)stage1_pgtbl_root >> PAGE_SHIFT) | +              satp_mode << SATP_MODE_SHIFT);

xen/arch/riscv/mm.c new file +8 -0
+
+    if ( (csr_read(CSR_SATP) >> SATP_MODE_SHIFT) == satp_mode )
+        is_mode_supported = true;
+
+    /* Clean MMU root page table and disable MMU */
+    stage1_pgtbl_root[index] = paddr_to_pte(0x0, 0x0);
+
+    csr_write(CSR_SATP, 0);
Quoted 8 lines
Quoted 1 line

+    asm volatile("sfence.vma");

I guess what you do in this function could do with some more comments.
Looks like you're briefly enabling the MMU to check that what you wrote
to SATP you can also read back. (Isn't there a register reporting whether the feature is available?)

I supposed that it has to be but I couldn't find a register in docs.

Quoted 9 lines

If so, I think you cannot clear the stage1_pgtbl_root[] slot before you've disabled the MMU again.

(As a minor aspect, I'd like to encourage you to write plain zero just
as 0, not as 0x0, unless used in contexts where other hex numbers nearby
make this desirable.)

You are right it should be cleared after csr_write(CSR_SATP, 0)

Quoted 18 lines
Quoted 18 lines

+    return is_mode_supported;

xen/arch/riscv/mm.c new file +16 -0
+}
+
+/*
+ * setup_initial_pagetables:
+ *
+ * Build the page tables for Xen that map the following:
+ *  1. Calculate page table's level numbers.
+ *  2. Init mmu description structure.
+ *  3. Check that linker addresses range doesn't overlap
+ *     with load addresses range
+ *  4. Map all linker addresses and load addresses ( it shouldn't
+ *     be 1:1 mapped and will be 1:1 mapped only in case if
+ *     linker address is equal to load address ) with
+ *     RW permissions by default.
+ *  5. Setup proper PTE permissions for each section.
+ */
Quoted 8 lines

xen/arch/riscv/mm.c line 238

Quoted 3 lines
xen/arch/riscv/mm.c new file +3 -0
+void __init setup_initial_pagetables(void)
+{
+    struct mmu_desc mmu_desc = { 0, 0, NULL, 0 };

Just {} ought to do as initializer, but if you want to spell things out,
then please use 0 / NULL consistently for integral / pointer type fields.

Thanks.

Quoted 7 lines
Quoted 3 lines

+    /*
+     * Access to _{stard, end } is always PC-relative

I guess you mean _start. For just a leading underscore I also don't think
using this braced form is useful.

OK then I'll update the comment w/o usage of braced form.

Quoted 15 lines
Quoted 14 lines

+     * thereby when access them we will get load adresses +     * of start and end of Xen
+     * To get linker addresses LOAD_TO_LINK() is required +     * to use
+     */
+    unsigned long load_start    = (unsigned long)_start; +    unsigned long load_end      = (unsigned long)_end; +    unsigned long linker_start  = LOAD_TO_LINK(load_start); +    unsigned long linker_end    = LOAD_TO_LINK(load_end); +
+    if ( (linker_start != load_start) &&
+         (linker_start <= load_end) && (load_start <= linker_end) ) {

Quoted 1 line

Nit: Style (brace placement).

Thanks,

Quoted 49 lines
Quoted 49 lines

+        early_printk("(XEN) linker and load address ranges overlap\n");
+        die();
+    }

xen/arch/riscv/mm.c new file +4 -0
+
+    calc_pgtbl_lvls_num(&mmu_desc);
+
+    if ( !check_pgtbl_mode_support(&mmu_desc, load_start,

RV_STAGE1_MODE) )
+    {
+        early_printk("requested MMU mode isn't supported by CPU\n" +                     "Please choose different in <asm/config.h>\n");
+        die();
+    }

xen/arch/riscv/mm.c new file +17 -0
+
+    mmu_desc.pgtbl_base = stage1_pgtbl_root;
+    mmu_desc.next_pgtbl = stage1_pgtbl_nonroot;
+
+    setup_initial_mapping(&mmu_desc,
+                          linker_start,
+                          linker_end,
+                          load_start,
+                          PTE_LEAF_DEFAULT);
+}
+
+void __init noinline enable_mmu()
+{
+    /*
+     * Calculate a linker time address of the mmu_is_enabled
+     * label and update CSR_STVEC with it.
+     * MMU is configured in a way where linker addresses are

mapped
+     * on load addresses so in a case when linker addresses are not equal
+     * to load addresses, after MMU is enabled, it will cause +     * an exception and jump to linker time addresses. +     * Otherwise if load addresses are equal to linker addresses the code
+     * after mmu_is_enabled label will be executed without exception.
+     */
+    csr_write(CSR_STVEC, LOAD_TO_LINK((unsigned long)&&mmu_is_enabled));

xen/arch/riscv/mm.c new file +4 -0
+
+    /* Ensure page table writes precede loading the SATP */
+    asm volatile("sfence.vma");
+
Quoted 8 lines
Quoted 3 lines

+    /* Enable the MMU and load the new pagetable for Xen */ +    csr_write(CSR_SATP,
+              ((unsigned long)stage1_pgtbl_root >> PAGE_SHIFT) |

Please try to avoid open-coding of existing constructs: Here you mean either PFN_DOWN() or paddr_to_pfn() (you see, we have even two). (As I
notice I did overlook at least similar earlier instance.)

Sure. Thanks.

Quoted 6 lines
Quoted 5 lines

+              RV_STAGE1_MODE << SATP_MODE_SHIFT); +
+    asm volatile(".align 2");
+      mmu_is_enabled:

Quoted 9 lines

How in the world is one to spot this label? Yes, it shouldn't be entirely
unindented. But it also should be indented less than the surrounding code
(with the exception of switch() statement case labels, where a non- case
label might be intended the same as a case ones). Our rule of thumb is to
indent such labels by a single space.

Thanks. It looks like I misunderstood previous comment about label indentation.

Quoted 19 lines
Quoted 16 lines

+    /*
+     * Stack should be re-inited as:
+     * 1. Right now an address of the stack is relative to load time
+     *    addresses what will cause an issue in case of load start address
+     *    isn't equal to linker start address.
+     * 2. Addresses in stack are all load time relative which can be an
+     *    issue in case when load start address isn't equal to linker
+     *    start address.
+     */
+    asm volatile ("mv sp, %0" : : "r"((unsigned long)cpu0_boot_stack + STACK_SIZE));

Nit: Style (overly long line).

Quoted 9 lines

What's worse - I don't think it is permitted to alter sp in the middle of
a function. The compiler may maintain local variables on the stack which
don't correspond to any programmer specified ones, including pointer ones
which point into the stack frame. This is specifically why both x86 and
Arm have switch_stack_and_jump() macros.

but the macros (from ARM) looks equal to the code mentioned above:
#define switch_stack_and_jump(stack, fn) do {

\
    asm volatile ("mov sp,%0; b " STR(fn) : : "r" (stack), "X" (fn) :
"memory" ); \
    unreachable();                                                    

\
} while ( false )

Here is part of disassembled enable_mmu():

ffffffffc004aedc:       18079073                csrw    satp,a5
ffffffffc004aee0:       00016797                auipc   a5,0x16
ffffffffc004aee4:       12078793                addi    a5,a5,288
ffffffffc004aee8:       813e                    mv      sp,a5
ffffffffc004af00:       0f4000ef                jal    

ra,ffffffffc004aff4 <cont_after_mmu_is_enabled>
...

Quoted 8 lines
Quoted 6 lines

+    /*
+     * We can't return to the caller because the stack was reseted +     * and it may have stash some variable on the stack. +     * Jump to a brand new function as the stack was reseted +    */

Nit: Style (indentation).

Thanks.

Quoted 14 lines
Quoted 14 lines

+    cont_after_mmu_is_enabled();

xen/arch/riscv/mm.c new file +2 -0
+}
+
xen/arch/riscv/riscv64/head.S +1 -0
index 8887f0cbd4..b3309d902c 100644
@@ -1,4 +1,5 @@
  #include <asm/asm.h>
+#include <asm/asm-offsets.h>
  #include <asm/riscv_encoding.h>

Quoted 8 lines
Quoted 6 lines

         .section .text.header, "ax", %progbits

xen/arch/riscv/riscv64/head.S +0 -0
@@ -32,3 +33,4 @@ ENTRY(start)

         add     sp, sp, t0

         tail    start_xen
+

???

Shouldn't it be the one empty line at the end of a file?

Quoted 12 lines
Quoted 11 lines
xen/arch/riscv/xen.lds.S +0 -0
@@ -136,6 +136,7 @@ SECTIONS
      . = ALIGN(POINTER_ALIGN);
      __init_end = .;


+    . = ALIGN(PAGE_SIZE);
     .bss : {                     /* BSS */
         __bss_start = .;
         *(.bss.stack_aligned)

Quoted 8 lines

Why do you need this? You properly use __aligned(PAGE_SIZE) for the page tables you define, and PAGE_SIZE wouldn't be enough here anyway if STACK_SIZE > PAGE_SIZE (as .bss.stack_aligned comes first). The only time you'd need such an ALIGN() is if the following label (__bss_start in this case) needed to be aligned at a certain boundary. (I'm a little puzzled though that __bss_start isn't [immediately] preceded by ". = ALIGN(POINTER_ALIGN);" - didn't .bss clearing rely on such alignment?)

ALIGN(PAGE_SIZE) isn't needed anymore.
I used it to have 4k aligned physical address for PTE when I mapped each section separately ( it was so in the previous verstion of MMU patch series )

Regarding ". = ALIGN(POINTER_ALIGN);" I would say that it is enough to have aligned __bss_end ( what was done ) to be sure that we can clear __SIZEOF_POINTER__ bytes each iteration of .bss clearing loop and don't worry that size of .bss section may not be divisible by __SIZEOF_POINTER__.

~ Oleksii

#4 lore raw

Re: [PATCH v5 1/4] xen/riscv: add VM space layout

In reply to Oleksii
Quoted 48 lines · Oleksii
Quoted 13 lines · Jan Beulich
Quoted 11 lines · Oleksii Kurochko

+ *
===================================================================
=========
+ *    Start addr    |   End addr        |  Size  | VM area description
+ *
===================================================================
=========

+ * FFFFFFFFC0000000 |  FFFFFFFFC0200000 |  2 MB  | Xen
+ * FFFFFFFFC0200000 |  FFFFFFFFC0600000 |  4 MB  | FDT
+ * FFFFFFFFC0600000 |  FFFFFFFFC0800000 |  2 MB  | Fixmap
Quoted 5 lines

These are all L2 slot 511 aiui, which may be worth mentioning especially since
the top bits don't match the top bits further down in the table (because of the
aliasing).

Than I'll add one more column where I'll put slot number

Quoted 11 lines
Quoted 2 lines

+ *     .................. unused ..................

This is covering slot 510, which again may be worth mentioning.

Quoted 4 lines

+ * 0000003200000000 |  0000007f40000000 | 331 GB | Direct map(L2
slot: 200-509)
+ * 0000003100000000 |  0000003140000000 |  1 GB  | Frametable(L2
slot: 196-197)

1Gb is, if I'm not mistaken, a single L2 slot.

Yeah, it can be misunderstood. I meant [196, 197), so 197 isn't included. I'll update the table.

Quoted 12 lines

Also assuming a 32-byte struct page_info (I don't think you'll get away with
less than that, when even Arm32 requires this much), there's a mismatch
between direct map and frame table size: With 4k pages, the scaling factor
would be 128 if I'm not mistaken. So perhaps you really mean 3Gb here to
cover for (slightly more than) the 331Gb of memory you mean to be able to
map?

Quoted 3 lines

For RV64 page_info size will be 56-byte and 32-byte for RV32 but you are right it should 3 Gb in that case what will be enough ( taking into account both available sizes of page_info structure ).

Since you say "both": I don't expect you will want to use 3Gb for RV32 there? The table is, at least for now, for RV64 / Sv39 only anyway.

Jan

#6 lore raw

Re: [PATCH v5 1/4] xen/riscv: add VM space layout

In reply to Oleksii
Quoted 48 lines · Oleksii
Quoted 13 lines · Jan Beulich
Quoted 11 lines · Oleksii Kurochko

+ *
===================================================================
=========
+ *    Start addr    |   End addr        |  Size  | VM area description
+ *
===================================================================
=========

+ * FFFFFFFFC0000000 |  FFFFFFFFC0200000 |  2 MB  | Xen
+ * FFFFFFFFC0200000 |  FFFFFFFFC0600000 |  4 MB  | FDT
+ * FFFFFFFFC0600000 |  FFFFFFFFC0800000 |  2 MB  | Fixmap
Quoted 5 lines

These are all L2 slot 511 aiui, which may be worth mentioning especially since
the top bits don't match the top bits further down in the table (because of the
aliasing).

Than I'll add one more column where I'll put slot number

Quoted 11 lines
Quoted 2 lines

+ *     .................. unused ..................

This is covering slot 510, which again may be worth mentioning.

Quoted 4 lines

+ * 0000003200000000 |  0000007f40000000 | 331 GB | Direct map(L2
slot: 200-509)
+ * 0000003100000000 |  0000003140000000 |  1 GB  | Frametable(L2
slot: 196-197)

1Gb is, if I'm not mistaken, a single L2 slot.

Yeah, it can be misunderstood. I meant [196, 197), so 197 isn't included. I'll update the table.

Quoted 12 lines

Also assuming a 32-byte struct page_info (I don't think you'll get away with
less than that, when even Arm32 requires this much), there's a mismatch
between direct map and frame table size: With 4k pages, the scaling factor
would be 128 if I'm not mistaken. So perhaps you really mean 3Gb here to
cover for (slightly more than) the 331Gb of memory you mean to be able to
map?

Quoted 3 lines

For RV64 page_info size will be 56-byte and 32-byte for RV32 but you are right it should 3 Gb in that case what will be enough ( taking into account both available sizes of page_info structure ).

As to the plan to it being 56 bytes (i.e. like on Arm): Arm forever has had a 64-bit padding field at the end. My best guess is that the field was introduced to have a 32-byte struct on Arm32. But then why artificially increase the struct from 48 to 56 bytes on Arm64? And hence why have the same oddity on RV64?

Jan

#16 lore raw

Re: [PATCH v5 2/4] xen/riscv: introduce setup_initial_pages

In reply to Oleksii
Quoted 12 lines · Oleksii
Quoted 11 lines · Jan Beulich
Quoted 9 lines · Oleksii Kurochko

+                        /* panic(), <asm/bug.h> aren't ready now. */
+                        die();
+                    }
+                }
+        }
+
+        /* Point to next page */
+        page_addr += XEN_PT_LEVEL_SIZE(0);

Quoted 5 lines
Quoted 2 lines

Seeing this as well as the loop heading - maybe more suitable as a for(;;) loop?

I am not sure that I understand the benefits of changing "while ( page_addr < map_end )" to "for(;;)".
Could you please explain me what the benefits are?

The common case of using while() is in situations where one cannot use for(). for() is (imo) preferable in all cases where the third of the controlling expressions isn't empty (and is to be carried out after every iteration): Any use of "continue" inside the loop will then properly effect loop progress. (Of course there are cases where this behavior isn't wanted; that's where while() may come into play then.)

Quoted 19 lines
Quoted 11 lines
Quoted 11 lines

+    csr_write(CSR_SATP,
+              ((unsigned long)stage1_pgtbl_root >> PAGE_SHIFT) | +              satp_mode << SATP_MODE_SHIFT);

xen/arch/riscv/mm.c new file +8 -0
+
+    if ( (csr_read(CSR_SATP) >> SATP_MODE_SHIFT) == satp_mode )
+        is_mode_supported = true;
+
+    /* Clean MMU root page table and disable MMU */
+    stage1_pgtbl_root[index] = paddr_to_pte(0x0, 0x0);
+
+    csr_write(CSR_SATP, 0);
Quoted 8 lines
Quoted 1 line

+    asm volatile("sfence.vma");

I guess what you do in this function could do with some more comments.
Looks like you're briefly enabling the MMU to check that what you wrote
to SATP you can also read back. (Isn't there a register reporting whether the feature is available?)

Quoted 1 line

I supposed that it has to be but I couldn't find a register in docs.

Well, yes, interestingly the register is marked WARL, so apparently intended to by used for probing like you do. (I find the definition of WARL a little odd though, as such writes supposedly aren't necessarily value preserving. For SATP this might mean that translation is enabled by a write of an unsupported mode, with a different number of levels. This isn't going to work very well, I'm afraid.)

Quoted 27 lines
Quoted 18 lines
Quoted 7 lines

+    /*
+     * Stack should be re-inited as:
+     * 1. Right now an address of the stack is relative to load time
+     *    addresses what will cause an issue in case of load start address
+     *    isn't equal to linker start address.

Quoted 8 lines

+     * 2. Addresses in stack are all load time relative which can be an
+     *    issue in case when load start address isn't equal to linker
+     *    start address.
+     */
+    asm volatile ("mv sp, %0" : : "r"((unsigned long)cpu0_boot_stack + STACK_SIZE));

Nit: Style (overly long line).

Quoted 9 lines

What's worse - I don't think it is permitted to alter sp in the middle of
a function. The compiler may maintain local variables on the stack which
don't correspond to any programmer specified ones, including pointer ones
which point into the stack frame. This is specifically why both x86 and
Arm have switch_stack_and_jump() macros.

Quoted 5 lines

but the macros (from ARM) looks equal to the code mentioned above:
#define switch_stack_and_jump(stack, fn) do {

\
    asm volatile ("mov sp,%0; b " STR(fn) : : "r" (stack), "X" (fn) :

"memory" ); \

Note how writing SP and branch are contained in a single asm() there. By checking ...

Quoted 6 lines
    unreachable();                                                    

\
} while ( false )

Here is part of disassembled enable_mmu():

Quoted 7 lines
ffffffffc004aedc:       18079073                csrw    satp,a5
ffffffffc004aee0:       00016797                auipc   a5,0x16
ffffffffc004aee4:       12078793                addi    a5,a5,288
ffffffffc004aee8:       813e                    mv      sp,a5
ffffffffc004af00:       0f4000ef                jal    

ra,ffffffffc004aff4 <cont_after_mmu_is_enabled>
...

... what the generated code in your case is you won't guarantee that things remain that way with future (or simply different) compilers.

Quoted 15 lines
Quoted 7 lines
Quoted 7 lines
xen/arch/riscv/riscv64/head.S +1 -0
@@ -1,4 +1,5 @@
  #include <asm/asm.h>
+#include <asm/asm-offsets.h>
  #include <asm/riscv_encoding.h>

Quoted 8 lines
Quoted 6 lines

         .section .text.header, "ax", %progbits

xen/arch/riscv/riscv64/head.S +0 -0
@@ -32,3 +33,4 @@ ENTRY(start)

         add     sp, sp, t0

         tail    start_xen
+

???

Quoted 1 line

Shouldn't it be the one empty line at the end of a file?

There should be a newline at the end of a file, but not normally a blank one. When you introduce a new file, it can be viewed as a matter of taste whether to have an empty last line, but when you have a seemingly unrelated change to a file like the one here, this is at least odd.

Quoted 24 lines
Quoted 11 lines
Quoted 10 lines
xen/arch/riscv/xen.lds.S +0 -0
@@ -136,6 +136,7 @@ SECTIONS
      . = ALIGN(POINTER_ALIGN);
      __init_end = .;


+    . = ALIGN(PAGE_SIZE);
     .bss : {                     /* BSS */
         __bss_start = .;
         *(.bss.stack_aligned)

Quoted 8 lines

Why do you need this? You properly use __aligned(PAGE_SIZE) for the page tables you define, and PAGE_SIZE wouldn't be enough here anyway if STACK_SIZE > PAGE_SIZE (as .bss.stack_aligned comes first). The only time you'd need such an ALIGN() is if the following label (__bss_start in this case) needed to be aligned at a certain boundary. (I'm a little puzzled though that __bss_start isn't [immediately] preceded by ". = ALIGN(POINTER_ALIGN);" - didn't .bss clearing rely on such alignment?)

ALIGN(PAGE_SIZE) isn't needed anymore.
I used it to have 4k aligned physical address for PTE when I mapped each section separately ( it was so in the previous verstion of MMU patch series )

Quoted 5 lines

Regarding ". = ALIGN(POINTER_ALIGN);" I would say that it is enough to have aligned __bss_end ( what was done ) to be sure that we can clear __SIZEOF_POINTER__ bytes each iteration of .bss clearing loop and don't worry that size of .bss section may not be divisible by __SIZEOF_POINTER__.

How would guaranteeing this only for __bss_end help? __bss_start could still be misaligned, and then you'd
(a) use misaligned stores for clearing and
(b) extend clearing to outside of the .bss (as the last of the misaligned stores would cross the __bss_end boundary).

Jan

#7 lore raw

Re: [PATCH v5 1/4] xen/riscv: add VM space layout

In reply to Jan Beulich

Hi,

Quoted 49 lines · Jan Beulich
Quoted 48 lines · Oleksii
Quoted 13 lines · Jan Beulich
Quoted 11 lines · Oleksii Kurochko

+ *
===================================================================
=========
+ *    Start addr    |   End addr        |  Size  | VM area description
+ *
===================================================================
=========

+ * FFFFFFFFC0000000 |  FFFFFFFFC0200000 |  2 MB  | Xen
+ * FFFFFFFFC0200000 |  FFFFFFFFC0600000 |  4 MB  | FDT
+ * FFFFFFFFC0600000 |  FFFFFFFFC0800000 |  2 MB  | Fixmap
Quoted 5 lines

These are all L2 slot 511 aiui, which may be worth mentioning especially since
the top bits don't match the top bits further down in the table (because of the
aliasing).

Than I'll add one more column where I'll put slot number

Quoted 11 lines
Quoted 2 lines

+ *     .................. unused ..................

This is covering slot 510, which again may be worth mentioning.

Quoted 4 lines

+ * 0000003200000000 |  0000007f40000000 | 331 GB | Direct map(L2
slot: 200-509)
+ * 0000003100000000 |  0000003140000000 |  1 GB  | Frametable(L2
slot: 196-197)

1Gb is, if I'm not mistaken, a single L2 slot.

Yeah, it can be misunderstood. I meant [196, 197), so 197 isn't included. I'll update the table.

Quoted 12 lines

Also assuming a 32-byte struct page_info (I don't think you'll get away with
less than that, when even Arm32 requires this much), there's a mismatch
between direct map and frame table size: With 4k pages, the scaling factor
would be 128 if I'm not mistaken. So perhaps you really mean 3Gb here to
cover for (slightly more than) the 331Gb of memory you mean to be able to
map?

Quoted 7 lines
Quoted 3 lines

For RV64 page_info size will be 56-byte and 32-byte for RV32 but you are right it should 3 Gb in that case what will be enough ( taking into account both available sizes of page_info structure ).

As to the plan to it being 56 bytes (i.e. like on Arm): Arm forever has had a 64-bit padding field at the end. My best guess is that the field was introduced to have a 32-byte struct on Arm32.

I can't exactly remember. But I would like to rework the struct page_info on Arm64 because...

But then why

Quoted 2 lines

artificially increase the struct from 48 to 56 bytes on Arm64? And hence why have the same oddity on RV64?

... with 56 bytes, some struct page_info may cross a cache boundary. For RISC-V, I would recommend to make sure the struct page_info will never cross a cache boundary.

Cheers,

Signature · 1 line
Julien Grall
#8 lore raw

Re: [PATCH v5 1/4] xen/riscv: add VM space layout

Quoted 63 lines · Julien Grall

Hi,

Quoted 49 lines · Jan Beulich
Quoted 48 lines · Oleksii
Quoted 13 lines · Jan Beulich
Quoted 11 lines · Oleksii Kurochko

+ *
===================================================================
=========
+ *    Start addr    |   End addr        |  Size  | VM area description
+ *
===================================================================
=========

+ * FFFFFFFFC0000000 |  FFFFFFFFC0200000 |  2 MB  | Xen
+ * FFFFFFFFC0200000 |  FFFFFFFFC0600000 |  4 MB  | FDT
+ * FFFFFFFFC0600000 |  FFFFFFFFC0800000 |  2 MB  | Fixmap
Quoted 5 lines

These are all L2 slot 511 aiui, which may be worth mentioning especially since
the top bits don't match the top bits further down in the table (because of the
aliasing).

Than I'll add one more column where I'll put slot number

Quoted 11 lines
Quoted 2 lines

+ *     .................. unused ..................

This is covering slot 510, which again may be worth mentioning.

Quoted 4 lines

+ * 0000003200000000 |  0000007f40000000 | 331 GB | Direct map(L2
slot: 200-509)
+ * 0000003100000000 |  0000003140000000 |  1 GB  | Frametable(L2
slot: 196-197)

1Gb is, if I'm not mistaken, a single L2 slot.

Yeah, it can be misunderstood. I meant [196, 197), so 197 isn't included. I'll update the table.

Quoted 12 lines

Also assuming a 32-byte struct page_info (I don't think you'll get away with
less than that, when even Arm32 requires this much), there's a mismatch
between direct map and frame table size: With 4k pages, the scaling factor
would be 128 if I'm not mistaken. So perhaps you really mean 3Gb here to
cover for (slightly more than) the 331Gb of memory you mean to be able to
map?

Quoted 7 lines
Quoted 3 lines

For RV64 page_info size will be 56-byte and 32-byte for RV32 but you are right it should 3 Gb in that case what will be enough ( taking into account both available sizes of page_info structure ).

As to the plan to it being 56 bytes (i.e. like on Arm): Arm forever has had a 64-bit padding field at the end. My best guess is that the field was introduced to have a 32-byte struct on Arm32.

I can't exactly remember. But I would like to rework the struct page_info on Arm64 because...

Quoted 6 lines

But then why

Quoted 2 lines

artificially increase the struct from 48 to 56 bytes on Arm64? And hence why have the same oddity on RV64?

... with 56 bytes, some struct page_info may cross a cache boundary.

I guess that's going to be challenging, unless you mean to go further up to 64 bytes?

Quoted 3 lines

For
RISC-V, I would recommend to make sure the struct page_info will never cross a cache boundary.

Since going up to 64 bytes is wasteful, and going down to 32 bytes likely isn't going to be easy, sticking to 48 bytes for now would seem reasonable to me.

Jan

#9 lore raw

Re: [PATCH v5 1/4] xen/riscv: add VM space layout

Hi Jan,

Quoted 65 lines · Jan Beulich
Quoted 64 lines · Julien Grall

Hi,

Quoted 49 lines · Jan Beulich
Quoted 48 lines · Oleksii
Quoted 13 lines · Jan Beulich
Quoted 11 lines · Oleksii Kurochko

+ *
===================================================================
=========
+ *    Start addr    |   End addr        |  Size  | VM area description
+ *
===================================================================
=========

+ * FFFFFFFFC0000000 |  FFFFFFFFC0200000 |  2 MB  | Xen
+ * FFFFFFFFC0200000 |  FFFFFFFFC0600000 |  4 MB  | FDT
+ * FFFFFFFFC0600000 |  FFFFFFFFC0800000 |  2 MB  | Fixmap
Quoted 5 lines

These are all L2 slot 511 aiui, which may be worth mentioning especially since
the top bits don't match the top bits further down in the table (because of the
aliasing).

Than I'll add one more column where I'll put slot number

Quoted 11 lines
Quoted 2 lines

+ *     .................. unused ..................

This is covering slot 510, which again may be worth mentioning.

Quoted 4 lines

+ * 0000003200000000 |  0000007f40000000 | 331 GB | Direct map(L2
slot: 200-509)
+ * 0000003100000000 |  0000003140000000 |  1 GB  | Frametable(L2
slot: 196-197)

1Gb is, if I'm not mistaken, a single L2 slot.

Yeah, it can be misunderstood. I meant [196, 197), so 197 isn't included. I'll update the table.

Quoted 12 lines

Also assuming a 32-byte struct page_info (I don't think you'll get away with
less than that, when even Arm32 requires this much), there's a mismatch
between direct map and frame table size: With 4k pages, the scaling factor
would be 128 if I'm not mistaken. So perhaps you really mean 3Gb here to
cover for (slightly more than) the 331Gb of memory you mean to be able to
map?

Quoted 7 lines
Quoted 3 lines

For RV64 page_info size will be 56-byte and 32-byte for RV32 but you are right it should 3 Gb in that case what will be enough ( taking into account both available sizes of page_info structure ).

As to the plan to it being 56 bytes (i.e. like on Arm): Arm forever has had a 64-bit padding field at the end. My best guess is that the field was introduced to have a 32-byte struct on Arm32.

I can't exactly remember. But I would like to rework the struct page_info on Arm64 because...

But then why

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

artificially increase the struct from 48 to 56 bytes on Arm64? And hence why have the same oddity on RV64?

... with 56 bytes, some struct page_info may cross a cache boundary.

I guess that's going to be challenging, unless you mean to go further up to 64 bytes?

Yes.

Quoted 6 lines
Quoted 4 lines

For
RISC-V, I would recommend to make sure the struct page_info will never cross a cache boundary.

Since going up to 64 bytes is wasteful,

Well yes. But this is a trade-off between performance and memory usage. With the current situation, you may have to pull two cache lines for struct page_info.

I suspect you might see some slow down when using the grant. But I don't have any concrete numbers.

Quoted 3 lines

and going down to 32 bytes likely
isn't going to be easy, sticking to 48 bytes for now would seem reasonable to me.

It may be more difficult to argue for an increase (if we notice any performance degradation) in the future because this would reduce the memory usable for every users.

Anyway, I haven't fully explore the problem on Arm yet and it is possible we could deal with any performance degradation differently (e.g. re-order the field and/or slightly increasing/decreasing the size).

I thought I would point it out just in case the RISC-V folks care about it.

Cheers,

Signature · 1 line
Julien Grall
author
#5 lore raw

Re: [PATCH v5 1/4] xen/riscv: add VM space layout

In reply to Jan Beulich
Quoted 62 lines · Jan Beulich
Quoted 55 lines · Oleksii
Quoted 15 lines · Jan Beulich
Quoted 10 lines · Oleksii Kurochko

+ *
===============================================================
====
=========
+ *    Start addr    |   End addr        |  Size  | VM area description
+ *
===============================================================
====
=========

Quoted 3 lines
+ * FFFFFFFFC0000000 |  FFFFFFFFC0200000 |  2 MB  | Xen
+ * FFFFFFFFC0200000 |  FFFFFFFFC0600000 |  4 MB  | FDT
+ * FFFFFFFFC0600000 |  FFFFFFFFC0800000 |  2 MB  | Fixmap
Quoted 5 lines

These are all L2 slot 511 aiui, which may be worth mentioning especially since
the top bits don't match the top bits further down in the table (because of the
aliasing).

Than I'll add one more column where I'll put slot number

Quoted 5 lines
Quoted 2 lines

+ *     .................. unused ..................

This is covering slot 510, which again may be worth mentioning.

Quoted 8 lines
Quoted 6 lines

+ * 0000003200000000 |  0000007f40000000 | 331 GB | Direct map(L2
slot: 200-509)
+ * 0000003100000000 |  0000003140000000 |  1 GB  | Frametable(L2
slot: 196-197)

1Gb is, if I'm not mistaken, a single L2 slot.

Yeah, it can be misunderstood. I meant [196, 197), so 197 isn't included. I'll update the table.

Quoted 15 lines

Also assuming a 32-byte struct page_info (I don't think you'll get
away with
less than that, when even Arm32 requires this much), there's a mismatch
between direct map and frame table size: With 4k pages, the scaling
factor
would be 128 if I'm not mistaken. So perhaps you really mean 3Gb here
to
cover for (slightly more than) the 331Gb of memory you mean to be able to
map?

Quoted 5 lines

For RV64 page_info size will be 56-byte and 32-byte for RV32 but you
are right it should 3 Gb in that case what will be enough ( taking into
account both available sizes of page_info structure ).

Quoted 4 lines

Since you say "both": I don't expect you will want to use 3Gb for RV32
there? The table is, at least for now, for RV64 / Sv39 only anyway.

You are right. There is no any sense to use 3gb for RV32.

~ Oleksii

author
#12 lore raw

Re: [PATCH v5 1/4] xen/riscv: add VM space layout

In reply to Jan Beulich
Quoted 62 lines · Jan Beulich
Quoted 55 lines · Oleksii
Quoted 15 lines · Jan Beulich
Quoted 10 lines · Oleksii Kurochko

+ *
===============================================================
====
=========
+ *    Start addr    |   End addr        |  Size  | VM area description
+ *
===============================================================
====
=========

Quoted 3 lines
+ * FFFFFFFFC0000000 |  FFFFFFFFC0200000 |  2 MB  | Xen
+ * FFFFFFFFC0200000 |  FFFFFFFFC0600000 |  4 MB  | FDT
+ * FFFFFFFFC0600000 |  FFFFFFFFC0800000 |  2 MB  | Fixmap
Quoted 5 lines

These are all L2 slot 511 aiui, which may be worth mentioning especially since
the top bits don't match the top bits further down in the table (because of the
aliasing).

Than I'll add one more column where I'll put slot number

Quoted 5 lines
Quoted 2 lines

+ *     .................. unused ..................

This is covering slot 510, which again may be worth mentioning.

Quoted 8 lines
Quoted 6 lines

+ * 0000003200000000 |  0000007f40000000 | 331 GB | Direct map(L2
slot: 200-509)
+ * 0000003100000000 |  0000003140000000 |  1 GB  | Frametable(L2
slot: 196-197)

1Gb is, if I'm not mistaken, a single L2 slot.

Yeah, it can be misunderstood. I meant [196, 197), so 197 isn't included. I'll update the table.

Quoted 15 lines

Also assuming a 32-byte struct page_info (I don't think you'll get
away with
less than that, when even Arm32 requires this much), there's a mismatch
between direct map and frame table size: With 4k pages, the scaling
factor
would be 128 if I'm not mistaken. So perhaps you really mean 3Gb here
to
cover for (slightly more than) the 331Gb of memory you mean to be able to
map?

Quoted 5 lines

For RV64 page_info size will be 56-byte and 32-byte for RV32 but you
are right it should 3 Gb in that case what will be enough ( taking into
account both available sizes of page_info structure ).

Quoted 8 lines

As to the plan to it being 56 bytes (i.e. like on Arm): Arm forever has
had a 64-bit padding field at the end. My best guess is that the field
was introduced to have a 32-byte struct on Arm32. But then why artificially increase the struct from 48 to 56 bytes on Arm64? And hence
why have the same oddity on RV64?

I didn't think about that. I just re-used page_info structure from ARM. I'll think about your comment. Thanks.

~ Oleksii

author
#17 lore raw

Re: [PATCH v5 2/4] xen/riscv: introduce setup_initial_pages

In reply to Jan Beulich
Quoted 21 lines · Jan Beulich
Quoted 13 lines · Oleksii
Quoted 12 lines · Jan Beulich
Quoted 10 lines · Oleksii Kurochko

+                        /* panic(), <asm/bug.h> aren't ready now.
*/
+                        die();
+                    }
+                }
+        }
+
+        /* Point to next page */
+        page_addr += XEN_PT_LEVEL_SIZE(0);

Quoted 6 lines
Quoted 3 lines

Seeing this as well as the loop heading - maybe more suitable as a
for(;;) loop?

I am not sure that I understand the benefits of changing "while ( page_addr < map_end )" to "for(;;)".
Could you please explain me what the benefits are?

Quoted 7 lines

The common case of using while() is in situations where one cannot use for(). for() is (imo) preferable in all cases where the third of the controlling expressions isn't empty (and is to be carried out after every iteration): Any use of "continue" inside the loop will then properly effect loop progress. (Of course there are cases where this behavior isn't wanted; that's where while() may come into play then.)

Thanks for clarification. Now it is more clear.

Quoted 25 lines
Quoted 22 lines
Quoted 14 lines
Quoted 14 lines

+    csr_write(CSR_SATP,
+              ((unsigned long)stage1_pgtbl_root >> PAGE_SHIFT) |
+              satp_mode << SATP_MODE_SHIFT);
+
+    if ( (csr_read(CSR_SATP) >> SATP_MODE_SHIFT) == satp_mode )
+        is_mode_supported = true;

xen/arch/riscv/mm.c new file +5 -0
+
+    /* Clean MMU root page table and disable MMU */
+    stage1_pgtbl_root[index] = paddr_to_pte(0x0, 0x0);
+
+    csr_write(CSR_SATP, 0);
Quoted 8 lines
Quoted 1 line

+    asm volatile("sfence.vma");

I guess what you do in this function could do with some more comments.
Looks like you're briefly enabling the MMU to check that what you wrote
to SATP you can also read back. (Isn't there a register reporting whether the feature is available?)

Quoted 2 lines

I supposed that it has to be but I couldn't find a register in docs.

Quoted 9 lines

Well, yes, interestingly the register is marked WARL, so apparently intended to by used for probing like you do. (I find the definition of
WARL a little odd though, as such writes supposedly aren't necessarily
value preserving. For SATP this might mean that translation is enabled
by a write of an unsupported mode, with a different number of levels. This isn't going to work very well, I'm afraid.)

Agree. It will be an issue in case of a different number of levels.

Then it looks there is no way to check if SATP mode is supported.

So we have to rely on the fact that the developer specified RV_STAGE1_MODE correctly in the config file.

Quoted 60 lines
Quoted 34 lines
Quoted 22 lines
Quoted 11 lines

+    /*
+     * Stack should be re-inited as:
+     * 1. Right now an address of the stack is relative to load
time
+     *    addresses what will cause an issue in case of load start
address
+     *    isn't equal to linker start address.
+     * 2. Addresses in stack are all load time relative which

Quoted 8 lines

can
be an
+     *    issue in case when load start address isn't equal to linker
+     *    start address.
+     */
+    asm volatile ("mv sp, %0" : : "r"((unsigned long)cpu0_boot_stack + STACK_SIZE));

Nit: Style (overly long line).

Quoted 12 lines

What's worse - I don't think it is permitted to alter sp in the middle of
a function. The compiler may maintain local variables on the stack
which
don't correspond to any programmer specified ones, including pointer
ones
which point into the stack frame. This is specifically why both x86
and
Arm have switch_stack_and_jump() macros.

Quoted 7 lines

but the macros (from ARM) looks equal to the code mentioned above:
#define switch_stack_and_jump(stack, fn) do
{
\
    asm volatile ("mov sp,%0; b " STR(fn) : : "r" (stack), "X" (fn) :
"memory" ); \

Note how writing SP and branch are contained in a single asm() there. By checking ...

Quoted 7 lines


unreachable();
\
} while ( false )

Here is part of disassembled enable_mmu():

Quoted 7 lines

ffffffffc004aedc:       18079073                csrw    satp,a5 ffffffffc004aee0:       00016797                auipc   a5,0x16 ffffffffc004aee4:       12078793                addi    a5,a5,288 ffffffffc004aee8:       813e                    mv      sp,a5 ffffffffc004af00:       0f4000ef                jal ra,ffffffffc004aff4 <cont_after_mmu_is_enabled>
...

Quoted 2 lines

... what the generated code in your case is you won't guarantee that things remain that way with future (or simply different) compilers.

Agree. Thanks for clarification. I'll take into account during the next version of patch series.

Quoted 16 lines
Quoted 16 lines
Quoted 16 lines
Quoted 10 lines
xen/arch/riscv/riscv64/head.S +1 -0
@@ -1,4 +1,5 @@
  #include <asm/asm.h>
+#include <asm/asm-offsets.h>
  #include <asm/riscv_encoding.h>


         .section .text.header, "ax", %progbits

xen/arch/riscv/riscv64/head.S +0 -0
@@ -32,3 +33,4 @@ ENTRY(start)
Quoted 4 lines

         add     sp, sp, t0

         tail    start_xen
+

???

Quoted 8 lines
Quoted 1 line

Shouldn't it be the one empty line at the end of a file?

There should be a newline at the end of a file, but not normally a blank one. When you introduce a new file, it can be viewed as a matter
of taste whether to have an empty last line, but when you have a seemingly unrelated change to a file like the one here, this is at least odd.

Agree. Then I'll remove this change from the patch series.

Quoted 38 lines
Quoted 29 lines
Quoted 16 lines
Quoted 11 lines
xen/arch/riscv/xen.lds.S +0 -0
@@ -136,6 +136,7 @@ SECTIONS
      . = ALIGN(POINTER_ALIGN);
      __init_end = .;


+    . = ALIGN(PAGE_SIZE);
     .bss : {                     /* BSS */
         __bss_start = .;
         *(.bss.stack_aligned)

Why do you need this? You properly use __aligned(PAGE_SIZE) for the
page tables you define, and PAGE_SIZE wouldn't be enough here anyway

Quoted 8 lines

if STACK_SIZE > PAGE_SIZE (as .bss.stack_aligned comes first). The
only time you'd need such an ALIGN() is if the following label (__bss_start in this case) needed to be aligned at a certain boundary. (I'm a little puzzled though that __bss_start isn't [immediately] preceded by ". = ALIGN(POINTER_ALIGN);" - didn't .bss
clearing rely on such alignment?)

ALIGN(PAGE_SIZE)  isn't needed anymore.
I used it to have 4k aligned physical address for PTE when I mapped each section separately ( it was so in the previous verstion of MMU patch series )

Quoted 8 lines

Regarding ". = ALIGN(POINTER_ALIGN);" I would say that it is enough to
have aligned __bss_end ( what was done ) to be sure that we can clear
__SIZEOF_POINTER__ bytes each iteration of .bss clearing loop and don't
worry that size of .bss section may not be divisible by __SIZEOF_POINTER__.

Quoted 7 lines

How would guaranteeing this only for __bss_end help? __bss_start could
still be misaligned, and then you'd
(a) use misaligned stores for clearing and
(b) extend clearing to outside of the .bss (as the last of the misaligned
stores would cross the __bss_end boundary).

It seems you are right. I'll create a separate commit to align __bss_start properly.

~ Oleksii

#18 lore raw

Re: [PATCH v5 2/4] xen/riscv: introduce setup_initial_pages

Quoted 37 lines · Oleksii
Quoted 27 lines · Jan Beulich
Quoted 23 lines · Oleksii
Quoted 14 lines · Jan Beulich
Quoted 13 lines · Oleksii Kurochko

+    csr_write(CSR_SATP,
+              ((unsigned long)stage1_pgtbl_root >> PAGE_SHIFT) |
+              satp_mode << SATP_MODE_SHIFT);
+
+    if ( (csr_read(CSR_SATP) >> SATP_MODE_SHIFT) == satp_mode )
+        is_mode_supported = true;

xen/arch/riscv/mm.c new file +5 -0
+
+    /* Clean MMU root page table and disable MMU */
+    stage1_pgtbl_root[index] = paddr_to_pte(0x0, 0x0);
+
+    csr_write(CSR_SATP, 0);
Quoted 8 lines
Quoted 1 line

+    asm volatile("sfence.vma");

I guess what you do in this function could do with some more comments.
Looks like you're briefly enabling the MMU to check that what you wrote
to SATP you can also read back. (Isn't there a register reporting whether the feature is available?)

Quoted 2 lines

I supposed that it has to be but I couldn't find a register in docs.

Quoted 9 lines

Well, yes, interestingly the register is marked WARL, so apparently intended to by used for probing like you do. (I find the definition of
WARL a little odd though, as such writes supposedly aren't necessarily
value preserving. For SATP this might mean that translation is enabled
by a write of an unsupported mode, with a different number of levels. This isn't going to work very well, I'm afraid.)

Quoted 6 lines

Agree. It will be an issue in case of a different number of levels.

Then it looks there is no way to check if SATP mode is supported.

So we have to rely on the fact that the developer specified RV_STAGE1_MODE correctly in the config file.

Well, maybe the spec could be clarified in this regard. That WARL behavior may be okay for some registers, but as said I think it isn't enough of a guarantee for SATP probing. Alistair, Bob - any thoughts?

Jan

author
#19 lore raw

Re: [PATCH v5 2/4] xen/riscv: introduce setup_initial_pages

Hi Jan,

Quoted 47 lines · Jan Beulich
Quoted 46 lines · Oleksii
Quoted 31 lines · Jan Beulich
Quoted 27 lines · Oleksii
Quoted 18 lines · Jan Beulich
Quoted 10 lines · Oleksii Kurochko

+    csr_write(CSR_SATP,
+              ((unsigned long)stage1_pgtbl_root >> PAGE_SHIFT)

Quoted 1 line

+              satp_mode << SATP_MODE_SHIFT); +
+    if ( (csr_read(CSR_SATP) >> SATP_MODE_SHIFT) == satp_mode
)
+        is_mode_supported = true;

xen/arch/riscv/mm.c line 217

Quoted 6 lines
xen/arch/riscv/mm.c new file +6 -0
+
+    /* Clean MMU root page table and disable MMU */
+    stage1_pgtbl_root[index] = paddr_to_pte(0x0, 0x0);
+
+    csr_write(CSR_SATP, 0);
+    asm volatile("sfence.vma");
Quoted 8 lines

I guess what you do in this function could do with some more comments.
Looks like you're briefly enabling the MMU to check that what you
wrote
to SATP you can also read back. (Isn't there a register reporting
whether the feature is available?)

Quoted 2 lines

I supposed that it has to be but I couldn't find a register in docs.

Quoted 12 lines

Well, yes, interestingly the register is marked WARL, so apparently
intended to by used for probing like you do. (I find the definition
of
WARL a little odd though, as such writes supposedly aren't necessarily
value preserving. For SATP this might mean that translation is enabled
by a write of an unsupported mode, with a different number of levels.
This isn't going to work very well, I'm afraid.)

Agree. It will be an issue in case of a different number of levels.

Quoted 8 lines
Quoted 4 lines

Then it looks there is no way to check if SATP mode is supported.

So we have to rely on the fact that the developer specified RV_STAGE1_MODE correctly in the config file.

Well, maybe the spec could be clarified in this regard. That WARL behavior may be okay for some registers, but as said I think it isn't enough of a guarantee for SATP probing. Alistair, Bob - any thoughts?

I've re-read the manual regarding CSR_SATP and the code of detecting SATP mode will work fine.
From the manual ( 4.1.11
Supervisor Address Translation and Protection (satp) Register ):
“Implementations are not required to support all MODE settings, and if satp is written with an unsupported MODE, the entire write has no effect; no fields in satp are modified.”

So there is no leave any open question so I'll provide new patch series.

~ Oleksii

author
#10 lore raw

Re: [PATCH v5 1/4] xen/riscv: add VM space layout

In reply to Julien Grall

Hi Julien,

Quoted 83 lines · Julien Grall
Quoted 83 lines
Quoted 83 lines
Quoted 68 lines
Quoted 62 lines
Quoted 17 lines · Oleksii Kurochko
Quoted 11 lines

+ *
=========================================================
==========
=========
+ *    Start addr    |   End addr        |  Size  | VM area
description
+ *
=========================================================
==========
=========

Quoted 4 lines
+ * FFFFFFFFC0000000 |  FFFFFFFFC0200000 |  2 MB  | Xen
+ * FFFFFFFFC0200000 |  FFFFFFFFC0600000 |  4 MB  | FDT
+ * FFFFFFFFC0600000 |  FFFFFFFFC0800000 |  2 MB  |

Fixmap

Quoted 7 lines

These are all L2 slot 511 aiui, which may be worth mentioning
especially since
the top bits don't match the top bits further down in the table
(because of the
aliasing).

Than I'll add one more column where I'll put slot number

Quoted 6 lines
Quoted 2 lines

+ *     .................. unused ..................

This is covering slot 510, which again may be worth mentioning.

Quoted 8 lines
Quoted 6 lines

+ * 0000003200000000 |  0000007f40000000 | 331 GB | Direct map(L2
slot: 200-509)
+ * 0000003100000000 |  0000003140000000 |  1 GB  | Frametable(L2
slot: 196-197)

1Gb is, if I'm not mistaken, a single L2 slot.

Yeah, it can be misunderstood. I meant [196, 197), so 197 isn't
included. I'll update the table.

Quoted 17 lines

Also assuming a 32-byte struct page_info (I don't think you'll get
away with
less than that, when even Arm32 requires this much), there's a
mismatch
between direct map and frame table size: With 4k pages, the scaling
factor
would be 128 if I'm not mistaken. So perhaps you really mean 3Gb here
to
cover for (slightly more than) the 331Gb of memory you mean to be
able to
map?

Quoted 5 lines

For RV64 page_info size will be 56-byte and 32-byte for RV32 but you
are right it should 3 Gb in that case what will be enough ( taking into
account both available sizes of page_info structure ).

Quoted 5 lines

As to the plan to it being 56 bytes (i.e. like on Arm): Arm forever has
had a 64-bit padding field at the end. My best guess is that the field
was introduced to have a 32-byte struct on Arm32.

I can't exactly remember. But I would like to rework the struct page_info on Arm64 because...

But then why

Quoted 3 lines

artificially increase the struct from 48 to 56 bytes on Arm64? And hence
why have the same oddity on RV64?

Quoted 14 lines
Quoted 6 lines
Quoted 2 lines

... with 56 bytes, some struct page_info may cross a cache boundary.

I guess that's going to be challenging, unless you mean to go further up
to 64 bytes?

Yes.

Quoted 5 lines
Quoted 5 lines

For
RISC-V, I would recommend to make sure the struct page_info will never
cross a cache boundary.

Do you mean that size(struct page_info) <= cache line size?

Quoted 7 lines
Quoted 2 lines

Since going up to 64 bytes is wasteful,

Well yes. But this is a trade-off between performance and memory usage.
With the current situation, you may have to pull two cache lines for struct page_info.

Just for my understanding.

stuct page_info will consume two cache lines (it happens in case of 3 consecutive which exceed the size of the cache line) if they are not aligned on 64 bytes boundary as cache line size on ARM is 128 ( if believe to ARM's asm/cache.h ).

Shouldn't alignment ( by adding empty fields inside page_info ) fix an issue? It looks like if the size of page_info will not be aligned that it will be always performance issue.

Quoted 14 lines

I suspect you might see some slow down when using the grant. But I don't
have any concrete numbers.

Quoted 4 lines

and going down to 32 bytes likely
isn't going to be easy, sticking to 48 bytes for now would seem reasonable
to me.

It may be more difficult to argue for an increase (if we notice any performance degradation) in the future because this would reduce the memory usable for every users.

Quoted 7 lines

Anyway, I haven't fully explore the problem on Arm yet and it is possible we could deal with any performance degradation differently (e.g. re-order the field and/or slightly increasing/decreasing the size).

I thought I would point it out just in case the RISC-V folks care about it.

I think it will be useful as RISC-V uses the same page_info structure.

~ Oleksii

#11 lore raw

Re: [PATCH v5 1/4] xen/riscv: add VM space layout

Quoted 5 lines · Oleksii
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

For
RISC-V, I would recommend to make sure the struct page_info will never
cross a cache boundary.

Do you mean that size(struct page_info) <= cache line size?

I don't think that's what was meant. Instead I expect the goal is for no struct page_info instance to ever cross a cache line boundary. IOW one of sizeof(struct page_info) % cachelinesize == 0 or cachelinesize % sizeof(struct page_info) == 0, or in yet different terms (with the expectation that cache lines are always a power of two in size) sizeof(struct page_info) == 2**n. Yet unless you're able to fit everything in 32 bytes, that'll mean more overhead than strictly necessary.

Jan

#20 lore raw

Re: [PATCH v5 2/4] xen/riscv: introduce setup_initial_pages

In reply to Oleksii
Quoted 58 lines · Oleksii

Hi Jan,

Quoted 47 lines · Jan Beulich
Quoted 46 lines · Oleksii
Quoted 31 lines · Jan Beulich
Quoted 27 lines · Oleksii
Quoted 18 lines · Jan Beulich
Quoted 10 lines · Oleksii Kurochko

+    csr_write(CSR_SATP,
+              ((unsigned long)stage1_pgtbl_root >> PAGE_SHIFT)

Quoted 1 line

+              satp_mode << SATP_MODE_SHIFT); +
+    if ( (csr_read(CSR_SATP) >> SATP_MODE_SHIFT) == satp_mode
)
+        is_mode_supported = true;

Review

Quoted 6 lines
(quoted diff) +6 -0
+
+    /* Clean MMU root page table and disable MMU */
+    stage1_pgtbl_root[index] = paddr_to_pte(0x0, 0x0);
+
+    csr_write(CSR_SATP, 0);
+    asm volatile("sfence.vma");
Quoted 8 lines

I guess what you do in this function could do with some more comments.
Looks like you're briefly enabling the MMU to check that what you
wrote
to SATP you can also read back. (Isn't there a register reporting
whether the feature is available?)

Quoted 2 lines

I supposed that it has to be but I couldn't find a register in docs.

Quoted 12 lines

Well, yes, interestingly the register is marked WARL, so apparently
intended to by used for probing like you do. (I find the definition
of
WARL a little odd though, as such writes supposedly aren't necessarily
value preserving. For SATP this might mean that translation is enabled
by a write of an unsupported mode, with a different number of levels.
This isn't going to work very well, I'm afraid.)

Agree. It will be an issue in case of a different number of levels.

Quoted 8 lines
Quoted 4 lines

Then it looks there is no way to check if SATP mode is supported.

So we have to rely on the fact that the developer specified RV_STAGE1_MODE correctly in the config file.

Well, maybe the spec could be clarified in this regard. That WARL behavior may be okay for some registers, but as said I think it isn't enough of a guarantee for SATP probing. Alistair, Bob - any thoughts?

Quoted 7 lines

I've re-read the manual regarding CSR_SATP and the code of detecting SATP mode will work fine.
From the manual ( 4.1.11
Supervisor Address Translation and Protection (satp) Register ):
“Implementations are not required to support all MODE settings, and if satp is written with an unsupported MODE, the entire write has no effect; no fields in satp are modified.”

Ah, I see. That's the sentence I had overlooked (and that's unhelpfully not only not implied to be that way, but actively implied to be different by figures 4.11 and 4.12 naming [all] the individual fields as WARL).

Jan