You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nuttx.apache.org by GitBox <gi...@apache.org> on 2022/04/14 12:58:37 UTC

[GitHub] [incubator-nuttx] pkarashchenko commented on a diff in pull request #6069: RISC-V: Add support for CONFIG_BUILD_KERNEL

pkarashchenko commented on code in PR #6069:
URL: https://github.com/apache/incubator-nuttx/pull/6069#discussion_r850396374


##########
arch/risc-v/src/common/pgalloc.h:
##########
@@ -0,0 +1,58 @@
+/****************************************************************************
+ * arch/risc-v/src/common/pgalloc.h
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+#ifndef __ARCH_RISC_V_SRC_COMMON_PGALLOC_H_
+#define __ARCH_RISC_V_SRC_COMMON_PGALLOC_H_

Review Comment:
   ```suggestion
   #ifndef __ARCH_RISC_V_SRC_COMMON_PGALLOC_H
   #define __ARCH_RISC_V_SRC_COMMON_PGALLOC_H
   ```



##########
arch/risc-v/src/common/pgalloc.h:
##########
@@ -0,0 +1,58 @@
+/****************************************************************************
+ * arch/risc-v/src/common/pgalloc.h
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+#ifndef __ARCH_RISC_V_SRC_COMMON_PGALLOC_H_
+#define __ARCH_RISC_V_SRC_COMMON_PGALLOC_H_
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <stdint.h>
+
+/****************************************************************************
+ * Public Functions Prototypes
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: riscv_pgpool_to_vaddr
+ *
+ * Description:
+ *   Get virtual address for pgpool physical address. Note: this function
+ *   is minimalistic and is only usable for kernel mappings and only tests
+ *   if the paddr is in the pgpool. For user mapped addresses this does not
+ *   work.
+ *
+ * Note:
+ *   To get it to work with user addresses, a manual table walk needs to be
+ *   implemented. Not too complex, but not needed for anything -> not
+ *   implemented.
+ *
+ * Input Parameters:
+ *   paddr - Physical pgpool address
+ *
+ * Return:
+ *   vaddr - Virtual address for physical address
+ *
+ ****************************************************************************/
+
+uintptr_t riscv_pgpool_to_vaddr(uintptr_t paddr);
+
+#endif /* __ARCH_RISC_V_SRC_COMMON_PGALLOC_H_ */

Review Comment:
   ```suggestion
   #endif /* __ARCH_RISC_V_SRC_COMMON_PGALLOC_H */
   ```



##########
arch/risc-v/src/common/crt0.c:
##########
@@ -0,0 +1,137 @@
+/****************************************************************************
+ * arch/risc-v/src/common/crt0.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <arch/syscall.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/compiler.h>
+#include <nuttx/config.h>
+
+#include <sys/types.h>
+#include <stdlib.h>
+
+#ifdef CONFIG_BUILD_KERNEL
+
+/****************************************************************************
+ * Public Function Prototypes
+ ****************************************************************************/
+
+int main(int argc, char *argv[]);
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_signal_handler
+ *
+ * Description:
+ *   This function is the user-space, signal handler trampoline function.  It
+ *   is called from up_signal_dispatch() in user-mode.
+ *
+ * Input Parameters:
+ *   a0 = sighand
+ *     The address user-space signal handling function
+ *   a1-a3 = signo, info, and ucontext
+ *     Standard arguments to be passed to the signal handling function.
+ *
+ * Returned Value:
+ *   None.  This function does not return in the normal sense.  It returns
+ *   via the SYS_signal_handler_return (see syscall.h)
+ *
+ ****************************************************************************/
+
+static void sig_trampoline(void) naked_function;
+static void sig_trampoline(void)
+{
+  __asm__ __volatile__
+  (
+    " addi sp, sp, -16\n"   /* Save ra on the stack */
+    " sd   ra, 8(sp)\n"
+    " mv   t0, a0\n"        /* t0=sighand */
+    " mv   a0, a1\n"        /* a0=signo */
+    " mv   a1, a2\n"        /* a1=info */
+    " mv   a2, a3\n"        /* a2=ucontext */
+    " jalr t0\n"            /* Call the signal handler (modifies ra) */
+    " ld   ra, 8(sp)\n"     /* Recover ra in sp */
+    " addi sp, sp, 16\n"

Review Comment:
   ```suggestion
       " addi sp, sp, " STACK_FRAME_SIZE "\n"
   ```



##########
arch/risc-v/src/common/crt0.c:
##########
@@ -0,0 +1,137 @@
+/****************************************************************************
+ * arch/risc-v/src/common/crt0.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <arch/syscall.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/compiler.h>
+#include <nuttx/config.h>
+
+#include <sys/types.h>
+#include <stdlib.h>
+
+#ifdef CONFIG_BUILD_KERNEL
+
+/****************************************************************************
+ * Public Function Prototypes
+ ****************************************************************************/
+
+int main(int argc, char *argv[]);
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_signal_handler
+ *
+ * Description:
+ *   This function is the user-space, signal handler trampoline function.  It
+ *   is called from up_signal_dispatch() in user-mode.
+ *
+ * Input Parameters:
+ *   a0 = sighand
+ *     The address user-space signal handling function
+ *   a1-a3 = signo, info, and ucontext
+ *     Standard arguments to be passed to the signal handling function.
+ *
+ * Returned Value:
+ *   None.  This function does not return in the normal sense.  It returns
+ *   via the SYS_signal_handler_return (see syscall.h)
+ *
+ ****************************************************************************/
+
+static void sig_trampoline(void) naked_function;
+static void sig_trampoline(void)
+{
+  __asm__ __volatile__
+  (
+    " addi sp, sp, -16\n"   /* Save ra on the stack */
+    " sd   ra, 8(sp)\n"
+    " mv   t0, a0\n"        /* t0=sighand */
+    " mv   a0, a1\n"        /* a0=signo */
+    " mv   a1, a2\n"        /* a1=info */
+    " mv   a2, a3\n"        /* a2=ucontext */
+    " jalr t0\n"            /* Call the signal handler (modifies ra) */
+    " ld   ra, 8(sp)\n"     /* Recover ra in sp */
+    " addi sp, sp, 16\n"
+    " li   a0, %0\n"        /* SYS_signal_handler_return */
+    " ecall\n"              /* Return from the SYSCALL */
+    " nop\n"
+    :
+    : "i" (SYS_signal_handler_return)
+    :
+  );
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: _start
+ *
+ * Description:
+ *   This function is the low level entry point into the main thread of
+ *   execution of a task.  It receives initial control when the task is
+ *   started and calls main entry point of the newly started task.
+ *
+ * Input Parameters:
+ *   argc - The number of parameters being passed.
+ *   argv - The parameters being passed. These lie in kernel-space memory
+ *     and will have to be reallocated  in user-space memory.
+ *
+ * Returned Value:
+ *   This function should not return.  It should call the user-mode start-up
+ *   main() function.  If that function returns, this function will call
+ *   exit.
+ *
+ ****************************************************************************/
+
+void _start(int argc, FAR char *argv[])

Review Comment:
   ```suggestion
   void _start(int argc, char *argv[])
   ```



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)

Review Comment:
   ```suggestion
                         group_addrenv_t *addrenv)
   ```



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)
+{
+  int       ret;
+  uintptr_t resvbase;
+  uintptr_t resvsize;
+  uintptr_t textbase;
+  uintptr_t database;
+  uintptr_t heapbase;
+
+  DEBUGASSERT(addrenv);
+  DEBUGASSERT(MM_ISALIGNED(ADDRENV_VBASE));
+
+  /* Make sure the address environment is wiped before doing anything */
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+
+  /* Create the static page tables */
+
+  if (create_spgtables(addrenv) < 0)
+    {
+      serr("ERROR: Failed to create static page tables\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  if (copy_kernel_mappings(addrenv) < 0)
+    {
+      serr("ERROR: Failed to copy kernel mappings to new environment");
+      ret = -EINVAL;
+      goto errout;
+    }
+
+  /* Calculate the base addresses for convenience */
+
+  resvbase = ADDRENV_VBASE;
+  resvsize = ARCH_DATA_RESERVE_SIZE;
+  textbase = resvbase + MM_PGALIGNUP(resvsize);
+  database = textbase + MM_PGALIGNUP(textsize);
+  heapbase = database + MM_PGALIGNUP(datasize);
+
+  /* Allocate 1 extra page for heap, temporary fix for #5811 */
+
+  heapsize = heapsize + MM_NPAGES(1);
+
+  /* Map the reserved area */
+
+  ret = create_region(addrenv, resvbase, resvsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create reserved region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Map each region in turn FIXME: Remove W-flag after .elf is loaded */
+
+  ret = create_region(addrenv, textbase, textsize, MMU_UTEXT_FLAGS | PTE_W);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .text region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, database, datasize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .bss/.data region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, heapbase, heapsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create heap region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Save the heap base and initial size allocated. These will be needed when
+   * the heap data structures are initialized.
+   */
+
+  addrenv->heapvbase = heapbase;
+  addrenv->heapsize = (size_t)ret << MM_PGSHIFT;
+
+  /* Save the text base */
+
+  addrenv->textvbase = textbase;
+
+  /* Save the data base */
+
+  addrenv->datavbase = database;
+
+  /* Provide the satp value for context switch */
+
+  addrenv->satp = mmu_satp_reg(addrenv->spgtables[0], 0);
+
+  /* When all is set and done, flush the data caches */
+
+  __ISB();
+  __DMB();
+
+  return OK;
+
+errout:
+  up_addrenv_destroy(addrenv);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_destroy
+ *
+ * Description:
+ *   This function is called when a final thread leaves the task group and
+ *   the task group is destroyed.  This function then destroys the defunct
+ *   address environment, releasing the underlying physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - The address environment to be destroyed.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_destroy(FAR group_addrenv_t *addrenv)
+{
+  /* Recursively destroy it all, need to table walk */
+
+  uintptr_t *ptprev;
+  uintptr_t *ptlast;
+  uintptr_t  paddr;
+  int        i;
+  int        j;
+
+  DEBUGASSERT(addrenv);
+
+  /* Make sure the caches are flushed before doing this */
+
+  __ISB();
+  __DMB();
+
+  /* First destroy the allocated memory and the final level page table */
+
+  ptprev = (uintptr_t *)addrenv->spgtables[ARCH_SPGTS - 1];
+  if (ptprev)
+    {
+      for (i = 0; i < ENTRIES_PER_PGT; i++)
+        {
+          ptlast = (uintptr_t *)mmu_pte_to_paddr(ptprev[i]);
+          if (ptlast)
+            {
+              /* Page table allocated, free any allocated memory */
+
+              for (j = 0; j < ENTRIES_PER_PGT; j++)
+                {
+                  paddr = mmu_pte_to_paddr(ptlast[j]);
+                  if (paddr)
+                    {
+                      mm_pgfree(paddr, 1);
+                    }
+                }
+
+              /* Then free the page table itself */
+
+              mm_pgfree((uintptr_t)ptlast, 1);
+            }
+        }
+    }
+
+  /* Then destroy the static tables */
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = addrenv->spgtables[i];
+      if (paddr)
+        {
+          mm_pgfree(paddr, 1);
+        }
+    }
+
+  /* When all is set and done, flush the caches */
+
+  __ISB();
+  __DMB();
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vtext
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vtext - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vtext(FAR group_addrenv_t *addrenv, FAR void **vtext)
+{
+  DEBUGASSERT(addrenv && vtext);
+  *vtext = (FAR void *)addrenv->textvbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vdata
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   textsize - For some implementations, the text and data will be saved
+ *      in the same memory region (read/write/execute) and, in this case,
+ *      the virtual address of the data just lies at this offset into the
+ *      common region.
+ *   vdata - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vdata(FAR group_addrenv_t *addrenv, uintptr_t textsize,
+                     FAR void **vdata)
+{
+  DEBUGASSERT(addrenv && vdata);
+  *vdata = (FAR void *)addrenv->datavbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vheap
+ *
+ * Description:
+ *   Return the heap virtual address associated with the newly created
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vheap - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+int up_addrenv_vheap(FAR const group_addrenv_t *addrenv, FAR void **vheap)
+{
+  DEBUGASSERT(addrenv && vheap);
+  *vheap = (FAR void *)addrenv->heapvbase;
+  return OK;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_heapsize
+ *
+ * Description:
+ *   Return the initial heap allocation size.  That is the amount of memory
+ *   allocated by up_addrenv_create() when the heap memory region was first
+ *   created.  This may or may not differ from the heapsize parameter that
+ *   was passed to up_addrenv_create()
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *
+ * Returned Value:
+ *   The initial heap size allocated is returned on success; a negated
+ *   errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+ssize_t up_addrenv_heapsize(FAR const group_addrenv_t *addrenv)
+{
+  DEBUGASSERT(addrenv);
+  return (ssize_t)addrenv->heapsize;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_select
+ *
+ * Description:
+ *   After an address environment has been established for a task (via
+ *   up_addrenv_create()), this function may be called to instantiate
+ *   that address environment in the virtual address space.  This might be
+ *   necessary, for example, to load the code for the task from a file or
+ *   to access address environment private data.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *   oldenv
+ *     The address environment that was in place before up_addrenv_select().
+ *     This may be used with up_addrenv_restore() to restore the original
+ *     address environment that was in place before up_addrenv_select() was
+ *     called.  Note that this may be a task agnostic, hardware
+ *     representation that is different from group_addrenv_t.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_select(FAR const group_addrenv_t *addrenv,
+                      FAR save_addrenv_t *oldenv)

Review Comment:
   ```suggestion
   int up_addrenv_select(const group_addrenv_t *addrenv,
                         save_addrenv_t *oldenv)
   ```



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)
+{
+  int       ret;
+  uintptr_t resvbase;
+  uintptr_t resvsize;
+  uintptr_t textbase;
+  uintptr_t database;
+  uintptr_t heapbase;
+
+  DEBUGASSERT(addrenv);
+  DEBUGASSERT(MM_ISALIGNED(ADDRENV_VBASE));
+
+  /* Make sure the address environment is wiped before doing anything */
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+
+  /* Create the static page tables */
+
+  if (create_spgtables(addrenv) < 0)
+    {
+      serr("ERROR: Failed to create static page tables\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  if (copy_kernel_mappings(addrenv) < 0)
+    {
+      serr("ERROR: Failed to copy kernel mappings to new environment");
+      ret = -EINVAL;
+      goto errout;
+    }
+
+  /* Calculate the base addresses for convenience */
+
+  resvbase = ADDRENV_VBASE;
+  resvsize = ARCH_DATA_RESERVE_SIZE;
+  textbase = resvbase + MM_PGALIGNUP(resvsize);
+  database = textbase + MM_PGALIGNUP(textsize);
+  heapbase = database + MM_PGALIGNUP(datasize);
+
+  /* Allocate 1 extra page for heap, temporary fix for #5811 */
+
+  heapsize = heapsize + MM_NPAGES(1);
+
+  /* Map the reserved area */
+
+  ret = create_region(addrenv, resvbase, resvsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create reserved region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Map each region in turn FIXME: Remove W-flag after .elf is loaded */
+
+  ret = create_region(addrenv, textbase, textsize, MMU_UTEXT_FLAGS | PTE_W);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .text region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, database, datasize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .bss/.data region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, heapbase, heapsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create heap region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Save the heap base and initial size allocated. These will be needed when
+   * the heap data structures are initialized.
+   */
+
+  addrenv->heapvbase = heapbase;
+  addrenv->heapsize = (size_t)ret << MM_PGSHIFT;
+
+  /* Save the text base */
+
+  addrenv->textvbase = textbase;
+
+  /* Save the data base */
+
+  addrenv->datavbase = database;
+
+  /* Provide the satp value for context switch */
+
+  addrenv->satp = mmu_satp_reg(addrenv->spgtables[0], 0);
+
+  /* When all is set and done, flush the data caches */
+
+  __ISB();
+  __DMB();
+
+  return OK;
+
+errout:
+  up_addrenv_destroy(addrenv);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_destroy
+ *
+ * Description:
+ *   This function is called when a final thread leaves the task group and
+ *   the task group is destroyed.  This function then destroys the defunct
+ *   address environment, releasing the underlying physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - The address environment to be destroyed.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_destroy(FAR group_addrenv_t *addrenv)
+{
+  /* Recursively destroy it all, need to table walk */
+
+  uintptr_t *ptprev;
+  uintptr_t *ptlast;
+  uintptr_t  paddr;
+  int        i;
+  int        j;
+
+  DEBUGASSERT(addrenv);
+
+  /* Make sure the caches are flushed before doing this */
+
+  __ISB();
+  __DMB();
+
+  /* First destroy the allocated memory and the final level page table */
+
+  ptprev = (uintptr_t *)addrenv->spgtables[ARCH_SPGTS - 1];
+  if (ptprev)
+    {
+      for (i = 0; i < ENTRIES_PER_PGT; i++)
+        {
+          ptlast = (uintptr_t *)mmu_pte_to_paddr(ptprev[i]);
+          if (ptlast)
+            {
+              /* Page table allocated, free any allocated memory */
+
+              for (j = 0; j < ENTRIES_PER_PGT; j++)
+                {
+                  paddr = mmu_pte_to_paddr(ptlast[j]);
+                  if (paddr)
+                    {
+                      mm_pgfree(paddr, 1);
+                    }
+                }
+
+              /* Then free the page table itself */
+
+              mm_pgfree((uintptr_t)ptlast, 1);
+            }
+        }
+    }
+
+  /* Then destroy the static tables */
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = addrenv->spgtables[i];
+      if (paddr)
+        {
+          mm_pgfree(paddr, 1);
+        }
+    }
+
+  /* When all is set and done, flush the caches */
+
+  __ISB();
+  __DMB();
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vtext
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vtext - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vtext(FAR group_addrenv_t *addrenv, FAR void **vtext)
+{
+  DEBUGASSERT(addrenv && vtext);
+  *vtext = (FAR void *)addrenv->textvbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vdata
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   textsize - For some implementations, the text and data will be saved
+ *      in the same memory region (read/write/execute) and, in this case,
+ *      the virtual address of the data just lies at this offset into the
+ *      common region.
+ *   vdata - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vdata(FAR group_addrenv_t *addrenv, uintptr_t textsize,
+                     FAR void **vdata)
+{
+  DEBUGASSERT(addrenv && vdata);
+  *vdata = (FAR void *)addrenv->datavbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vheap
+ *
+ * Description:
+ *   Return the heap virtual address associated with the newly created
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vheap - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+int up_addrenv_vheap(FAR const group_addrenv_t *addrenv, FAR void **vheap)
+{
+  DEBUGASSERT(addrenv && vheap);
+  *vheap = (FAR void *)addrenv->heapvbase;
+  return OK;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_heapsize
+ *
+ * Description:
+ *   Return the initial heap allocation size.  That is the amount of memory
+ *   allocated by up_addrenv_create() when the heap memory region was first
+ *   created.  This may or may not differ from the heapsize parameter that
+ *   was passed to up_addrenv_create()
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *
+ * Returned Value:
+ *   The initial heap size allocated is returned on success; a negated
+ *   errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+ssize_t up_addrenv_heapsize(FAR const group_addrenv_t *addrenv)
+{
+  DEBUGASSERT(addrenv);
+  return (ssize_t)addrenv->heapsize;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_select
+ *
+ * Description:
+ *   After an address environment has been established for a task (via
+ *   up_addrenv_create()), this function may be called to instantiate
+ *   that address environment in the virtual address space.  This might be
+ *   necessary, for example, to load the code for the task from a file or
+ *   to access address environment private data.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *   oldenv
+ *     The address environment that was in place before up_addrenv_select().
+ *     This may be used with up_addrenv_restore() to restore the original
+ *     address environment that was in place before up_addrenv_select() was
+ *     called.  Note that this may be a task agnostic, hardware
+ *     representation that is different from group_addrenv_t.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_select(FAR const group_addrenv_t *addrenv,
+                      FAR save_addrenv_t *oldenv)
+{
+  DEBUGASSERT(addrenv);
+  if (oldenv)
+    {
+      /* Save the old environment */
+
+      uintptr_t satp_reg = mmu_read_satp();
+      *oldenv = (save_addrenv_t)satp_reg;
+    }
+
+  mmu_write_satp(addrenv->satp);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_restore
+ *
+ * Description:
+ *   After an address environment has been temporarily instantiated by
+ *   up_addrenv_select, this function may be called to restore the
+ *   original address environment.
+ *
+ * Input Parameters:
+ *   oldenv - The hardware representation of the address environment
+ *     previously returned by up_addrenv_select.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_restore(FAR const save_addrenv_t *oldenv)

Review Comment:
   ```suggestion
   int up_addrenv_restore(const save_addrenv_t *oldenv)
   ```



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);

Review Comment:
   do we need to check `vaddr != 0` or this is insured by the caller? I mean maybe adding `DEBUGASSERT(vaddr != 0);` can be reasonable here



##########
arch/risc-v/src/common/crt0.c:
##########
@@ -0,0 +1,137 @@
+/****************************************************************************
+ * arch/risc-v/src/common/crt0.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <arch/syscall.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/compiler.h>
+#include <nuttx/config.h>
+
+#include <sys/types.h>
+#include <stdlib.h>
+
+#ifdef CONFIG_BUILD_KERNEL
+
+/****************************************************************************
+ * Public Function Prototypes
+ ****************************************************************************/
+
+int main(int argc, char *argv[]);
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_signal_handler
+ *
+ * Description:
+ *   This function is the user-space, signal handler trampoline function.  It
+ *   is called from up_signal_dispatch() in user-mode.
+ *
+ * Input Parameters:
+ *   a0 = sighand
+ *     The address user-space signal handling function
+ *   a1-a3 = signo, info, and ucontext
+ *     Standard arguments to be passed to the signal handling function.
+ *
+ * Returned Value:
+ *   None.  This function does not return in the normal sense.  It returns
+ *   via the SYS_signal_handler_return (see syscall.h)
+ *
+ ****************************************************************************/
+
+static void sig_trampoline(void) naked_function;
+static void sig_trampoline(void)
+{
+  __asm__ __volatile__
+  (
+    " addi sp, sp, -16\n"   /* Save ra on the stack */
+    " sd   ra, 8(sp)\n"
+    " mv   t0, a0\n"        /* t0=sighand */
+    " mv   a0, a1\n"        /* a0=signo */
+    " mv   a1, a2\n"        /* a1=info */
+    " mv   a2, a3\n"        /* a2=ucontext */
+    " jalr t0\n"            /* Call the signal handler (modifies ra) */
+    " ld   ra, 8(sp)\n"     /* Recover ra in sp */

Review Comment:
   ```suggestion
       REGLOAD "   ra, 8(sp)\n"     /* Recover ra in sp */
   ```



##########
arch/risc-v/src/mpfs/mpfs_pgalloc.c:
##########
@@ -0,0 +1,67 @@
+/****************************************************************************
+ * arch/risc-v/src/mpfs/mpfs_pgalloc.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/arch.h>
+#include <nuttx/config.h>
+#include <nuttx/pgalloc.h>
+
+#include <assert.h>
+#include <debug.h>
+
+#include <arch/board/board_memorymap.h>
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Private Data
+ ****************************************************************************/
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_allocate_pgheap
+ *
+ * Description:
+ *   If there is a page allocator in the configuration, then this function
+ *   must be provided by the platform-specific code.  The OS initialization
+ *   logic will call this function early in the initialization sequence to
+ *   get the page heap information needed to configure the page allocator.
+ *
+ ****************************************************************************/
+
+void up_allocate_pgheap(FAR void **heap_start, size_t *heap_size)
+{
+  DEBUGASSERT(heap_start && heap_size);
+
+  *heap_start = (FAR void *)PGPOOL_START;

Review Comment:
   ```suggestion
     *heap_start = (void *)PGPOOL_START;
   ```



##########
arch/risc-v/src/common/riscv_pgalloc.c:
##########
@@ -0,0 +1,223 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_pgalloc.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+#include <debug.h>
+
+#include <nuttx/arch.h>
+#include <nuttx/addrenv.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+#include <nuttx/sched.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+#ifdef CONFIG_BUILD_KERNEL
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Last PGT level */
+
+#define PGT_LAST    (RV_MMU_PT_LEVELS)
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);

Review Comment:
   Do we need `DEBUGASSERT(vaddr != 0);` or non-NULL result is guaranteed by the caller?



##########
arch/risc-v/src/common/riscv_mmu.h:
##########
@@ -90,7 +94,7 @@
 
 #ifdef CONFIG_ARCH_MMU_TYPE_SV39
 #define RV_MMU_PTE_PADDR_SHIFT  (10)
-#define RV_MMU_PTE_PPN_MASK     ((1 << RV_MMU_PTE_PADDR_SHIFT) - 1)
+#define RV_MMU_PTE_PPN_MASK     (((1ul << 44) - 1) << RV_MMU_PTE_PADDR_SHIFT)

Review Comment:
   ```suggestion
   #define RV_MMU_PTE_PPN_MASK     (((UINT64_C(1) << 44) - 1) << RV_MMU_PTE_PADDR_SHIFT)
   ```



##########
arch/risc-v/src/common/crt0.c:
##########
@@ -0,0 +1,137 @@
+/****************************************************************************
+ * arch/risc-v/src/common/crt0.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <arch/syscall.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/compiler.h>
+#include <nuttx/config.h>
+
+#include <sys/types.h>
+#include <stdlib.h>
+
+#ifdef CONFIG_BUILD_KERNEL
+
+/****************************************************************************
+ * Public Function Prototypes
+ ****************************************************************************/
+
+int main(int argc, char *argv[]);
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_signal_handler
+ *
+ * Description:
+ *   This function is the user-space, signal handler trampoline function.  It
+ *   is called from up_signal_dispatch() in user-mode.
+ *
+ * Input Parameters:
+ *   a0 = sighand
+ *     The address user-space signal handling function
+ *   a1-a3 = signo, info, and ucontext
+ *     Standard arguments to be passed to the signal handling function.
+ *
+ * Returned Value:
+ *   None.  This function does not return in the normal sense.  It returns
+ *   via the SYS_signal_handler_return (see syscall.h)
+ *
+ ****************************************************************************/
+
+static void sig_trampoline(void) naked_function;
+static void sig_trampoline(void)
+{
+  __asm__ __volatile__
+  (
+    " addi sp, sp, -16\n"   /* Save ra on the stack */
+    " sd   ra, 8(sp)\n"

Review Comment:
   ```suggestion
       REGSTORE "   ra, 8(sp)\n"
   ```



##########
arch/risc-v/src/mpfs/mpfs_mm_init.c:
##########
@@ -0,0 +1,188 @@
+/****************************************************************************
+ * arch/risc-v/src/mpfs/mpfs_mm_init.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+#include <nuttx/arch.h>
+
+#include <stdint.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <arch/board/board_memorymap.h>
+
+#include "mpfs_memorymap.h"
+
+#include "riscv_internal.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* PMP settings */
+
+#define PMP_IO_FLAGS    (PMPCFG_A_NAPOT | PMPCFG_R | PMPCFG_W)
+#define PMP_RAM_FLAGS   (PMPCFG_A_NAPOT | PMPCFG_X | PMPCFG_R | PMPCFG_W)
+
+/* Open up (basically) the whole memory */
+
+#define PMP_IO_BASE     (MPFS_CLINT_BASE)
+#define PMP_IO_SIZE     (MPFS_DDR_BASE - MPFS_CLINT_BASE)
+#define PMP_RAM_BASE    (MPFS_DDR_BASE)
+#define PMP_RAM_SIZE    (MPFS_DDR_SIZE)
+
+/* Map the whole I/O memory with vaddr = paddr mappings */
+
+#define MMU_IO_BASE     (0x00000000)
+#define MMU_IO_SIZE     (0x80000000)
+
+/* Physical and virtual addresses to page tables (vaddr = paddr mapping) */
+
+#define PGT_L1_PBASE    (uintptr_t)&m_l1_pgtable
+#define PGT_L2_PBASE    (uintptr_t)&m_l2_pgtable
+#define PGT_L3_PBASE    (uintptr_t)&m_l3_pgtable
+#define PGT_L1_VBASE    PGT_L1_PBASE
+#define PGT_L2_VBASE    PGT_L2_PBASE
+#define PGT_L3_VBASE    PGT_L3_PBASE
+
+#define PGT_L1_SIZE     (512)  /* Enough to map 512 GiB */
+#define PGT_L2_SIZE     (512)  /* Enough to map 1 GiB */
+#define PGT_L3_SIZE     (1024) /* Enough to map 4 MiB */
+
+/****************************************************************************
+ * Private Data
+ ****************************************************************************/
+
+/* Kernel mappings simply here, mapping is vaddr=paddr */
+
+static uint64_t         m_l1_pgtable[PGT_L1_SIZE] locate_data(".pgtables");
+static uint64_t         m_l2_pgtable[PGT_L2_SIZE] locate_data(".pgtables");
+static uint64_t         m_l3_pgtable[PGT_L3_SIZE] locate_data(".pgtables");

Review Comment:
   Optional:
   ```suggestion
   static uintptr_t        m_l1_pgtable[PGT_L1_SIZE] locate_data(".pgtables");
   static uintptr_t        m_l2_pgtable[PGT_L2_SIZE] locate_data(".pgtables");
   static uintptr_t        m_l3_pgtable[PGT_L3_SIZE] locate_data(".pgtables");
   ```
   
   I'm not sure how much specific to MPFS is here, but looks like generic code. Maybe and be moved to common in future.



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)
+{
+  int       ret;
+  uintptr_t resvbase;
+  uintptr_t resvsize;
+  uintptr_t textbase;
+  uintptr_t database;
+  uintptr_t heapbase;
+
+  DEBUGASSERT(addrenv);
+  DEBUGASSERT(MM_ISALIGNED(ADDRENV_VBASE));
+
+  /* Make sure the address environment is wiped before doing anything */
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+
+  /* Create the static page tables */
+
+  if (create_spgtables(addrenv) < 0)
+    {
+      serr("ERROR: Failed to create static page tables\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  if (copy_kernel_mappings(addrenv) < 0)
+    {
+      serr("ERROR: Failed to copy kernel mappings to new environment");
+      ret = -EINVAL;
+      goto errout;
+    }
+
+  /* Calculate the base addresses for convenience */
+
+  resvbase = ADDRENV_VBASE;
+  resvsize = ARCH_DATA_RESERVE_SIZE;
+  textbase = resvbase + MM_PGALIGNUP(resvsize);
+  database = textbase + MM_PGALIGNUP(textsize);
+  heapbase = database + MM_PGALIGNUP(datasize);
+
+  /* Allocate 1 extra page for heap, temporary fix for #5811 */
+
+  heapsize = heapsize + MM_NPAGES(1);
+
+  /* Map the reserved area */
+
+  ret = create_region(addrenv, resvbase, resvsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create reserved region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Map each region in turn FIXME: Remove W-flag after .elf is loaded */
+
+  ret = create_region(addrenv, textbase, textsize, MMU_UTEXT_FLAGS | PTE_W);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .text region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, database, datasize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .bss/.data region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, heapbase, heapsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create heap region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Save the heap base and initial size allocated. These will be needed when
+   * the heap data structures are initialized.
+   */
+
+  addrenv->heapvbase = heapbase;
+  addrenv->heapsize = (size_t)ret << MM_PGSHIFT;
+
+  /* Save the text base */
+
+  addrenv->textvbase = textbase;
+
+  /* Save the data base */
+
+  addrenv->datavbase = database;
+
+  /* Provide the satp value for context switch */
+
+  addrenv->satp = mmu_satp_reg(addrenv->spgtables[0], 0);
+
+  /* When all is set and done, flush the data caches */
+
+  __ISB();
+  __DMB();
+
+  return OK;
+
+errout:
+  up_addrenv_destroy(addrenv);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_destroy
+ *
+ * Description:
+ *   This function is called when a final thread leaves the task group and
+ *   the task group is destroyed.  This function then destroys the defunct
+ *   address environment, releasing the underlying physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - The address environment to be destroyed.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_destroy(FAR group_addrenv_t *addrenv)

Review Comment:
   ```suggestion
   int up_addrenv_destroy(group_addrenv_t *addrenv)
   ```



##########
arch/risc-v/src/common/crt0.c:
##########
@@ -0,0 +1,137 @@
+/****************************************************************************
+ * arch/risc-v/src/common/crt0.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <arch/syscall.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/compiler.h>
+#include <nuttx/config.h>
+
+#include <sys/types.h>
+#include <stdlib.h>
+
+#ifdef CONFIG_BUILD_KERNEL
+
+/****************************************************************************
+ * Public Function Prototypes
+ ****************************************************************************/
+
+int main(int argc, char *argv[]);
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_signal_handler
+ *
+ * Description:
+ *   This function is the user-space, signal handler trampoline function.  It
+ *   is called from up_signal_dispatch() in user-mode.
+ *
+ * Input Parameters:
+ *   a0 = sighand
+ *     The address user-space signal handling function
+ *   a1-a3 = signo, info, and ucontext
+ *     Standard arguments to be passed to the signal handling function.
+ *
+ * Returned Value:
+ *   None.  This function does not return in the normal sense.  It returns
+ *   via the SYS_signal_handler_return (see syscall.h)
+ *
+ ****************************************************************************/
+
+static void sig_trampoline(void) naked_function;
+static void sig_trampoline(void)
+{
+  __asm__ __volatile__
+  (
+    " addi sp, sp, -16\n"   /* Save ra on the stack */

Review Comment:
   ```suggestion
       " addi sp, sp, -" STACK_FRAME_SIZE "\n"   /* Save ra on the stack */
   ```



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)
+{
+  int       ret;
+  uintptr_t resvbase;
+  uintptr_t resvsize;
+  uintptr_t textbase;
+  uintptr_t database;
+  uintptr_t heapbase;
+
+  DEBUGASSERT(addrenv);
+  DEBUGASSERT(MM_ISALIGNED(ADDRENV_VBASE));
+
+  /* Make sure the address environment is wiped before doing anything */
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+
+  /* Create the static page tables */
+
+  if (create_spgtables(addrenv) < 0)
+    {
+      serr("ERROR: Failed to create static page tables\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  if (copy_kernel_mappings(addrenv) < 0)
+    {
+      serr("ERROR: Failed to copy kernel mappings to new environment");
+      ret = -EINVAL;
+      goto errout;
+    }
+
+  /* Calculate the base addresses for convenience */
+
+  resvbase = ADDRENV_VBASE;
+  resvsize = ARCH_DATA_RESERVE_SIZE;
+  textbase = resvbase + MM_PGALIGNUP(resvsize);
+  database = textbase + MM_PGALIGNUP(textsize);
+  heapbase = database + MM_PGALIGNUP(datasize);
+
+  /* Allocate 1 extra page for heap, temporary fix for #5811 */
+
+  heapsize = heapsize + MM_NPAGES(1);
+
+  /* Map the reserved area */
+
+  ret = create_region(addrenv, resvbase, resvsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create reserved region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Map each region in turn FIXME: Remove W-flag after .elf is loaded */
+
+  ret = create_region(addrenv, textbase, textsize, MMU_UTEXT_FLAGS | PTE_W);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .text region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, database, datasize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .bss/.data region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, heapbase, heapsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create heap region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Save the heap base and initial size allocated. These will be needed when
+   * the heap data structures are initialized.
+   */
+
+  addrenv->heapvbase = heapbase;
+  addrenv->heapsize = (size_t)ret << MM_PGSHIFT;
+
+  /* Save the text base */
+
+  addrenv->textvbase = textbase;
+
+  /* Save the data base */
+
+  addrenv->datavbase = database;
+
+  /* Provide the satp value for context switch */
+
+  addrenv->satp = mmu_satp_reg(addrenv->spgtables[0], 0);
+
+  /* When all is set and done, flush the data caches */
+
+  __ISB();
+  __DMB();
+
+  return OK;
+
+errout:
+  up_addrenv_destroy(addrenv);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_destroy
+ *
+ * Description:
+ *   This function is called when a final thread leaves the task group and
+ *   the task group is destroyed.  This function then destroys the defunct
+ *   address environment, releasing the underlying physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - The address environment to be destroyed.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_destroy(FAR group_addrenv_t *addrenv)
+{
+  /* Recursively destroy it all, need to table walk */
+
+  uintptr_t *ptprev;
+  uintptr_t *ptlast;
+  uintptr_t  paddr;
+  int        i;
+  int        j;
+
+  DEBUGASSERT(addrenv);
+
+  /* Make sure the caches are flushed before doing this */
+
+  __ISB();
+  __DMB();
+
+  /* First destroy the allocated memory and the final level page table */
+
+  ptprev = (uintptr_t *)addrenv->spgtables[ARCH_SPGTS - 1];
+  if (ptprev)
+    {
+      for (i = 0; i < ENTRIES_PER_PGT; i++)
+        {
+          ptlast = (uintptr_t *)mmu_pte_to_paddr(ptprev[i]);
+          if (ptlast)
+            {
+              /* Page table allocated, free any allocated memory */
+
+              for (j = 0; j < ENTRIES_PER_PGT; j++)
+                {
+                  paddr = mmu_pte_to_paddr(ptlast[j]);
+                  if (paddr)
+                    {
+                      mm_pgfree(paddr, 1);
+                    }
+                }
+
+              /* Then free the page table itself */
+
+              mm_pgfree((uintptr_t)ptlast, 1);
+            }
+        }
+    }
+
+  /* Then destroy the static tables */
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = addrenv->spgtables[i];
+      if (paddr)
+        {
+          mm_pgfree(paddr, 1);
+        }
+    }
+
+  /* When all is set and done, flush the caches */
+
+  __ISB();
+  __DMB();
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vtext
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vtext - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vtext(FAR group_addrenv_t *addrenv, FAR void **vtext)
+{
+  DEBUGASSERT(addrenv && vtext);
+  *vtext = (FAR void *)addrenv->textvbase;

Review Comment:
   ```suggestion
     *vtext = (void *)addrenv->textvbase;
   ```



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)
+{
+  int       ret;
+  uintptr_t resvbase;
+  uintptr_t resvsize;
+  uintptr_t textbase;
+  uintptr_t database;
+  uintptr_t heapbase;
+
+  DEBUGASSERT(addrenv);
+  DEBUGASSERT(MM_ISALIGNED(ADDRENV_VBASE));
+
+  /* Make sure the address environment is wiped before doing anything */
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+
+  /* Create the static page tables */
+
+  if (create_spgtables(addrenv) < 0)
+    {
+      serr("ERROR: Failed to create static page tables\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  if (copy_kernel_mappings(addrenv) < 0)
+    {
+      serr("ERROR: Failed to copy kernel mappings to new environment");
+      ret = -EINVAL;
+      goto errout;
+    }
+
+  /* Calculate the base addresses for convenience */
+
+  resvbase = ADDRENV_VBASE;
+  resvsize = ARCH_DATA_RESERVE_SIZE;
+  textbase = resvbase + MM_PGALIGNUP(resvsize);
+  database = textbase + MM_PGALIGNUP(textsize);
+  heapbase = database + MM_PGALIGNUP(datasize);
+
+  /* Allocate 1 extra page for heap, temporary fix for #5811 */
+
+  heapsize = heapsize + MM_NPAGES(1);
+
+  /* Map the reserved area */
+
+  ret = create_region(addrenv, resvbase, resvsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create reserved region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Map each region in turn FIXME: Remove W-flag after .elf is loaded */
+
+  ret = create_region(addrenv, textbase, textsize, MMU_UTEXT_FLAGS | PTE_W);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .text region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, database, datasize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .bss/.data region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, heapbase, heapsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create heap region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Save the heap base and initial size allocated. These will be needed when
+   * the heap data structures are initialized.
+   */
+
+  addrenv->heapvbase = heapbase;
+  addrenv->heapsize = (size_t)ret << MM_PGSHIFT;
+
+  /* Save the text base */
+
+  addrenv->textvbase = textbase;
+
+  /* Save the data base */
+
+  addrenv->datavbase = database;
+
+  /* Provide the satp value for context switch */
+
+  addrenv->satp = mmu_satp_reg(addrenv->spgtables[0], 0);
+
+  /* When all is set and done, flush the data caches */
+
+  __ISB();
+  __DMB();
+
+  return OK;
+
+errout:
+  up_addrenv_destroy(addrenv);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_destroy
+ *
+ * Description:
+ *   This function is called when a final thread leaves the task group and
+ *   the task group is destroyed.  This function then destroys the defunct
+ *   address environment, releasing the underlying physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - The address environment to be destroyed.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_destroy(FAR group_addrenv_t *addrenv)
+{
+  /* Recursively destroy it all, need to table walk */
+
+  uintptr_t *ptprev;
+  uintptr_t *ptlast;
+  uintptr_t  paddr;
+  int        i;
+  int        j;
+
+  DEBUGASSERT(addrenv);
+
+  /* Make sure the caches are flushed before doing this */
+
+  __ISB();
+  __DMB();
+
+  /* First destroy the allocated memory and the final level page table */
+
+  ptprev = (uintptr_t *)addrenv->spgtables[ARCH_SPGTS - 1];
+  if (ptprev)
+    {
+      for (i = 0; i < ENTRIES_PER_PGT; i++)
+        {
+          ptlast = (uintptr_t *)mmu_pte_to_paddr(ptprev[i]);
+          if (ptlast)
+            {
+              /* Page table allocated, free any allocated memory */
+
+              for (j = 0; j < ENTRIES_PER_PGT; j++)
+                {
+                  paddr = mmu_pte_to_paddr(ptlast[j]);
+                  if (paddr)
+                    {
+                      mm_pgfree(paddr, 1);
+                    }
+                }
+
+              /* Then free the page table itself */
+
+              mm_pgfree((uintptr_t)ptlast, 1);
+            }
+        }
+    }
+
+  /* Then destroy the static tables */
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = addrenv->spgtables[i];
+      if (paddr)
+        {
+          mm_pgfree(paddr, 1);
+        }
+    }
+
+  /* When all is set and done, flush the caches */
+
+  __ISB();
+  __DMB();
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vtext
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vtext - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vtext(FAR group_addrenv_t *addrenv, FAR void **vtext)

Review Comment:
   ```suggestion
   int up_addrenv_vtext(group_addrenv_t *addrenv, void **vtext)
   ```



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)
+{
+  int       ret;
+  uintptr_t resvbase;
+  uintptr_t resvsize;
+  uintptr_t textbase;
+  uintptr_t database;
+  uintptr_t heapbase;
+
+  DEBUGASSERT(addrenv);
+  DEBUGASSERT(MM_ISALIGNED(ADDRENV_VBASE));
+
+  /* Make sure the address environment is wiped before doing anything */
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+
+  /* Create the static page tables */
+
+  if (create_spgtables(addrenv) < 0)
+    {
+      serr("ERROR: Failed to create static page tables\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  if (copy_kernel_mappings(addrenv) < 0)
+    {
+      serr("ERROR: Failed to copy kernel mappings to new environment");
+      ret = -EINVAL;
+      goto errout;
+    }
+
+  /* Calculate the base addresses for convenience */
+
+  resvbase = ADDRENV_VBASE;
+  resvsize = ARCH_DATA_RESERVE_SIZE;
+  textbase = resvbase + MM_PGALIGNUP(resvsize);
+  database = textbase + MM_PGALIGNUP(textsize);
+  heapbase = database + MM_PGALIGNUP(datasize);
+
+  /* Allocate 1 extra page for heap, temporary fix for #5811 */
+
+  heapsize = heapsize + MM_NPAGES(1);
+
+  /* Map the reserved area */
+
+  ret = create_region(addrenv, resvbase, resvsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create reserved region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Map each region in turn FIXME: Remove W-flag after .elf is loaded */
+
+  ret = create_region(addrenv, textbase, textsize, MMU_UTEXT_FLAGS | PTE_W);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .text region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, database, datasize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .bss/.data region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, heapbase, heapsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create heap region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Save the heap base and initial size allocated. These will be needed when
+   * the heap data structures are initialized.
+   */
+
+  addrenv->heapvbase = heapbase;
+  addrenv->heapsize = (size_t)ret << MM_PGSHIFT;
+
+  /* Save the text base */
+
+  addrenv->textvbase = textbase;
+
+  /* Save the data base */
+
+  addrenv->datavbase = database;
+
+  /* Provide the satp value for context switch */
+
+  addrenv->satp = mmu_satp_reg(addrenv->spgtables[0], 0);
+
+  /* When all is set and done, flush the data caches */
+
+  __ISB();
+  __DMB();
+
+  return OK;
+
+errout:
+  up_addrenv_destroy(addrenv);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_destroy
+ *
+ * Description:
+ *   This function is called when a final thread leaves the task group and
+ *   the task group is destroyed.  This function then destroys the defunct
+ *   address environment, releasing the underlying physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - The address environment to be destroyed.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_destroy(FAR group_addrenv_t *addrenv)
+{
+  /* Recursively destroy it all, need to table walk */
+
+  uintptr_t *ptprev;
+  uintptr_t *ptlast;
+  uintptr_t  paddr;
+  int        i;
+  int        j;
+
+  DEBUGASSERT(addrenv);
+
+  /* Make sure the caches are flushed before doing this */
+
+  __ISB();
+  __DMB();
+
+  /* First destroy the allocated memory and the final level page table */
+
+  ptprev = (uintptr_t *)addrenv->spgtables[ARCH_SPGTS - 1];
+  if (ptprev)
+    {
+      for (i = 0; i < ENTRIES_PER_PGT; i++)
+        {
+          ptlast = (uintptr_t *)mmu_pte_to_paddr(ptprev[i]);
+          if (ptlast)
+            {
+              /* Page table allocated, free any allocated memory */
+
+              for (j = 0; j < ENTRIES_PER_PGT; j++)
+                {
+                  paddr = mmu_pte_to_paddr(ptlast[j]);
+                  if (paddr)
+                    {
+                      mm_pgfree(paddr, 1);
+                    }
+                }
+
+              /* Then free the page table itself */
+
+              mm_pgfree((uintptr_t)ptlast, 1);
+            }
+        }
+    }
+
+  /* Then destroy the static tables */
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = addrenv->spgtables[i];
+      if (paddr)
+        {
+          mm_pgfree(paddr, 1);
+        }
+    }
+
+  /* When all is set and done, flush the caches */
+
+  __ISB();
+  __DMB();
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vtext
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vtext - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vtext(FAR group_addrenv_t *addrenv, FAR void **vtext)
+{
+  DEBUGASSERT(addrenv && vtext);
+  *vtext = (FAR void *)addrenv->textvbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vdata
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   textsize - For some implementations, the text and data will be saved
+ *      in the same memory region (read/write/execute) and, in this case,
+ *      the virtual address of the data just lies at this offset into the
+ *      common region.
+ *   vdata - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vdata(FAR group_addrenv_t *addrenv, uintptr_t textsize,
+                     FAR void **vdata)
+{
+  DEBUGASSERT(addrenv && vdata);
+  *vdata = (FAR void *)addrenv->datavbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vheap
+ *
+ * Description:
+ *   Return the heap virtual address associated with the newly created
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vheap - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+int up_addrenv_vheap(FAR const group_addrenv_t *addrenv, FAR void **vheap)
+{
+  DEBUGASSERT(addrenv && vheap);
+  *vheap = (FAR void *)addrenv->heapvbase;
+  return OK;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_heapsize
+ *
+ * Description:
+ *   Return the initial heap allocation size.  That is the amount of memory
+ *   allocated by up_addrenv_create() when the heap memory region was first
+ *   created.  This may or may not differ from the heapsize parameter that
+ *   was passed to up_addrenv_create()
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *
+ * Returned Value:
+ *   The initial heap size allocated is returned on success; a negated
+ *   errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+ssize_t up_addrenv_heapsize(FAR const group_addrenv_t *addrenv)

Review Comment:
   ```suggestion
   ssize_t up_addrenv_heapsize(const group_addrenv_t *addrenv)
   ```



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)
+{
+  int       ret;
+  uintptr_t resvbase;
+  uintptr_t resvsize;
+  uintptr_t textbase;
+  uintptr_t database;
+  uintptr_t heapbase;
+
+  DEBUGASSERT(addrenv);
+  DEBUGASSERT(MM_ISALIGNED(ADDRENV_VBASE));
+
+  /* Make sure the address environment is wiped before doing anything */
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+
+  /* Create the static page tables */
+
+  if (create_spgtables(addrenv) < 0)
+    {
+      serr("ERROR: Failed to create static page tables\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  if (copy_kernel_mappings(addrenv) < 0)
+    {
+      serr("ERROR: Failed to copy kernel mappings to new environment");
+      ret = -EINVAL;
+      goto errout;
+    }
+
+  /* Calculate the base addresses for convenience */
+
+  resvbase = ADDRENV_VBASE;
+  resvsize = ARCH_DATA_RESERVE_SIZE;
+  textbase = resvbase + MM_PGALIGNUP(resvsize);
+  database = textbase + MM_PGALIGNUP(textsize);
+  heapbase = database + MM_PGALIGNUP(datasize);
+
+  /* Allocate 1 extra page for heap, temporary fix for #5811 */
+
+  heapsize = heapsize + MM_NPAGES(1);
+
+  /* Map the reserved area */
+
+  ret = create_region(addrenv, resvbase, resvsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create reserved region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Map each region in turn FIXME: Remove W-flag after .elf is loaded */
+
+  ret = create_region(addrenv, textbase, textsize, MMU_UTEXT_FLAGS | PTE_W);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .text region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, database, datasize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .bss/.data region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, heapbase, heapsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create heap region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Save the heap base and initial size allocated. These will be needed when
+   * the heap data structures are initialized.
+   */
+
+  addrenv->heapvbase = heapbase;
+  addrenv->heapsize = (size_t)ret << MM_PGSHIFT;
+
+  /* Save the text base */
+
+  addrenv->textvbase = textbase;
+
+  /* Save the data base */
+
+  addrenv->datavbase = database;
+
+  /* Provide the satp value for context switch */
+
+  addrenv->satp = mmu_satp_reg(addrenv->spgtables[0], 0);
+
+  /* When all is set and done, flush the data caches */
+
+  __ISB();
+  __DMB();
+
+  return OK;
+
+errout:
+  up_addrenv_destroy(addrenv);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_destroy
+ *
+ * Description:
+ *   This function is called when a final thread leaves the task group and
+ *   the task group is destroyed.  This function then destroys the defunct
+ *   address environment, releasing the underlying physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - The address environment to be destroyed.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_destroy(FAR group_addrenv_t *addrenv)
+{
+  /* Recursively destroy it all, need to table walk */
+
+  uintptr_t *ptprev;
+  uintptr_t *ptlast;
+  uintptr_t  paddr;
+  int        i;
+  int        j;
+
+  DEBUGASSERT(addrenv);
+
+  /* Make sure the caches are flushed before doing this */
+
+  __ISB();
+  __DMB();
+
+  /* First destroy the allocated memory and the final level page table */
+
+  ptprev = (uintptr_t *)addrenv->spgtables[ARCH_SPGTS - 1];
+  if (ptprev)
+    {
+      for (i = 0; i < ENTRIES_PER_PGT; i++)
+        {
+          ptlast = (uintptr_t *)mmu_pte_to_paddr(ptprev[i]);
+          if (ptlast)
+            {
+              /* Page table allocated, free any allocated memory */
+
+              for (j = 0; j < ENTRIES_PER_PGT; j++)
+                {
+                  paddr = mmu_pte_to_paddr(ptlast[j]);
+                  if (paddr)
+                    {
+                      mm_pgfree(paddr, 1);
+                    }
+                }
+
+              /* Then free the page table itself */
+
+              mm_pgfree((uintptr_t)ptlast, 1);
+            }
+        }
+    }
+
+  /* Then destroy the static tables */
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = addrenv->spgtables[i];
+      if (paddr)
+        {
+          mm_pgfree(paddr, 1);
+        }
+    }
+
+  /* When all is set and done, flush the caches */
+
+  __ISB();
+  __DMB();
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vtext
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vtext - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vtext(FAR group_addrenv_t *addrenv, FAR void **vtext)
+{
+  DEBUGASSERT(addrenv && vtext);
+  *vtext = (FAR void *)addrenv->textvbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vdata
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   textsize - For some implementations, the text and data will be saved
+ *      in the same memory region (read/write/execute) and, in this case,
+ *      the virtual address of the data just lies at this offset into the
+ *      common region.
+ *   vdata - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vdata(FAR group_addrenv_t *addrenv, uintptr_t textsize,
+                     FAR void **vdata)
+{
+  DEBUGASSERT(addrenv && vdata);
+  *vdata = (FAR void *)addrenv->datavbase;

Review Comment:
   ```suggestion
   int up_addrenv_vdata(group_addrenv_t *addrenv, uintptr_t textsize,
                        void **vdata)
   {
     DEBUGASSERT(addrenv && vdata);
     *vdata = (void *)addrenv->datavbase;
   ```



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)
+{
+  int       ret;
+  uintptr_t resvbase;
+  uintptr_t resvsize;
+  uintptr_t textbase;
+  uintptr_t database;
+  uintptr_t heapbase;
+
+  DEBUGASSERT(addrenv);
+  DEBUGASSERT(MM_ISALIGNED(ADDRENV_VBASE));
+
+  /* Make sure the address environment is wiped before doing anything */
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+
+  /* Create the static page tables */
+
+  if (create_spgtables(addrenv) < 0)
+    {
+      serr("ERROR: Failed to create static page tables\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  if (copy_kernel_mappings(addrenv) < 0)
+    {
+      serr("ERROR: Failed to copy kernel mappings to new environment");
+      ret = -EINVAL;
+      goto errout;
+    }
+
+  /* Calculate the base addresses for convenience */
+
+  resvbase = ADDRENV_VBASE;
+  resvsize = ARCH_DATA_RESERVE_SIZE;
+  textbase = resvbase + MM_PGALIGNUP(resvsize);
+  database = textbase + MM_PGALIGNUP(textsize);
+  heapbase = database + MM_PGALIGNUP(datasize);
+
+  /* Allocate 1 extra page for heap, temporary fix for #5811 */
+
+  heapsize = heapsize + MM_NPAGES(1);
+
+  /* Map the reserved area */
+
+  ret = create_region(addrenv, resvbase, resvsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create reserved region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Map each region in turn FIXME: Remove W-flag after .elf is loaded */
+
+  ret = create_region(addrenv, textbase, textsize, MMU_UTEXT_FLAGS | PTE_W);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .text region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, database, datasize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .bss/.data region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, heapbase, heapsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create heap region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Save the heap base and initial size allocated. These will be needed when
+   * the heap data structures are initialized.
+   */
+
+  addrenv->heapvbase = heapbase;
+  addrenv->heapsize = (size_t)ret << MM_PGSHIFT;
+
+  /* Save the text base */
+
+  addrenv->textvbase = textbase;
+
+  /* Save the data base */
+
+  addrenv->datavbase = database;
+
+  /* Provide the satp value for context switch */
+
+  addrenv->satp = mmu_satp_reg(addrenv->spgtables[0], 0);
+
+  /* When all is set and done, flush the data caches */
+
+  __ISB();
+  __DMB();
+
+  return OK;
+
+errout:
+  up_addrenv_destroy(addrenv);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_destroy
+ *
+ * Description:
+ *   This function is called when a final thread leaves the task group and
+ *   the task group is destroyed.  This function then destroys the defunct
+ *   address environment, releasing the underlying physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - The address environment to be destroyed.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_destroy(FAR group_addrenv_t *addrenv)
+{
+  /* Recursively destroy it all, need to table walk */
+
+  uintptr_t *ptprev;
+  uintptr_t *ptlast;
+  uintptr_t  paddr;
+  int        i;
+  int        j;
+
+  DEBUGASSERT(addrenv);
+
+  /* Make sure the caches are flushed before doing this */
+
+  __ISB();
+  __DMB();
+
+  /* First destroy the allocated memory and the final level page table */
+
+  ptprev = (uintptr_t *)addrenv->spgtables[ARCH_SPGTS - 1];
+  if (ptprev)
+    {
+      for (i = 0; i < ENTRIES_PER_PGT; i++)
+        {
+          ptlast = (uintptr_t *)mmu_pte_to_paddr(ptprev[i]);
+          if (ptlast)
+            {
+              /* Page table allocated, free any allocated memory */
+
+              for (j = 0; j < ENTRIES_PER_PGT; j++)
+                {
+                  paddr = mmu_pte_to_paddr(ptlast[j]);
+                  if (paddr)
+                    {
+                      mm_pgfree(paddr, 1);
+                    }
+                }
+
+              /* Then free the page table itself */
+
+              mm_pgfree((uintptr_t)ptlast, 1);
+            }
+        }
+    }
+
+  /* Then destroy the static tables */
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = addrenv->spgtables[i];
+      if (paddr)
+        {
+          mm_pgfree(paddr, 1);
+        }
+    }
+
+  /* When all is set and done, flush the caches */
+
+  __ISB();
+  __DMB();
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vtext
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vtext - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vtext(FAR group_addrenv_t *addrenv, FAR void **vtext)
+{
+  DEBUGASSERT(addrenv && vtext);
+  *vtext = (FAR void *)addrenv->textvbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vdata
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   textsize - For some implementations, the text and data will be saved
+ *      in the same memory region (read/write/execute) and, in this case,
+ *      the virtual address of the data just lies at this offset into the
+ *      common region.
+ *   vdata - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vdata(FAR group_addrenv_t *addrenv, uintptr_t textsize,
+                     FAR void **vdata)
+{
+  DEBUGASSERT(addrenv && vdata);
+  *vdata = (FAR void *)addrenv->datavbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vheap
+ *
+ * Description:
+ *   Return the heap virtual address associated with the newly created
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vheap - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+int up_addrenv_vheap(FAR const group_addrenv_t *addrenv, FAR void **vheap)
+{
+  DEBUGASSERT(addrenv && vheap);
+  *vheap = (FAR void *)addrenv->heapvbase;
+  return OK;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_heapsize
+ *
+ * Description:
+ *   Return the initial heap allocation size.  That is the amount of memory
+ *   allocated by up_addrenv_create() when the heap memory region was first
+ *   created.  This may or may not differ from the heapsize parameter that
+ *   was passed to up_addrenv_create()
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *
+ * Returned Value:
+ *   The initial heap size allocated is returned on success; a negated
+ *   errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+ssize_t up_addrenv_heapsize(FAR const group_addrenv_t *addrenv)
+{
+  DEBUGASSERT(addrenv);
+  return (ssize_t)addrenv->heapsize;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_select
+ *
+ * Description:
+ *   After an address environment has been established for a task (via
+ *   up_addrenv_create()), this function may be called to instantiate
+ *   that address environment in the virtual address space.  This might be
+ *   necessary, for example, to load the code for the task from a file or
+ *   to access address environment private data.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *   oldenv
+ *     The address environment that was in place before up_addrenv_select().
+ *     This may be used with up_addrenv_restore() to restore the original
+ *     address environment that was in place before up_addrenv_select() was
+ *     called.  Note that this may be a task agnostic, hardware
+ *     representation that is different from group_addrenv_t.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_select(FAR const group_addrenv_t *addrenv,
+                      FAR save_addrenv_t *oldenv)
+{
+  DEBUGASSERT(addrenv);
+  if (oldenv)
+    {
+      /* Save the old environment */
+
+      uintptr_t satp_reg = mmu_read_satp();
+      *oldenv = (save_addrenv_t)satp_reg;
+    }
+
+  mmu_write_satp(addrenv->satp);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_restore
+ *
+ * Description:
+ *   After an address environment has been temporarily instantiated by
+ *   up_addrenv_select, this function may be called to restore the
+ *   original address environment.
+ *
+ * Input Parameters:
+ *   oldenv - The hardware representation of the address environment
+ *     previously returned by up_addrenv_select.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_restore(FAR const save_addrenv_t *oldenv)
+{
+  DEBUGASSERT(oldenv);
+  mmu_write_satp((uintptr_t)*oldenv);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_coherent
+ *
+ * Description:
+ *   Flush D-Cache and invalidate I-Cache in preparation for a change in
+ *   address environments.  This should immediately precede a call to
+ *   up_addrenv_select();
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment to be made coherent.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_coherent(FAR const group_addrenv_t *addrenv)

Review Comment:
   ```suggestion
   int up_addrenv_coherent(const group_addrenv_t *addrenv)
   ```



##########
arch/risc-v/src/common/riscv_mmu.h:
##########
@@ -90,7 +94,7 @@
 
 #ifdef CONFIG_ARCH_MMU_TYPE_SV39
 #define RV_MMU_PTE_PADDR_SHIFT  (10)
-#define RV_MMU_PTE_PPN_MASK     ((1 << RV_MMU_PTE_PADDR_SHIFT) - 1)
+#define RV_MMU_PTE_PPN_MASK     (((1ul << 44) - 1) << RV_MMU_PTE_PADDR_SHIFT)

Review Comment:
   Is `<< 44` applicable for both RV32 and RV64?



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)
+{
+  int       ret;
+  uintptr_t resvbase;
+  uintptr_t resvsize;
+  uintptr_t textbase;
+  uintptr_t database;
+  uintptr_t heapbase;
+
+  DEBUGASSERT(addrenv);
+  DEBUGASSERT(MM_ISALIGNED(ADDRENV_VBASE));
+
+  /* Make sure the address environment is wiped before doing anything */
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+
+  /* Create the static page tables */
+
+  if (create_spgtables(addrenv) < 0)
+    {
+      serr("ERROR: Failed to create static page tables\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  if (copy_kernel_mappings(addrenv) < 0)
+    {
+      serr("ERROR: Failed to copy kernel mappings to new environment");
+      ret = -EINVAL;
+      goto errout;
+    }
+
+  /* Calculate the base addresses for convenience */
+
+  resvbase = ADDRENV_VBASE;
+  resvsize = ARCH_DATA_RESERVE_SIZE;
+  textbase = resvbase + MM_PGALIGNUP(resvsize);
+  database = textbase + MM_PGALIGNUP(textsize);
+  heapbase = database + MM_PGALIGNUP(datasize);
+
+  /* Allocate 1 extra page for heap, temporary fix for #5811 */
+
+  heapsize = heapsize + MM_NPAGES(1);
+
+  /* Map the reserved area */
+
+  ret = create_region(addrenv, resvbase, resvsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create reserved region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Map each region in turn FIXME: Remove W-flag after .elf is loaded */
+
+  ret = create_region(addrenv, textbase, textsize, MMU_UTEXT_FLAGS | PTE_W);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .text region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, database, datasize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .bss/.data region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, heapbase, heapsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create heap region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Save the heap base and initial size allocated. These will be needed when
+   * the heap data structures are initialized.
+   */
+
+  addrenv->heapvbase = heapbase;
+  addrenv->heapsize = (size_t)ret << MM_PGSHIFT;
+
+  /* Save the text base */
+
+  addrenv->textvbase = textbase;
+
+  /* Save the data base */
+
+  addrenv->datavbase = database;
+
+  /* Provide the satp value for context switch */
+
+  addrenv->satp = mmu_satp_reg(addrenv->spgtables[0], 0);
+
+  /* When all is set and done, flush the data caches */
+
+  __ISB();
+  __DMB();
+
+  return OK;
+
+errout:
+  up_addrenv_destroy(addrenv);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_destroy
+ *
+ * Description:
+ *   This function is called when a final thread leaves the task group and
+ *   the task group is destroyed.  This function then destroys the defunct
+ *   address environment, releasing the underlying physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - The address environment to be destroyed.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_destroy(FAR group_addrenv_t *addrenv)
+{
+  /* Recursively destroy it all, need to table walk */
+
+  uintptr_t *ptprev;
+  uintptr_t *ptlast;
+  uintptr_t  paddr;
+  int        i;
+  int        j;
+
+  DEBUGASSERT(addrenv);
+
+  /* Make sure the caches are flushed before doing this */
+
+  __ISB();
+  __DMB();
+
+  /* First destroy the allocated memory and the final level page table */
+
+  ptprev = (uintptr_t *)addrenv->spgtables[ARCH_SPGTS - 1];
+  if (ptprev)
+    {
+      for (i = 0; i < ENTRIES_PER_PGT; i++)
+        {
+          ptlast = (uintptr_t *)mmu_pte_to_paddr(ptprev[i]);
+          if (ptlast)
+            {
+              /* Page table allocated, free any allocated memory */
+
+              for (j = 0; j < ENTRIES_PER_PGT; j++)
+                {
+                  paddr = mmu_pte_to_paddr(ptlast[j]);
+                  if (paddr)
+                    {
+                      mm_pgfree(paddr, 1);
+                    }
+                }
+
+              /* Then free the page table itself */
+
+              mm_pgfree((uintptr_t)ptlast, 1);
+            }
+        }
+    }
+
+  /* Then destroy the static tables */
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = addrenv->spgtables[i];
+      if (paddr)
+        {
+          mm_pgfree(paddr, 1);
+        }
+    }
+
+  /* When all is set and done, flush the caches */
+
+  __ISB();
+  __DMB();
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vtext
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vtext - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vtext(FAR group_addrenv_t *addrenv, FAR void **vtext)
+{
+  DEBUGASSERT(addrenv && vtext);
+  *vtext = (FAR void *)addrenv->textvbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vdata
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   textsize - For some implementations, the text and data will be saved
+ *      in the same memory region (read/write/execute) and, in this case,
+ *      the virtual address of the data just lies at this offset into the
+ *      common region.
+ *   vdata - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vdata(FAR group_addrenv_t *addrenv, uintptr_t textsize,
+                     FAR void **vdata)
+{
+  DEBUGASSERT(addrenv && vdata);
+  *vdata = (FAR void *)addrenv->datavbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vheap
+ *
+ * Description:
+ *   Return the heap virtual address associated with the newly created
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vheap - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+int up_addrenv_vheap(FAR const group_addrenv_t *addrenv, FAR void **vheap)
+{
+  DEBUGASSERT(addrenv && vheap);
+  *vheap = (FAR void *)addrenv->heapvbase;

Review Comment:
   ```suggestion
   int up_addrenv_vheap(const group_addrenv_t *addrenv, void **vheap)
   {
     DEBUGASSERT(addrenv && vheap);
     *vheap = (void *)addrenv->heapvbase;
   ```



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)
+{
+  int       ret;
+  uintptr_t resvbase;
+  uintptr_t resvsize;
+  uintptr_t textbase;
+  uintptr_t database;
+  uintptr_t heapbase;
+
+  DEBUGASSERT(addrenv);
+  DEBUGASSERT(MM_ISALIGNED(ADDRENV_VBASE));
+
+  /* Make sure the address environment is wiped before doing anything */
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+
+  /* Create the static page tables */
+
+  if (create_spgtables(addrenv) < 0)
+    {
+      serr("ERROR: Failed to create static page tables\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  if (copy_kernel_mappings(addrenv) < 0)
+    {
+      serr("ERROR: Failed to copy kernel mappings to new environment");
+      ret = -EINVAL;
+      goto errout;
+    }
+
+  /* Calculate the base addresses for convenience */
+
+  resvbase = ADDRENV_VBASE;
+  resvsize = ARCH_DATA_RESERVE_SIZE;
+  textbase = resvbase + MM_PGALIGNUP(resvsize);
+  database = textbase + MM_PGALIGNUP(textsize);
+  heapbase = database + MM_PGALIGNUP(datasize);
+
+  /* Allocate 1 extra page for heap, temporary fix for #5811 */
+
+  heapsize = heapsize + MM_NPAGES(1);
+
+  /* Map the reserved area */
+
+  ret = create_region(addrenv, resvbase, resvsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create reserved region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Map each region in turn FIXME: Remove W-flag after .elf is loaded */
+
+  ret = create_region(addrenv, textbase, textsize, MMU_UTEXT_FLAGS | PTE_W);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .text region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, database, datasize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .bss/.data region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, heapbase, heapsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create heap region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Save the heap base and initial size allocated. These will be needed when
+   * the heap data structures are initialized.
+   */
+
+  addrenv->heapvbase = heapbase;
+  addrenv->heapsize = (size_t)ret << MM_PGSHIFT;
+
+  /* Save the text base */
+
+  addrenv->textvbase = textbase;
+
+  /* Save the data base */
+
+  addrenv->datavbase = database;
+
+  /* Provide the satp value for context switch */
+
+  addrenv->satp = mmu_satp_reg(addrenv->spgtables[0], 0);
+
+  /* When all is set and done, flush the data caches */
+
+  __ISB();
+  __DMB();
+
+  return OK;
+
+errout:
+  up_addrenv_destroy(addrenv);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_destroy
+ *
+ * Description:
+ *   This function is called when a final thread leaves the task group and
+ *   the task group is destroyed.  This function then destroys the defunct
+ *   address environment, releasing the underlying physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - The address environment to be destroyed.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_destroy(FAR group_addrenv_t *addrenv)
+{
+  /* Recursively destroy it all, need to table walk */
+
+  uintptr_t *ptprev;
+  uintptr_t *ptlast;
+  uintptr_t  paddr;
+  int        i;
+  int        j;
+
+  DEBUGASSERT(addrenv);
+
+  /* Make sure the caches are flushed before doing this */
+
+  __ISB();
+  __DMB();
+
+  /* First destroy the allocated memory and the final level page table */
+
+  ptprev = (uintptr_t *)addrenv->spgtables[ARCH_SPGTS - 1];
+  if (ptprev)
+    {
+      for (i = 0; i < ENTRIES_PER_PGT; i++)
+        {
+          ptlast = (uintptr_t *)mmu_pte_to_paddr(ptprev[i]);
+          if (ptlast)
+            {
+              /* Page table allocated, free any allocated memory */
+
+              for (j = 0; j < ENTRIES_PER_PGT; j++)
+                {
+                  paddr = mmu_pte_to_paddr(ptlast[j]);
+                  if (paddr)
+                    {
+                      mm_pgfree(paddr, 1);
+                    }
+                }
+
+              /* Then free the page table itself */
+
+              mm_pgfree((uintptr_t)ptlast, 1);
+            }
+        }
+    }
+
+  /* Then destroy the static tables */
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = addrenv->spgtables[i];
+      if (paddr)
+        {
+          mm_pgfree(paddr, 1);
+        }
+    }
+
+  /* When all is set and done, flush the caches */
+
+  __ISB();
+  __DMB();
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vtext
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vtext - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vtext(FAR group_addrenv_t *addrenv, FAR void **vtext)
+{
+  DEBUGASSERT(addrenv && vtext);
+  *vtext = (FAR void *)addrenv->textvbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vdata
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   textsize - For some implementations, the text and data will be saved
+ *      in the same memory region (read/write/execute) and, in this case,
+ *      the virtual address of the data just lies at this offset into the
+ *      common region.
+ *   vdata - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vdata(FAR group_addrenv_t *addrenv, uintptr_t textsize,
+                     FAR void **vdata)
+{
+  DEBUGASSERT(addrenv && vdata);
+  *vdata = (FAR void *)addrenv->datavbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vheap
+ *
+ * Description:
+ *   Return the heap virtual address associated with the newly created
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vheap - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+int up_addrenv_vheap(FAR const group_addrenv_t *addrenv, FAR void **vheap)
+{
+  DEBUGASSERT(addrenv && vheap);
+  *vheap = (FAR void *)addrenv->heapvbase;
+  return OK;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_heapsize
+ *
+ * Description:
+ *   Return the initial heap allocation size.  That is the amount of memory
+ *   allocated by up_addrenv_create() when the heap memory region was first
+ *   created.  This may or may not differ from the heapsize parameter that
+ *   was passed to up_addrenv_create()
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *
+ * Returned Value:
+ *   The initial heap size allocated is returned on success; a negated
+ *   errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+ssize_t up_addrenv_heapsize(FAR const group_addrenv_t *addrenv)
+{
+  DEBUGASSERT(addrenv);
+  return (ssize_t)addrenv->heapsize;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_select
+ *
+ * Description:
+ *   After an address environment has been established for a task (via
+ *   up_addrenv_create()), this function may be called to instantiate
+ *   that address environment in the virtual address space.  This might be
+ *   necessary, for example, to load the code for the task from a file or
+ *   to access address environment private data.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *   oldenv
+ *     The address environment that was in place before up_addrenv_select().
+ *     This may be used with up_addrenv_restore() to restore the original
+ *     address environment that was in place before up_addrenv_select() was
+ *     called.  Note that this may be a task agnostic, hardware
+ *     representation that is different from group_addrenv_t.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_select(FAR const group_addrenv_t *addrenv,
+                      FAR save_addrenv_t *oldenv)
+{
+  DEBUGASSERT(addrenv);
+  if (oldenv)
+    {
+      /* Save the old environment */
+
+      uintptr_t satp_reg = mmu_read_satp();
+      *oldenv = (save_addrenv_t)satp_reg;
+    }
+
+  mmu_write_satp(addrenv->satp);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_restore
+ *
+ * Description:
+ *   After an address environment has been temporarily instantiated by
+ *   up_addrenv_select, this function may be called to restore the
+ *   original address environment.
+ *
+ * Input Parameters:
+ *   oldenv - The hardware representation of the address environment
+ *     previously returned by up_addrenv_select.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_restore(FAR const save_addrenv_t *oldenv)
+{
+  DEBUGASSERT(oldenv);
+  mmu_write_satp((uintptr_t)*oldenv);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_coherent
+ *
+ * Description:
+ *   Flush D-Cache and invalidate I-Cache in preparation for a change in
+ *   address environments.  This should immediately precede a call to
+ *   up_addrenv_select();
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment to be made coherent.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_coherent(FAR const group_addrenv_t *addrenv)
+{
+  /* Flush the instruction and data caches */
+
+  __ISB();
+  __DMB();
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_clone
+ *
+ * Description:
+ *   Duplicate an address environment.  This does not copy the underlying
+ *   memory, only the representation that can be used to instantiate that
+ *   memory as an address environment.
+ *
+ * Input Parameters:
+ *   src - The address environment to be copied.
+ *   dest - The location to receive the copied address environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_clone(FAR const group_addrenv_t *src,
+                     FAR group_addrenv_t *dest)
+{
+  DEBUGASSERT(src && dest);
+  memcpy(dest, src, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_attach
+ *
+ * Description:
+ *   This function is called from the core scheduler logic when a thread
+ *   is created that needs to share the address environment of its task
+ *   group.
+ *
+ * Input Parameters:
+ *   group - The task group to which the new thread belongs.
+ *   tcb   - The tcb of the thread needing the address environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_attach(FAR struct task_group_s *group, FAR struct tcb_s *tcb)

Review Comment:
   ```suggestion
   int up_addrenv_attach(struct task_group_s *group, struct tcb_s *tcb)
   ```



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)
+{
+  int       ret;
+  uintptr_t resvbase;
+  uintptr_t resvsize;
+  uintptr_t textbase;
+  uintptr_t database;
+  uintptr_t heapbase;
+
+  DEBUGASSERT(addrenv);
+  DEBUGASSERT(MM_ISALIGNED(ADDRENV_VBASE));
+
+  /* Make sure the address environment is wiped before doing anything */
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+
+  /* Create the static page tables */
+
+  if (create_spgtables(addrenv) < 0)
+    {
+      serr("ERROR: Failed to create static page tables\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  if (copy_kernel_mappings(addrenv) < 0)
+    {
+      serr("ERROR: Failed to copy kernel mappings to new environment");
+      ret = -EINVAL;
+      goto errout;
+    }
+
+  /* Calculate the base addresses for convenience */
+
+  resvbase = ADDRENV_VBASE;
+  resvsize = ARCH_DATA_RESERVE_SIZE;
+  textbase = resvbase + MM_PGALIGNUP(resvsize);
+  database = textbase + MM_PGALIGNUP(textsize);
+  heapbase = database + MM_PGALIGNUP(datasize);
+
+  /* Allocate 1 extra page for heap, temporary fix for #5811 */
+
+  heapsize = heapsize + MM_NPAGES(1);
+
+  /* Map the reserved area */
+
+  ret = create_region(addrenv, resvbase, resvsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create reserved region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Map each region in turn FIXME: Remove W-flag after .elf is loaded */
+
+  ret = create_region(addrenv, textbase, textsize, MMU_UTEXT_FLAGS | PTE_W);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .text region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, database, datasize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .bss/.data region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, heapbase, heapsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create heap region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Save the heap base and initial size allocated. These will be needed when
+   * the heap data structures are initialized.
+   */
+
+  addrenv->heapvbase = heapbase;
+  addrenv->heapsize = (size_t)ret << MM_PGSHIFT;
+
+  /* Save the text base */
+
+  addrenv->textvbase = textbase;
+
+  /* Save the data base */
+
+  addrenv->datavbase = database;
+
+  /* Provide the satp value for context switch */
+
+  addrenv->satp = mmu_satp_reg(addrenv->spgtables[0], 0);
+
+  /* When all is set and done, flush the data caches */
+
+  __ISB();
+  __DMB();
+
+  return OK;
+
+errout:
+  up_addrenv_destroy(addrenv);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_destroy
+ *
+ * Description:
+ *   This function is called when a final thread leaves the task group and
+ *   the task group is destroyed.  This function then destroys the defunct
+ *   address environment, releasing the underlying physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - The address environment to be destroyed.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_destroy(FAR group_addrenv_t *addrenv)
+{
+  /* Recursively destroy it all, need to table walk */
+
+  uintptr_t *ptprev;
+  uintptr_t *ptlast;
+  uintptr_t  paddr;
+  int        i;
+  int        j;
+
+  DEBUGASSERT(addrenv);
+
+  /* Make sure the caches are flushed before doing this */
+
+  __ISB();
+  __DMB();
+
+  /* First destroy the allocated memory and the final level page table */
+
+  ptprev = (uintptr_t *)addrenv->spgtables[ARCH_SPGTS - 1];
+  if (ptprev)
+    {
+      for (i = 0; i < ENTRIES_PER_PGT; i++)
+        {
+          ptlast = (uintptr_t *)mmu_pte_to_paddr(ptprev[i]);
+          if (ptlast)
+            {
+              /* Page table allocated, free any allocated memory */
+
+              for (j = 0; j < ENTRIES_PER_PGT; j++)
+                {
+                  paddr = mmu_pte_to_paddr(ptlast[j]);
+                  if (paddr)
+                    {
+                      mm_pgfree(paddr, 1);
+                    }
+                }
+
+              /* Then free the page table itself */
+
+              mm_pgfree((uintptr_t)ptlast, 1);
+            }
+        }
+    }
+
+  /* Then destroy the static tables */
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = addrenv->spgtables[i];
+      if (paddr)
+        {
+          mm_pgfree(paddr, 1);
+        }
+    }
+
+  /* When all is set and done, flush the caches */
+
+  __ISB();
+  __DMB();
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vtext
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vtext - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vtext(FAR group_addrenv_t *addrenv, FAR void **vtext)
+{
+  DEBUGASSERT(addrenv && vtext);
+  *vtext = (FAR void *)addrenv->textvbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vdata
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   textsize - For some implementations, the text and data will be saved
+ *      in the same memory region (read/write/execute) and, in this case,
+ *      the virtual address of the data just lies at this offset into the
+ *      common region.
+ *   vdata - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vdata(FAR group_addrenv_t *addrenv, uintptr_t textsize,
+                     FAR void **vdata)
+{
+  DEBUGASSERT(addrenv && vdata);
+  *vdata = (FAR void *)addrenv->datavbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vheap
+ *
+ * Description:
+ *   Return the heap virtual address associated with the newly created
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vheap - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+int up_addrenv_vheap(FAR const group_addrenv_t *addrenv, FAR void **vheap)
+{
+  DEBUGASSERT(addrenv && vheap);
+  *vheap = (FAR void *)addrenv->heapvbase;
+  return OK;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_heapsize
+ *
+ * Description:
+ *   Return the initial heap allocation size.  That is the amount of memory
+ *   allocated by up_addrenv_create() when the heap memory region was first
+ *   created.  This may or may not differ from the heapsize parameter that
+ *   was passed to up_addrenv_create()
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *
+ * Returned Value:
+ *   The initial heap size allocated is returned on success; a negated
+ *   errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+ssize_t up_addrenv_heapsize(FAR const group_addrenv_t *addrenv)
+{
+  DEBUGASSERT(addrenv);
+  return (ssize_t)addrenv->heapsize;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_select
+ *
+ * Description:
+ *   After an address environment has been established for a task (via
+ *   up_addrenv_create()), this function may be called to instantiate
+ *   that address environment in the virtual address space.  This might be
+ *   necessary, for example, to load the code for the task from a file or
+ *   to access address environment private data.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *   oldenv
+ *     The address environment that was in place before up_addrenv_select().
+ *     This may be used with up_addrenv_restore() to restore the original
+ *     address environment that was in place before up_addrenv_select() was
+ *     called.  Note that this may be a task agnostic, hardware
+ *     representation that is different from group_addrenv_t.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_select(FAR const group_addrenv_t *addrenv,
+                      FAR save_addrenv_t *oldenv)
+{
+  DEBUGASSERT(addrenv);
+  if (oldenv)
+    {
+      /* Save the old environment */
+
+      uintptr_t satp_reg = mmu_read_satp();
+      *oldenv = (save_addrenv_t)satp_reg;
+    }
+
+  mmu_write_satp(addrenv->satp);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_restore
+ *
+ * Description:
+ *   After an address environment has been temporarily instantiated by
+ *   up_addrenv_select, this function may be called to restore the
+ *   original address environment.
+ *
+ * Input Parameters:
+ *   oldenv - The hardware representation of the address environment
+ *     previously returned by up_addrenv_select.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_restore(FAR const save_addrenv_t *oldenv)
+{
+  DEBUGASSERT(oldenv);
+  mmu_write_satp((uintptr_t)*oldenv);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_coherent
+ *
+ * Description:
+ *   Flush D-Cache and invalidate I-Cache in preparation for a change in
+ *   address environments.  This should immediately precede a call to
+ *   up_addrenv_select();
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment to be made coherent.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_coherent(FAR const group_addrenv_t *addrenv)
+{
+  /* Flush the instruction and data caches */
+
+  __ISB();
+  __DMB();
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_clone
+ *
+ * Description:
+ *   Duplicate an address environment.  This does not copy the underlying
+ *   memory, only the representation that can be used to instantiate that
+ *   memory as an address environment.
+ *
+ * Input Parameters:
+ *   src - The address environment to be copied.
+ *   dest - The location to receive the copied address environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_clone(FAR const group_addrenv_t *src,
+                     FAR group_addrenv_t *dest)
+{
+  DEBUGASSERT(src && dest);
+  memcpy(dest, src, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_attach
+ *
+ * Description:
+ *   This function is called from the core scheduler logic when a thread
+ *   is created that needs to share the address environment of its task
+ *   group.
+ *
+ * Input Parameters:
+ *   group - The task group to which the new thread belongs.
+ *   tcb   - The tcb of the thread needing the address environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_attach(FAR struct task_group_s *group, FAR struct tcb_s *tcb)
+{
+  /* There is nothing that needs to be done */
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_detach
+ *
+ * Description:
+ *   This function is called when a task or thread exits in order to release
+ *   its reference to an address environment.  The address environment,
+ *   however, should persist until up_addrenv_destroy() is called when the
+ *   task group is itself destroyed.  Any resources unique to this thread
+ *   may be destroyed now.
+ *
+ *   NOTE: In some platforms, nothing will need to be done in this case.
+ *   Simply being a member of the group that has the address environment
+ *   may be sufficient.
+ *
+ * Input Parameters:
+ *   group - The group to which the thread belonged.
+ *   tcb - The TCB of the task or thread whose the address environment will
+ *     be released.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_detach(FAR struct task_group_s *group, FAR struct tcb_s *tcb)

Review Comment:
   ```suggestion
   int up_addrenv_detach(struct task_group_s *group, struct tcb_s *tcb)
   ```



##########
arch/risc-v/src/mpfs/mpfs_mm_init.c:
##########
@@ -0,0 +1,188 @@
+/****************************************************************************
+ * arch/risc-v/src/mpfs/mpfs_mm_init.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+#include <nuttx/arch.h>
+
+#include <stdint.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <arch/board/board_memorymap.h>
+
+#include "mpfs_memorymap.h"
+
+#include "riscv_internal.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* PMP settings */
+
+#define PMP_IO_FLAGS    (PMPCFG_A_NAPOT | PMPCFG_R | PMPCFG_W)
+#define PMP_RAM_FLAGS   (PMPCFG_A_NAPOT | PMPCFG_X | PMPCFG_R | PMPCFG_W)
+
+/* Open up (basically) the whole memory */
+
+#define PMP_IO_BASE     (MPFS_CLINT_BASE)
+#define PMP_IO_SIZE     (MPFS_DDR_BASE - MPFS_CLINT_BASE)
+#define PMP_RAM_BASE    (MPFS_DDR_BASE)
+#define PMP_RAM_SIZE    (MPFS_DDR_SIZE)
+
+/* Map the whole I/O memory with vaddr = paddr mappings */
+
+#define MMU_IO_BASE     (0x00000000)
+#define MMU_IO_SIZE     (0x80000000)
+
+/* Physical and virtual addresses to page tables (vaddr = paddr mapping) */
+
+#define PGT_L1_PBASE    (uintptr_t)&m_l1_pgtable
+#define PGT_L2_PBASE    (uintptr_t)&m_l2_pgtable
+#define PGT_L3_PBASE    (uintptr_t)&m_l3_pgtable
+#define PGT_L1_VBASE    PGT_L1_PBASE
+#define PGT_L2_VBASE    PGT_L2_PBASE
+#define PGT_L3_VBASE    PGT_L3_PBASE
+
+#define PGT_L1_SIZE     (512)  /* Enough to map 512 GiB */
+#define PGT_L2_SIZE     (512)  /* Enough to map 1 GiB */
+#define PGT_L3_SIZE     (1024) /* Enough to map 4 MiB */
+
+/****************************************************************************
+ * Private Data
+ ****************************************************************************/
+
+/* Kernel mappings simply here, mapping is vaddr=paddr */
+
+static uint64_t         m_l1_pgtable[PGT_L1_SIZE] locate_data(".pgtables");
+static uint64_t         m_l2_pgtable[PGT_L2_SIZE] locate_data(".pgtables");
+static uint64_t         m_l3_pgtable[PGT_L3_SIZE] locate_data(".pgtables");

Review Comment:
   As an alternative this potentially can come up as linker defined symbols from liker script. And placement in proper sections will be done there as well



##########
arch/risc-v/src/common/riscv_addrenv.c:
##########
@@ -0,0 +1,828 @@
+/****************************************************************************
+ * arch/risc-v/src/common/riscv_addrenv.c
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Address Environment Interfaces
+ *
+ * Low-level interfaces used in binfmt/ to instantiate tasks with address
+ * environments.  These interfaces all operate on type group_addrenv_t which
+ * is an abstract representation of a task group's address environment and
+ * must be defined in arch/arch.h if CONFIG_ARCH_ADDRENV is defined.
+ *
+ *   up_addrenv_create   - Create an address environment
+ *   up_addrenv_destroy  - Destroy an address environment.
+ *   up_addrenv_vtext    - Returns the virtual base address of the .text
+ *                         address environment
+ *   up_addrenv_vdata    - Returns the virtual base address of the .bss/.data
+ *                         address environment
+ *   up_addrenv_heapsize - Returns the size of the initial heap allocation.
+ *   up_addrenv_select   - Instantiate an address environment
+ *   up_addrenv_restore  - Restore an address environment
+ *   up_addrenv_clone    - Copy an address environment from one location to
+ *                        another.
+ *
+ * Higher-level interfaces used by the tasking logic.  These interfaces are
+ * used by the functions in sched/ and all operate on the thread which whose
+ * group been assigned an address environment by up_addrenv_clone().
+ *
+ *   up_addrenv_attach   - Clone the address environment assigned to one TCB
+ *                         to another.  This operation is done when a pthread
+ *                         is created that share's the same address
+ *                         environment.
+ *   up_addrenv_detach   - Release the threads reference to an address
+ *                         environment when a task/thread exits.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <errno.h>
+#include <assert.h>
+#include <debug.h>
+
+#include <nuttx/addrenv.h>
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/pgalloc.h>
+
+#include <arch/barriers.h>
+
+#include "pgalloc.h"
+#include "riscv_mmu.h"
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Only CONFIG_BUILD_KERNEL is supported (i.e. tested) */
+
+#ifndef CONFIG_BUILD_KERNEL
+#  error "This module is intended to be used with CONFIG_BUILD_KERNEL"
+#endif
+
+/* Entries per PGT */
+
+#define ENTRIES_PER_PGT     (RV_MMU_ENTRIES_PER_PGT)
+
+/* Base address for address environment */
+
+#define ADDRENV_VBASE       (CONFIG_ARCH_DATA_VBASE)
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+extern uintptr_t            g_kernel_mappings;
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: wipe_page
+ *
+ * Description:
+ *   Wipe a page of physical memory, first mapping it into virtual memory.
+ *
+ * Input Parameters:
+ *   paddr - Physical address of page
+ *
+ ****************************************************************************/
+
+static inline void wipe_page(uintptr_t paddr)
+{
+  uintptr_t vaddr = riscv_pgpool_to_vaddr(paddr);
+  memset((void *)vaddr, 0, MM_PGSIZE);
+}
+
+/****************************************************************************
+ * Name: map_spgtables
+ *
+ * Description:
+ *   Map vaddr to the static page tables.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ ****************************************************************************/
+
+static void map_spgtables(group_addrenv_t *addrenv, uintptr_t vaddr)
+{
+  int       i;
+  uintptr_t prev;
+
+  /* Start from L1, and connect until max level - 1 */
+
+  prev = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Check if the mapping already exists */
+
+  if (mmu_ln_getentry(1, prev, vaddr) != 0)
+    {
+      return;
+    }
+
+  /* No mapping yet, create it */
+
+  for (i = 0; i < (ARCH_SPGTS - 1); i++)
+    {
+      uintptr_t next = riscv_pgpool_to_vaddr(addrenv->spgtables[i + 1]);
+      mmu_ln_setentry(i + 1, prev, next, vaddr, MMU_UPGT_FLAGS);
+      prev = next;
+    }
+}
+
+/****************************************************************************
+ * Name: create_spgtables
+ *
+ * Description:
+ *   Create the static page tables. Allocate memory for them and connect them
+ *   together.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_spgtables(group_addrenv_t *addrenv)
+{
+  int       i;
+  uintptr_t paddr;
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = mm_pgalloc(1);
+      if (!paddr)
+        {
+          return -ENOMEM;
+        }
+
+      /* Wipe the memory and assign it */
+
+      wipe_page(paddr);
+      addrenv->spgtables[i] = paddr;
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return i;
+}
+
+/****************************************************************************
+ * Name: copy_kernel_mappings
+ *
+ * Description:
+ *   Copy kernel mappings to address environment. Expects that the user page
+ *   table does not contain any mappings yet (as they will be wiped).
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment. The page tables must exist
+ *      at this point.
+ *
+ * Returned value:
+ *   OK on success, ERROR on failure
+ *
+ ****************************************************************************/
+
+static int copy_kernel_mappings(group_addrenv_t *addrenv)
+{
+  uintptr_t user_mappings = riscv_pgpool_to_vaddr(addrenv->spgtables[0]);
+
+  /* Copy the L1 references */
+
+  if (user_mappings == 0)
+    {
+      return ERROR;
+    }
+
+  memcpy((void *)user_mappings, (void *)g_kernel_mappings, ENTRIES_PER_PGT);
+
+  return OK;
+}
+
+/****************************************************************************
+ * Name: create_region
+ *
+ * Description:
+ *   Map a single region of memory to MMU. Assumes that the static page
+ *   tables exist. Allocates the final level page tables and commits the
+ *   region memory to physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment
+ *   vaddr - Base virtual address for the mapping
+ *   size - Size of the region in bytes
+ *   mmuflags - MMU flags to use
+ *
+ * Returned value:
+ *   Amount of pages created on success; a negated errno value on failure
+ *
+ ****************************************************************************/
+
+static int create_region(group_addrenv_t *addrenv, uintptr_t vaddr,
+                         size_t size, uint32_t mmuflags)
+{
+  uintptr_t ptlast;
+  uintptr_t ptprev;
+  uintptr_t paddr;
+  uint32_t  ptlevel;
+  int       npages;
+  int       nmapped;
+  int       i;
+  int       j;
+
+  nmapped   = 0;
+  npages    = MM_NPAGES(size);
+  ptprev    = riscv_pgpool_to_vaddr(addrenv->spgtables[ARCH_SPGTS - 1]);
+  ptlevel   = ARCH_SPGTS;
+
+  /* Create mappings for the lower level tables */
+
+  map_spgtables(addrenv, vaddr);
+
+  /* Begin allocating memory for the page tables */
+
+  for (i = 0; i < npages; i += ENTRIES_PER_PGT)
+    {
+      /* Get the current final level entry corresponding to this vaddr */
+
+      paddr = mmu_pte_to_paddr(mmu_ln_getentry(ptlevel, ptprev, vaddr));
+
+      if (paddr == 0)
+        {
+          /* Nothing yet, allocate one page for final level page table */
+
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Map the page table to the prior level */
+
+          mmu_ln_setentry(ptlevel, ptprev, paddr, vaddr, MMU_UPGT_FLAGS);
+
+          /* This is then used to map the final level */
+
+          wipe_page(paddr);
+        }
+
+      ptlast = riscv_pgpool_to_vaddr(paddr);
+
+      /* Then allocate memory for the region data */
+
+      for (j = 0; j < ENTRIES_PER_PGT && nmapped < size; j++)
+        {
+          paddr = mm_pgalloc(1);
+          if (!paddr)
+            {
+              return -ENOMEM;
+            }
+
+          /* Wipe the physical page memory */
+
+          wipe_page(paddr);
+
+          /* Then map the virtual address to the physical address */
+
+          mmu_ln_setentry(ptlevel + 1, ptlast, paddr, vaddr, mmuflags);
+          nmapped   += MM_PGSIZE;
+          vaddr     += MM_PGSIZE;
+        }
+    }
+
+  /* Flush the data cache, so the changes are committed to memory */
+
+  __DMB();
+
+  return npages;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: up_addrenv_create
+ *
+ * Description:
+ *   This function is called when a new task is created in order to
+ *   instantiate an address environment for the new task group.
+ *   up_addrenv_create() is essentially the allocator of the physical
+ *   memory for the new task.
+ *
+ * Input Parameters:
+ *   textsize - The size (in bytes) of the .text address environment needed
+ *     by the task.  This region may be read/execute only.
+ *   datasize - The size (in bytes) of the .data/.bss address environment
+ *     needed by the task.  This region may be read/write only.  NOTE: The
+ *     actual size of the data region that is allocated will include a
+ *     OS private reserved region at the beginning.  The size of the
+ *     private, reserved region is give by ARCH_DATA_RESERVE_SIZE.
+ *   heapsize - The initial size (in bytes) of the heap address environment
+ *     needed by the task.  This region may be read/write only.
+ *   addrenv - The location to return the representation of the task address
+ *     environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_create(size_t textsize, size_t datasize, size_t heapsize,
+                      FAR group_addrenv_t *addrenv)
+{
+  int       ret;
+  uintptr_t resvbase;
+  uintptr_t resvsize;
+  uintptr_t textbase;
+  uintptr_t database;
+  uintptr_t heapbase;
+
+  DEBUGASSERT(addrenv);
+  DEBUGASSERT(MM_ISALIGNED(ADDRENV_VBASE));
+
+  /* Make sure the address environment is wiped before doing anything */
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+
+  /* Create the static page tables */
+
+  if (create_spgtables(addrenv) < 0)
+    {
+      serr("ERROR: Failed to create static page tables\n");
+      ret = -ENOMEM;
+      goto errout;
+    }
+
+  if (copy_kernel_mappings(addrenv) < 0)
+    {
+      serr("ERROR: Failed to copy kernel mappings to new environment");
+      ret = -EINVAL;
+      goto errout;
+    }
+
+  /* Calculate the base addresses for convenience */
+
+  resvbase = ADDRENV_VBASE;
+  resvsize = ARCH_DATA_RESERVE_SIZE;
+  textbase = resvbase + MM_PGALIGNUP(resvsize);
+  database = textbase + MM_PGALIGNUP(textsize);
+  heapbase = database + MM_PGALIGNUP(datasize);
+
+  /* Allocate 1 extra page for heap, temporary fix for #5811 */
+
+  heapsize = heapsize + MM_NPAGES(1);
+
+  /* Map the reserved area */
+
+  ret = create_region(addrenv, resvbase, resvsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create reserved region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Map each region in turn FIXME: Remove W-flag after .elf is loaded */
+
+  ret = create_region(addrenv, textbase, textsize, MMU_UTEXT_FLAGS | PTE_W);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .text region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, database, datasize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create .bss/.data region: %d\n", ret);
+      goto errout;
+    }
+
+  ret = create_region(addrenv, heapbase, heapsize, MMU_UDATA_FLAGS);
+
+  if (ret < 0)
+    {
+      berr("ERROR: Failed to create heap region: %d\n", ret);
+      goto errout;
+    }
+
+  /* Save the heap base and initial size allocated. These will be needed when
+   * the heap data structures are initialized.
+   */
+
+  addrenv->heapvbase = heapbase;
+  addrenv->heapsize = (size_t)ret << MM_PGSHIFT;
+
+  /* Save the text base */
+
+  addrenv->textvbase = textbase;
+
+  /* Save the data base */
+
+  addrenv->datavbase = database;
+
+  /* Provide the satp value for context switch */
+
+  addrenv->satp = mmu_satp_reg(addrenv->spgtables[0], 0);
+
+  /* When all is set and done, flush the data caches */
+
+  __ISB();
+  __DMB();
+
+  return OK;
+
+errout:
+  up_addrenv_destroy(addrenv);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_destroy
+ *
+ * Description:
+ *   This function is called when a final thread leaves the task group and
+ *   the task group is destroyed.  This function then destroys the defunct
+ *   address environment, releasing the underlying physical memory.
+ *
+ * Input Parameters:
+ *   addrenv - The address environment to be destroyed.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_destroy(FAR group_addrenv_t *addrenv)
+{
+  /* Recursively destroy it all, need to table walk */
+
+  uintptr_t *ptprev;
+  uintptr_t *ptlast;
+  uintptr_t  paddr;
+  int        i;
+  int        j;
+
+  DEBUGASSERT(addrenv);
+
+  /* Make sure the caches are flushed before doing this */
+
+  __ISB();
+  __DMB();
+
+  /* First destroy the allocated memory and the final level page table */
+
+  ptprev = (uintptr_t *)addrenv->spgtables[ARCH_SPGTS - 1];
+  if (ptprev)
+    {
+      for (i = 0; i < ENTRIES_PER_PGT; i++)
+        {
+          ptlast = (uintptr_t *)mmu_pte_to_paddr(ptprev[i]);
+          if (ptlast)
+            {
+              /* Page table allocated, free any allocated memory */
+
+              for (j = 0; j < ENTRIES_PER_PGT; j++)
+                {
+                  paddr = mmu_pte_to_paddr(ptlast[j]);
+                  if (paddr)
+                    {
+                      mm_pgfree(paddr, 1);
+                    }
+                }
+
+              /* Then free the page table itself */
+
+              mm_pgfree((uintptr_t)ptlast, 1);
+            }
+        }
+    }
+
+  /* Then destroy the static tables */
+
+  for (i = 0; i < ARCH_SPGTS; i++)
+    {
+      paddr = addrenv->spgtables[i];
+      if (paddr)
+        {
+          mm_pgfree(paddr, 1);
+        }
+    }
+
+  /* When all is set and done, flush the caches */
+
+  __ISB();
+  __DMB();
+
+  memset(addrenv, 0, sizeof(group_addrenv_t));
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vtext
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vtext - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vtext(FAR group_addrenv_t *addrenv, FAR void **vtext)
+{
+  DEBUGASSERT(addrenv && vtext);
+  *vtext = (FAR void *)addrenv->textvbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vdata
+ *
+ * Description:
+ *   Return the virtual address associated with the newly create .text
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   textsize - For some implementations, the text and data will be saved
+ *      in the same memory region (read/write/execute) and, in this case,
+ *      the virtual address of the data just lies at this offset into the
+ *      common region.
+ *   vdata - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_vdata(FAR group_addrenv_t *addrenv, uintptr_t textsize,
+                     FAR void **vdata)
+{
+  DEBUGASSERT(addrenv && vdata);
+  *vdata = (FAR void *)addrenv->datavbase;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_vheap
+ *
+ * Description:
+ *   Return the heap virtual address associated with the newly created
+ *   address environment.  This function is used by the binary loaders in
+ *   order get an address that can be used to initialize the new task.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *      returned by up_addrenv_create.
+ *   vheap - The location to return the virtual address.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+int up_addrenv_vheap(FAR const group_addrenv_t *addrenv, FAR void **vheap)
+{
+  DEBUGASSERT(addrenv && vheap);
+  *vheap = (FAR void *)addrenv->heapvbase;
+  return OK;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_heapsize
+ *
+ * Description:
+ *   Return the initial heap allocation size.  That is the amount of memory
+ *   allocated by up_addrenv_create() when the heap memory region was first
+ *   created.  This may or may not differ from the heapsize parameter that
+ *   was passed to up_addrenv_create()
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *
+ * Returned Value:
+ *   The initial heap size allocated is returned on success; a negated
+ *   errno value on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_BUILD_KERNEL
+ssize_t up_addrenv_heapsize(FAR const group_addrenv_t *addrenv)
+{
+  DEBUGASSERT(addrenv);
+  return (ssize_t)addrenv->heapsize;
+}
+#endif
+
+/****************************************************************************
+ * Name: up_addrenv_select
+ *
+ * Description:
+ *   After an address environment has been established for a task (via
+ *   up_addrenv_create()), this function may be called to instantiate
+ *   that address environment in the virtual address space.  This might be
+ *   necessary, for example, to load the code for the task from a file or
+ *   to access address environment private data.
+ *
+ * Input Parameters:
+ *   addrenv - The representation of the task address environment previously
+ *     returned by up_addrenv_create.
+ *   oldenv
+ *     The address environment that was in place before up_addrenv_select().
+ *     This may be used with up_addrenv_restore() to restore the original
+ *     address environment that was in place before up_addrenv_select() was
+ *     called.  Note that this may be a task agnostic, hardware
+ *     representation that is different from group_addrenv_t.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_select(FAR const group_addrenv_t *addrenv,
+                      FAR save_addrenv_t *oldenv)
+{
+  DEBUGASSERT(addrenv);
+  if (oldenv)
+    {
+      /* Save the old environment */
+
+      uintptr_t satp_reg = mmu_read_satp();
+      *oldenv = (save_addrenv_t)satp_reg;
+    }
+
+  mmu_write_satp(addrenv->satp);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_restore
+ *
+ * Description:
+ *   After an address environment has been temporarily instantiated by
+ *   up_addrenv_select, this function may be called to restore the
+ *   original address environment.
+ *
+ * Input Parameters:
+ *   oldenv - The hardware representation of the address environment
+ *     previously returned by up_addrenv_select.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_restore(FAR const save_addrenv_t *oldenv)
+{
+  DEBUGASSERT(oldenv);
+  mmu_write_satp((uintptr_t)*oldenv);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_coherent
+ *
+ * Description:
+ *   Flush D-Cache and invalidate I-Cache in preparation for a change in
+ *   address environments.  This should immediately precede a call to
+ *   up_addrenv_select();
+ *
+ * Input Parameters:
+ *   addrenv - Describes the address environment to be made coherent.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_coherent(FAR const group_addrenv_t *addrenv)
+{
+  /* Flush the instruction and data caches */
+
+  __ISB();
+  __DMB();
+  return OK;
+}
+
+/****************************************************************************
+ * Name: up_addrenv_clone
+ *
+ * Description:
+ *   Duplicate an address environment.  This does not copy the underlying
+ *   memory, only the representation that can be used to instantiate that
+ *   memory as an address environment.
+ *
+ * Input Parameters:
+ *   src - The address environment to be copied.
+ *   dest - The location to receive the copied address environment.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int up_addrenv_clone(FAR const group_addrenv_t *src,
+                     FAR group_addrenv_t *dest)

Review Comment:
   ```suggestion
   int up_addrenv_clone(const group_addrenv_t *src,
                        group_addrenv_t *dest)
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@nuttx.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org