chore: migrate project into clean repository

This commit is contained in:
yuuux
2026-08-13 16:50:52 +08:00
commit d1d25a09e7
27405 changed files with 9422808 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
# 版本管理已移至 cmake/version.cmake
# 由主 CMakeLists.txt 在早期阶段包含
add_subdirectory(${CHIP})
if (DEFINED CONFIG_BOOT)
include(${CMAKE_CURRENT_SOURCE_DIR}/boot.cmake)
endif()

38
arcs-sdk/startup/Kconfig Normal file
View File

@@ -0,0 +1,38 @@
menu "ARCS System Startup Configuration"
rsource "arcs/Kconfig"
config ARCS_STARTUP_CONFIG
bool "ARCS startup config"
default y
imply MODULE_FREERTOS
imply MODULE_HEAP
imply LOG
imply ARCS_HAL_WARNING_DISABLE
imply BOOT_HART
if ARCS_STARTUP_CONFIG
config ARCS_STARTUP_CUSTOM_LINKER_FILE
bool "ARCS startup custom linker file"
default n
config PSRAM_INIT
bool "PSRAM init"
default y if ARCS_AP_CORE
config CLOCK_INIT
bool "CLOCK init"
default y if ARCS_AP_CORE
config BOOT
bool "BOOT embedded"
default y if ARCS_CP_CORE
endif
endmenu
if BOOT
orsource "boot/Kconfig.boot"
endif

View File

@@ -0,0 +1,48 @@
set(TOP_PATH ${CMAKE_HOME_DIRECTORY})
set(LIB_PATH ${CMAKE_CURRENT_SOURCE_DIR})
file(GLOB_RECURSE LIB_SRCS "system.c" "*.[cS]")
enable_language(ASM)
listenai_library_named(startup)
if (DEFINED CONFIG_ARCS_HAL_DEBUG)
list(FILTER LIB_SRCS EXCLUDE REGEX "sysport.c")
list(FILTER LIB_SRCS EXCLUDE REGEX "dmacpy.c")
endif()
listenai_library_sources(
${LIB_SRCS}
)
listenai_include_directories(
${LIB_PATH}
)
if (DEFINED CONFIG_ARCS_HAL_WCND)
listenai_link_libraries(arcs_hal_wcnd)
endif()
if (NOT DEFINED CONFIG_MEM_CONFIG_USE_CUSTOM_FILE)
listenai_include_directories(memmap)
endif()
if (NOT DEFINED CONFIG_ARCS_STARTUP_CUSTOM_LINKER_FILE)
listenai_set_linker_script(${CMAKE_CURRENT_SOURCE_DIR}/system.ld)
endif()
if (DEFINED CONFIG_BACK_TRACE)
add_compile_definitions(CFG_BACK_TRACE)
# Define the project executable name for backtrace
if(DEFINED PROJECT_NAME)
add_compile_definitions(PROJECT_EXECUTABLE_NAME="${PROJECT_NAME}")
else()
add_compile_definitions(PROJECT_EXECUTABLE_NAME="arcs")
endif()
endif()
if (DEFINED CONFIG_CPP_EXCEPTIONS)
add_compile_options(
-fexceptions
)
endif()

View File

@@ -0,0 +1,73 @@
config MAIN_TASK_STACK_SIZE
int "main task stack size"
default 2048
config MAIN_TASK_PRIORITY
int "main task priority"
default 1
config DCACHE_ENABLE
bool "Enable DCACHE"
default y
config ICACHE_ENABLE
bool "Enable ICACHE"
default y
config LINK_CPP_RUNTIME_SECTIONS
bool "link cpp runtime sections"
default y
help
Link the C++ runtime sections
config CPP_EXCEPTIONS
bool "Enable C++ exceptions"
default y
config EXCEPTION_REBOOT_IMMEDIATELY
bool "reboot immediately in exception handler"
default n
config BOOT_WITH_WATCHDOG
bool "boot with watchdog"
default n
help
Enable the watchdog in boot
config WATCHDOG_ENABLE
bool "watchdog enable"
default y if BOOT_WITH_WATCHDOG
help
Enable the watchdog
config SYS_INIT
bool "Enable system initialization framework"
default y
help
Enable the SYS_INIT framework for multi-level system initialization.
This framework provides 5 initialization levels that match ARCS boot flow:
- PRE_SYSTEM_INIT: BEFORE scatload (in platform_pre_startup)
⚠️ WARNING: .data NOT copied, .bss NOT zeroed!
DO NOT use global variables!
- PRE_DEVICES_INIT: Before lisa_device_init()
- PRE_KERNEL: Before vTaskStartScheduler()
- POST_KERNEL: After vTaskStartScheduler()
- PRE_APPLICATION: Before main()
Use SYS_INIT macro to register initialization functions at different levels.
If unsure, say Y.
config SYS_INIT_DEBUG
bool "Enable system initialization debug output"
depends on SYS_INIT
default n
help
Enable detailed debug logging for system initialization.
rsource "Kconfig.mem"
rsource "Kconfig.syslog"
rsource "Kconfig.debug"

View File

@@ -0,0 +1,9 @@
menu "back trace"
config BACK_TRACE
bool "backtrace support"
default n
help
Enable the exception back trace
endmenu

View File

@@ -0,0 +1,150 @@
menu "memory config"
config MEM_CONFIG
bool "memory config"
default y
config MEM_CONFIG_USE_CUSTOM_FILE
bool "use custom memory config file"
depends on !MEM_CONFIG
default n
if MEM_CONFIG
config MEM_INTERRUPT_STACK_SIZE
hex "interrupt stack size"
default 0x1000
menu "sram memory config"
config MEM_SRAM_BASE
hex "sram base address"
default 0x20000000 if !MEM_WFRAM_ISOLATED
default 0x20010000 if MEM_WFRAM_ISOLATED
config MEM_SRAM_SIZE
hex "sram size"
default 0x00040000
endmenu
menu "psram memory config"
config MEM_CMN_SRAM_BASE
hex "cmn sram base address"
default 0x20040000
config MEM_CMN_SRAM_SIZE
hex "cmn sram size"
default 0x00010000
config MEM_PSRAM_BASE
hex "psram base address"
default 0x28000000
config MEM_PSRAM_SIZE
hex "psram size"
default 0x00800000
endmenu
menu "flash memory config"
config MEM_FLASH_BASE
hex "flash base address"
default 0x30000000
config MEM_FLASH_SIZE
hex "flash size"
default 0x00800000
endmenu
menu "local memory config"
config MEM_ILM_BASE
hex "ilm base address"
default 0x00080000 if ARCS_AP_CORE
default 0x00280000 if ARCS_CP_CORE
config MEM_ILM_SIZE
hex "ilm size"
default 0x00004000
config MEM_DLM_BASE
hex "dlm base address"
default 0x00100000 if ARCS_AP_CORE
default 0x00300000 if ARCS_CP_CORE
config MEM_DLM_SIZE
hex "dlm size"
default 0x00002000
endmenu
menu "luna ram memory config"
config MEM_LUNA_BASE
hex "luna ram base address"
default 0x200B0000
config MEM_LUNA_SIZE
hex "luna ram size"
default 0x00006000
endmenu
menu "bluetooth ram memory config"
config MEM_BTRAM_BASE
hex "bluetooth ram base address"
default 0x200C0000
config MEM_BTRAM_SIZE
hex "bluetooth ram size"
default 0x00008000
endmenu
menu "ipc memory config"
config MEM_IPC_ISOLATED
bool "ipc ram isolated"
default y
config MEM_IPC_BASE
hex "ipc base address"
default 0x20050000
depends on MEM_IPC_ISOLATED
config MEM_IPC_SIZE
hex "ipc size"
default 0x00002000
depends on MEM_IPC_ISOLATED
endmenu
menu "wifi memory config"
config MEM_WFRAM_ISOLATED
bool "wifi ram isolated"
default y
help
wifi ram will be allocated from sram by linker if not set
config MEM_WFRAM_BASE
hex "wifi ram base address"
default 0x20000080
depends on MEM_WFRAM_ISOLATED
help
WiFi RAM base address (note: the first 128 bytes are reserved for WiFi hardware)
config MEM_WFRAM_SIZE
hex "wifi ram size "
default 0x00010000
depends on MEM_WFRAM_ISOLATED
config MEM_WIFI_CALIBRATION_SIZE
hex "wifi calibration data size reserved"
default 0x4000 if ARCS_AP_CORE
default 0
config MEM_WIFI_TRACE_SIZE
hex "wifi trace data size reserved"
default 0x2000 if ARCS_AP_CORE
default 0
endmenu
endif
endmenu

View File

@@ -0,0 +1,62 @@
menu "syslog backend uart"
config SYSLOG_UART_BACKEND
bool "syslog backend uart"
default y
help
Enable syslog backend for UART output.
if SYSLOG_UART_BACKEND
config SYSLOG_UART_PORT
int "uart port"
default 0
range 0 2
config SYSLOG_UART_BAUDRATE
int "uart baudrate"
default 921600
choice SYSLOG_UART_DEVICE_NAME
prompt "uart device name"
default SYSLOG_UART_DEVICE_UART0
help
Specify the UART device name for syslog output.
config SYSLOG_UART_DEVICE_UART0
bool "uart0"
select LISA_DEVICE
select LISA_UART_DEVICE
select LISA_UART0
config SYSLOG_UART_DEVICE_UART1
bool "uart1"
select LISA_DEVICE
select LISA_UART_DEVICE
select LISA_UART1
config SYSLOG_UART_DEVICE_UART2
bool "uart2"
select LISA_DEVICE
select LISA_UART_DEVICE
select LISA_UART2
endchoice
endif
config SYSLOG_PRINTK_REDIRECT
bool "printk redirect"
default n
config SYSLOG_PRINTF_REDIRECT
bool "printf redirect"
default n
config SYSLOG_STDOUT
bool "stdout"
default y
config SYSLOG_BANNER
bool "banner"
default y
endmenu

View File

@@ -0,0 +1,276 @@
#if CFG_BACK_TRACE
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include "arcs_ap.h"
#include "system_RISCVN300.h"
#include "nmsis_core.h"
#include "log_print.h"
#include "sysexec.h"
#include "multi_heap.h"
#include "FreeRTOS.h"
#include "task.h"
#define RVB_CALL_STACK_MAX_DEPTH 16
#define rvb_print(fmt, ...) printf(fmt, ##__VA_ARGS__)
#define rvb_println(fmt, ...) printf(fmt "\n", ##__VA_ARGS__)
struct stackframe {
uint32_t fp;
uint32_t ra;
};
#define ADDR_IN_RANGE(addr, start, end) (((addr) >= (start)) && ((addr) <= (end)))
#define ADDR_IN_SRAM(addr) ADDR_IN_RANGE(addr, 0x20000000, 0x20000000 + (256 + 64 + 384 + 24) * 1024)
#define ADDR_IN_PSRAM(addr) ADDR_IN_RANGE(addr, 0x28000000, 0x28000000 + 16 * 1024 * 1024)
static bool addr_isvalid(uint32_t addr)
{
if (ADDR_IN_SRAM(addr)) {
return true;
}
if (ADDR_IN_PSRAM(addr)) {
return true;
}
return false;
}
static void stack_dump(uint32_t *data, size_t cnt)
{
for (size_t i = 0; i < cnt; i++) {
if (i % 4 == 0) {
rvb_print("\n%p: ", data);
}
rvb_print("%08lx ", (unsigned long)*data++);
}
rvb_print("\n");
}
static inline bool frame_isvalid(struct stackframe *frame, uint32_t sp_start, uint32_t sp_end)
{
if ((uint32_t)frame < sp_start || (uint32_t)frame > sp_end) {
return false;
}
if (!addr_isvalid((uint32_t)frame)) {
return false;
}
if (!addr_isvalid(frame->fp)) {
return false;
}
return true;
}
static inline void backtrace(uint32_t pc, uint32_t fp, uint32_t sp_start, uint32_t sp_end)
{
rvb_println("Possible backtrace:");
rvb_print("riscv64-unknown-elf-addr2line -e build/" PROJECT_EXECUTABLE_NAME " -a ");
rvb_print("%lx ", (unsigned long)pc);
struct stackframe *frame;
frame = (struct stackframe *)(fp - 2 * sizeof(uint32_t));
while (frame_isvalid(frame, sp_start, sp_end)) {
rvb_print("%lx ", (unsigned long)(frame->ra - 4));
frame = (struct stackframe *)(frame->fp - 2 * sizeof(uint32_t));
}
rvb_println("");
}
static void task_backtrace(TaskHandle_t th, uint32_t pc, uint32_t sp, uint32_t fp)
{
TaskStatus_t task_status = {0};
vTaskGetInfo(th, &task_status, pdFALSE, eInvalid);
rvb_println("Fault on task: %p(%s), stack:0x%08lx-0x%08lx, sp:0x%08lx\n", th, task_status.pcTaskName,
(unsigned long)task_status.pxStackBase, (unsigned long)task_status.pxEndOfStack, (unsigned long)sp);
if (sp < (uint32_t)task_status.pxStackBase || sp > (uint32_t)task_status.pxEndOfStack) {
rvb_println("Stack overflow\n");
} else {
rvb_println("Stack dump on task: %p(%s)", th, task_status.pcTaskName);
stack_dump((uint32_t *)sp, ((uint32_t)task_status.pxEndOfStack - sp) / sizeof(uint32_t));
}
backtrace(pc, fp, (uint32_t)task_status.pxStackBase, (uint32_t)task_status.pxEndOfStack);
rvb_println("backtrace end");
}
static void show_all_tasks_info()
{
const char *task_state_str[] = {
"running",
"ready",
"blocked",
"suspended",
"deleted",
"invalid",
};
rvb_println("");
rvb_println("**********************task info**********************");
TaskStatus_t *pxTaskStatusArray;
UBaseType_t uxArraySize, uxTask;
configRUN_TIME_COUNTER_TYPE ulTotalRunTime;
uxArraySize = uxTaskGetNumberOfTasks();
pxTaskStatusArray = pvPortMalloc(uxArraySize * sizeof(TaskStatus_t));
if (pxTaskStatusArray != NULL) {
uxArraySize = uxTaskGetSystemState(pxTaskStatusArray, uxArraySize, &ulTotalRunTime);
rvb_print("%-12s\t%-12s\t%-12s\t%-12s\t%-12s\t%-12s\n", "name", "state", "prio", "stack(byte)", "max-used(%)", "cpu(%)");
for (uxTask = 0; uxTask < uxArraySize; uxTask++) {
uint32_t stack_size =
(uint32_t)pxTaskStatusArray[uxTask].pxEndOfStack - (uint32_t)pxTaskStatusArray[uxTask].pxStackBase;
rvb_print("%-12s\t%-12s\t%-12ld\t%-12ld\t%-12.2f\t%-12.2f\n", pxTaskStatusArray[uxTask].pcTaskName,
task_state_str[pxTaskStatusArray[uxTask].eCurrentState],
(unsigned long)pxTaskStatusArray[uxTask].uxCurrentPriority,
(unsigned long)stack_size, 100.0f - (float)pxTaskStatusArray[uxTask].usStackHighWaterMark * 4 / (float)stack_size * 100,
(float)pxTaskStatusArray[uxTask].ulRunTimeCounter / (float)ulTotalRunTime * 100);
}
vPortFree(pxTaskStatusArray);
} else {
rvb_print("Failed to allocate memory for task status array.\n");
}
rvb_println("");
}
static void heap_travel_cb(void *start, void *end, multi_heap_info_t *info)
{
rvb_println("%-12p\t%-12p\t%-12d\t%-12d\t%-12d", start, end, info->total_free_bytes,
info->total_allocated_bytes, info->minimum_free_bytes);
}
void show_heap_info(void)
{
void heap_caps_travel(void (*callback)(void *, void *, multi_heap_info_t *));
rvb_println("**********************heap info**********************");
rvb_println("%-12s\t%-12s\t%-12s\t%-12s\t%-12s", "start", "end", "free", "used", "free(min)");
heap_caps_travel(heap_travel_cb);
rvb_println("");
}
enum {
NORMAL_MODE = 0,
INTERRUPT_MODE,
EXCE_MODE,
NMI_MODE,
};
static const char *fault_detail_get(uint8_t exec_code)
{
const char *mdcause_str[4] = {
"reserved",
"pmp",
"bus",
"nice"
};
uint32_t mdcause = __RV_CSR_READ(CSR_MDCAUSE);
if (exec_code == 1 || exec_code == 5 || exec_code == 7) {
return mdcause_str[mdcause];
}
return "unknown";
}
static const char *fault_reason_get(uint8_t code)
{
static const char *exc_reason_str[] = {
[CAUSE_MISALIGNED_FETCH] = "Instruction address misaligned",
[CAUSE_FAULT_FETCH] = "Instruction access fault",
[CAUSE_ILLEGAL_INSTRUCTION] = "Illegal instruction",
[CAUSE_BREAKPOINT] = "Breakpoint",
[CAUSE_MISALIGNED_LOAD] = "Load address misaligned",
[CAUSE_FAULT_LOAD] = "Load access fault",
[CAUSE_MISALIGNED_STORE] = "Store/AMO address misaligned",
[CAUSE_FAULT_STORE] = "Store/AMO access fault",
[CAUSE_USER_ECALL] = "User ecall",
[CAUSE_SUPERVISOR_ECALL] = "Supervisor ecall",
[CAUSE_MACHINE_ECALL] = "Machine ecall",
[CAUSE_FETCH_PAGE_FAULT] = "Fetch page fault",
[CAUSE_LOAD_PAGE_FAULT] = "Load page fault",
[CAUSE_STORE_PAGE_FAULT] = "Store page fault",
[0x18] = "stack overflow",
[0x19] = "stack underflow",
};
return code >= sizeof(exc_reason_str)/sizeof(exc_reason_str[0]) ? "unknown" : exc_reason_str[code];
}
void rv_backtrace_fault(uint32_t sp, struct exec_frame *frame, uint32_t mstatus, uint32_t mstratch)
{
(void)mstratch; // Suppress unused parameter warning
const char *sub_mode_str[] = {
"normal",
"interrupt",
"exception",
"nmi",
};
extern uint32_t _sstack[], _estack[];
uint8_t trap_before = (frame->msubm & MSUBM_PTYP) >> 8;
uint32_t exc_code = frame->mcause & 0x1F;
if (trap_before == INTERRUPT_MODE || trap_before == NMI_MODE) {
sp = frame->sp;
sp += sizeof(struct EXC_Frame);
} else if (trap_before == EXCE_MODE) {
sp = frame->sp;
sp += sizeof(struct exec_frame);
} else if (trap_before == NORMAL_MODE) {
if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
/* nothing */
} else {
sp = frame->sp;
}
}
rvb_println("*****************************************************");
rvb_println("Exception reason: %ld(%s), detail: %s", (unsigned long)exc_code,
fault_reason_get(exc_code), fault_detail_get(exc_code));
rvb_println("interrupt stack: %lx~%lx, sp: %lx", (unsigned long)_sstack, (unsigned long)_estack, (unsigned long)sp);
rvb_println("Fault on mode: %d(%s)", trap_before, sub_mode_str[trap_before]);
if (trap_before == NORMAL_MODE) {
if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
task_backtrace(xTaskGetCurrentTaskHandle(), frame->epc, frame->sp, frame->fp);
goto task_info_show;
}
}
if (sp < (uint32_t)_sstack || sp > (uint32_t)_estack) {
rvb_println("Stack overflow\n");
} else {
rvb_println("Stack dump on interrupt stack");
stack_dump((uint32_t *)sp, ((uint32_t)_estack - sp) / sizeof(uint32_t));
}
backtrace(frame->epc, frame->fp, (uint32_t)_sstack, (uint32_t)_estack);
task_info_show:
rvb_println("\n\n");
if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
show_heap_info();
show_all_tasks_info();
} else {
rvb_println("Rtos is not started");
}
}
#endif

View File

@@ -0,0 +1,75 @@
#include "stdint.h"
#include "stdio.h"
#include "chip.h"
#include "Driver_WDT.h"
#include "wdt_reg.h"
#include "arcs_ap.h"
struct boot_info {
uint32_t reboot_cnt: 8;
uint32_t recover_reason: 8;
uint32_t reserved: 14;
uint32_t boot_wdt: 1;
uint32_t req: 1;
};
static void boot_watchdog_handler(void)
{
ECLIC_DisableIRQ(IRQ_AP_WDT_VECTOR);
struct boot_info *info = (struct boot_info *)&IP_AON_CTRL->REG_AON_DIG_RSVD4.all;
info->boot_wdt = 1;
__asm__ volatile("fence.i");
printf("boot_watchdog_handler\n");
volatile int i = 0;
while(i++ < 10000);
/* 为防止看门狗无法复位, 冗余软件复位 */
info->req = 1;
IP_CMN_SYS->REG_SW_RESET_CP1.bit.CMNSW2CMN_RST_EN = 1;
IP_CMN_SYS->REG_SW_RESET_CP1.bit.CMNSW2CP_RST_EN = 1;
IP_CMN_SYS->REG_SW_RESET_CP1.bit.CMNSW2AP_RST_EN = 1;
__COMPILER_BARRIER();
IP_CMN_SYS->REG_SW_RESET_CP0.all = 0xCAFE000A;
}
int boot_watchdog_init(void)
{
uint8_t clk_src = hal_driver_wdt_clk_src_32k;
uint8_t int_time = hal_driver_wdt_int_time_19;
uint8_t rst_time = hal_driver_wdt_rst_time_14;
uint32_t cfg = 0;
cfg = __RV_INSERT_FIELD(cfg, WDT_CTRL_CLKSEL_Msk, clk_src);
cfg = __RV_INSERT_FIELD(cfg, WDT_CTRL_INTTIME_Msk, int_time);
cfg = __RV_INSERT_FIELD(cfg, WDT_CTRL_RSTTIME_Msk, rst_time);
cfg = __RV_INSERT_FIELD(cfg, WDT_CTRL_RSTEN_Msk, 0x1);
cfg = __RV_INSERT_FIELD(cfg, WDT_CTRL_INTEN_Msk, 0x1);
cfg = __RV_INSERT_FIELD(cfg, WDT_CTRL_EN_Msk, 0x1);
WDT_RegDef *wdt_hw = (WDT_RegDef *)IP_AP_WDT;
wdt_hw->REG_WREN.all = 0x5AA5;
wdt_hw->REG_CTRL.all = cfg;
register_ISR(IRQ_AP_WDT_VECTOR, boot_watchdog_handler, NULL);
ECLIC_EnableIRQ(IRQ_AP_WDT_VECTOR);
return 0;
}
int boot_watchdog_feed(void)
{
WDT_RegDef *wdt_hw = (WDT_RegDef *)IP_AP_WDT;
wdt_hw->REG_WREN.all = 0x5AA5;
wdt_hw->REG_RESTART.all = 0xCAFE;
return 0;
}
int boot_watchdog_enable(int flag)
{
WDT_RegDef *wdt_hw = (WDT_RegDef *)IP_AP_WDT;
wdt_hw->REG_WREN.all = 0x5AA5;
wdt_hw->REG_CTRL.all = __RV_INSERT_FIELD(wdt_hw->REG_CTRL.all, WDT_CTRL_EN_Msk, flag);
return 0;
}

View File

@@ -0,0 +1,658 @@
/*
* cache_ap.c
*
* Created on: Jul 10, 2020
*
*/
#include <assert.h>
#include "chip.h"
#include "nmsis_core.h"
#include "cache.h"
/**
* @brief Enables the CPU instruction cache.
*
* This function activates the internal instruction cache of the CPU
* to enhance the execution speed of programs. It is part of the Hardware
* Abstraction Layer (HAL), providing an interface to manage hardware-specific
* features such as caching operations. Enabling the instruction cache allows
* for faster access to frequently executed instructions, which is crucial
* for performance-critical applications.
*/
void HAL_EnableICache(void){
#if HAL_ICACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
EnableICache();
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Disables the CPU instruction cache.
*
* This function deactivates the internal instruction cache of the CPU
* to potentially aid in debugging or to meet specific system requirements
* where caching of instructions needs to be prevented. It is part of the Hardware
* Abstraction Layer (HAL), providing an interface to manage hardware-specific
* features such as caching operations. Disabling the instruction cache may be
* necessary in scenarios where precise control over instruction execution is required.
*/
void HAL_DisableICache(void){
#if HAL_ICACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
DisableICache();
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Invalidates the CPU instruction cache.
*
* This function clears the contents of the internal instruction cache of the CPU.
* Invalidating the cache is useful to ensure that no stale or corrupted data is used
* by the CPU, which is particularly important after direct memory access (DMA) operations
* or after loading new programs into memory. It is part of the Hardware Abstraction Layer (HAL),
* providing an interface to manage hardware-specific features such as caching operations.
* This operation helps in maintaining data coherency and consistency across the system.
*/
void HAL_InvalidateICache(void){
#if HAL_ICACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
MInvalICache();
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Invalidates a range of the CPU data cache based on address and size.
*
* This function clears a specific portion of the CPU's internal data cache. By providing
* an address and the size of the area, this function ensures that any modifications in
* memory in this specified range do not use stale or outdated cache entries. This is particularly
* useful for systems where memory regions are dynamically altered or when devices not supporting
* cache coherency modify the memory. It helps in maintaining data integrity and coherency
* especially in systems involving direct memory access (DMA) operations.
*
* @param addr Pointer to the start address of the memory region to invalidate.
* @param dsize Size of the memory region to invalidate, in bytes.
*/
void HAL_InvalidateICache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_ICACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_ICACHE_CFG_LINE_SIZE + dsize + (HAL_ICACHE_CFG_LINE_SIZE - 1)) / HAL_ICACHE_CFG_LINE_SIZE;
MInvalICacheLines((unsigned long)addr, (unsigned long)cnt);
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Locks a range of the CPU instruction cache based on address and size.
*
* This function prevents the CPU instruction cache from being updated or invalidated within a specified
* range. It ensures that the cache entries in this range remain fixed and are not replaced or
* evicted. This can be useful in scenarios where instruction stability is critical and should not be
* changed by other operations or processes.
*
* @param addr Pointer to the start address of the memory region to lock.
* @param dsize Size of the memory region to lock, in bytes.
*/
void HAL_LockICache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_ICACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_ICACHE_CFG_LINE_SIZE + dsize + (HAL_ICACHE_CFG_LINE_SIZE - 1)) / HAL_ICACHE_CFG_LINE_SIZE;
MLockICacheLines((unsigned long)addr, (unsigned long)cnt);
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Unlocks a previously locked range of the CPU instruction cache based on address and size.
*
* This function allows the CPU instruction cache to be updated or invalidated within a previously locked
* range. It ensures that the cache entries in this range can now be replaced or evicted as needed,
* returning the cache operation to its normal behavior. This is useful when the critical operation
* requiring instruction stability is complete and normal cache operations need to resume.
*
* @param addr Pointer to the start address of the memory region to unlock.
* @param dsize Size of the memory region to unlock, in bytes.
*/
void HAL_UnLockICache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_ICACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_ICACHE_CFG_LINE_SIZE + dsize + (HAL_ICACHE_CFG_LINE_SIZE - 1)) / HAL_ICACHE_CFG_LINE_SIZE;
MUnlockICacheLines((unsigned long)addr, (unsigned long)cnt);
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Enables the CPU data cache.
*
* This function activates the internal data cache of the CPU
* to enhance the execution speed and efficiency of data access and processing.
* It is part of the Hardware Abstraction Layer (HAL), providing an interface to manage
* hardware-specific features such as caching operations. Enabling the data cache helps
* improve system performance by reducing memory access times and minimizing CPU idle time
* during data fetches from main memory.
*/
void HAL_EnableDCache(void){
#if HAL_DCACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
EnableDCache();
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Disables the CPU data cache.
*
* This function deactivates the internal data cache of the CPU.
* Disabling the data cache can be useful in scenarios where data caching may lead
* to consistency issues, such as during non-cache-coherent DMA operations or when
* the predictability of every data access is required. It is part of the Hardware
* Abstraction Layer (HAL), providing an interface to manage hardware-specific features.
* Disabling the data cache ensures that all data reads and writes are directly made to
* and from the main memory, which can be crucial for real-time and safety-critical applications.
*/
void HAL_DisableDCache(void){
#if HAL_DCACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
DisableDCache();
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Invalidates the CPU data cache.
*
* This function clears the contents of the internal data cache of the CPU.
* Invalidating the cache is essential to prevent the use of stale or incorrect data
* that might remain after changes in memory. It is commonly used after direct memory
* access (DMA) operations or when hardware devices modify memory outside of the CPU's control.
* It is part of the Hardware Abstraction Layer (HAL), providing an interface to manage
* hardware-specific features such as caching operations. This operation ensures data coherency
* and consistency across the system, particularly in systems where memory is shared between the CPU
* and other hardware components.
*/
void HAL_InvalidateDCache(void){
#if HAL_DCACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
MInvalDCache();
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Flushes the CPU data cache.
*
* This function ensures that all modified data within the CPU's internal data cache
* are written back to the main memory. Flushing the data cache is crucial before
* any operations that require up-to-date data from other processors or hardware
* that do not have cache coherency mechanisms. It is part of the Hardware
* Abstraction Layer (HAL), providing an interface to manage hardware-specific features
* such as caching operations. This operation helps maintain data coherency and
* consistency across different parts of the system, particularly in multi-core
* or multi-processor environments.
*/
void HAL_FlushDCache(void){
#if HAL_DCACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
MFlushDCache();
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Flushes and invalidates the CPU data cache.
*
* This function ensures that all modified data within the CPU's internal data cache
* are written back to the main memory, and then invalidates the cache to remove all entries.
* This is particularly useful in scenarios where data coherence and consistency are critical,
* such as before DMA operations where peripheral devices need to access the latest data,
* or after updating firmware that changes the memory layout. It is part of the Hardware
* Abstraction Layer (HAL), providing an interface to manage hardware-specific features
* such as caching operations. Flushing and invalidating the data cache ensures that
* no stale data is used and all future data reads are done directly from the main memory.
*/
void HAL_FlushInvalidateDCache(void){
#if HAL_DCACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
MFlushInvalDCache();
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Invalidates a range of the CPU data cache based on address and size.
*
* This function clears a specific portion of the CPU's internal data cache. By providing
* an address and the size of the area, this function ensures that any modifications in
* memory in this specified range do not use stale or outdated cache entries. This is particularly
* useful for systems where memory regions are dynamically altered or when devices not supporting
* cache coherency modify the memory. It helps in maintaining data integrity and coherency
* especially in systems involving direct memory access (DMA) operations.
*
* @param addr Pointer to the start address of the memory region to invalidate.
* @param dsize Size of the memory region to invalidate, in bytes.
*/
_FAST_FUNC_SRAM void HAL_InvalidateDCache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_DCACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_DCACHE_CFG_LINE_SIZE + dsize + (HAL_DCACHE_CFG_LINE_SIZE - 1)) / HAL_DCACHE_CFG_LINE_SIZE;
MInvalDCacheLines((unsigned long)addr, (unsigned long)cnt);
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Flushes a range of the CPU data cache based on address and size.
*
* This function writes back all modified data within a specified range of the CPU's internal data cache
* to the main memory. This operation is crucial for ensuring data coherence in systems where other processors
* or hardware devices access the same memory region but do not share a cache coherency mechanism. It is typically
* used prior to DMA operations or when processors in a multi-processor system access shared data.
*
* @param addr Pointer to the start address of the memory region to flush.
* @param dsize Size of the memory region to flush, in bytes.
*/
_FAST_FUNC_SRAM void HAL_FlushDCache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_DCACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_DCACHE_CFG_LINE_SIZE + dsize + (HAL_DCACHE_CFG_LINE_SIZE - 1)) / HAL_DCACHE_CFG_LINE_SIZE;
MFlushDCacheLines((unsigned long)addr, (unsigned long)cnt);
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Flushes and invalidates a range of the CPU data cache based on address and size.
*
* This function combines the actions of writing back all modified data within a specified range
* of the CPU's internal data cache to the main memory and then invalidating the cache entries.
* This ensures that no stale data remains and all future accesses to this memory range will be
* fetched directly from the main memory. This operation is particularly vital in systems with
* non-cache-coherent DMA operations or in multi-core systems where processors need to share
* up-to-date data without any inconsistencies.
*
* @param addr Pointer to the start address of the memory region to flush and invalidate.
* @param dsize Size of the memory region to flush and invalidate, in bytes.
*/
void HAL_FlushInvalidateDCache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_DCACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_DCACHE_CFG_LINE_SIZE + dsize + (HAL_DCACHE_CFG_LINE_SIZE - 1)) / HAL_DCACHE_CFG_LINE_SIZE;
MFlushInvalDCacheLines((unsigned long)addr, (unsigned long)cnt);
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Locks a range of the CPU data cache based on address and size.
*
* This function prevents the CPU data cache from being updated or invalidated within a specified
* range. It ensures that the cache entries in this range remain fixed and are not replaced or
* evicted. This can be useful in scenarios where data stability is critical and should not be
* changed by other operations or processes.
*
* @param addr Pointer to the start address of the memory region to lock.
* @param dsize Size of the memory region to lock, in bytes.
*/
void HAL_LockDCache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_DCACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_DCACHE_CFG_LINE_SIZE + dsize + (HAL_DCACHE_CFG_LINE_SIZE - 1)) / HAL_DCACHE_CFG_LINE_SIZE;
MLockDCacheLines((unsigned long)addr, (unsigned long)cnt);
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
/**
* @brief Unlocks a previously locked range of the CPU data cache based on address and size.
*
* This function allows the CPU data cache to be updated or invalidated within a previously locked
* range. It ensures that the cache entries in this range can now be replaced or evicted as needed,
* returning the cache operation to its normal behavior. This is useful when the critical operation
* requiring data stability is complete and normal cache operations need to resume.
*
* @param addr Pointer to the start address of the memory region to unlock.
* @param dsize Size of the memory region to unlock, in bytes.
*/
void HAL_UnLockDCache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_DCACHE_VALID
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_DCACHE_CFG_LINE_SIZE + dsize + (HAL_DCACHE_CFG_LINE_SIZE - 1)) / HAL_DCACHE_CFG_LINE_SIZE;
MUnlockDCacheLines((unsigned long)addr, (unsigned long)cnt);
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
#endif
}
// This function will be abandon
int range_is_cacheable(unsigned long start, unsigned long size){
return 0;
}
void unaligned_cache_line_move(unsigned char* src, unsigned char* dst, unsigned long len)
{
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
int i;
unsigned char* src_p = (unsigned char*) src;
unsigned char* dst_p = (unsigned char*) dst;
for (i = 0; i < len; ++i) {
*(dst_p + i) = *(src_p + i);
}
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
}
void dcache_clean_range(unsigned long start, unsigned long end){
uint32_t line_mask = HAL_DCACHE_CFG_LINE_SIZE - 1;
// 对start向上取整到cache line边界
unsigned long aligned_start = (start + line_mask) & (~line_mask);
// 对end向下取整到cache line边界
unsigned long aligned_end = end & (~line_mask);
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
// 只有当有完整的cache line需要处理时才进行操作
if (aligned_start < aligned_end) {
HAL_FlushDCache_by_Addr((uint32_t *)aligned_start, (aligned_end - aligned_start));
}
// 对不对齐的部分进行单独处理
if (start < aligned_start) {
// 处理start到aligned_start之间的数据
// 这里需要更细粒度的处理方式
}
if (end > aligned_end) {
// 处理aligned_end到end之间的数据
// 这里需要更细粒度的处理方式
}
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
}
void dcache_invalidate_range(unsigned long start, unsigned long end){
uint32_t line_mask = HAL_DCACHE_CFG_LINE_SIZE - 1;
// 对start向上取整到cache line边界
unsigned long aligned_start = (start + line_mask) & (~line_mask);
// 对end向下取整到cache line边界
unsigned long aligned_end = end & (~line_mask);
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
// 只有当有完整的cache line需要处理时才进行操作
if (aligned_start < aligned_end) {
HAL_InvalidateDCache_by_Addr((uint32_t *)aligned_start, (aligned_end - aligned_start));
}
// 对不对齐的部分进行单独处理
if (start < aligned_start) {
// 处理start到aligned_start之间的数据
// 这里需要更细粒度的处理方式
}
if (end > aligned_end) {
// 处理aligned_end到end之间的数据
// 这里需要更细粒度的处理方式
}
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
}
void dcache_flush_range(unsigned long start, unsigned long end){
uint32_t line_mask = HAL_DCACHE_CFG_LINE_SIZE - 1;
// 对start向上取整到cache line边界
unsigned long aligned_start = (start + line_mask) & (~line_mask);
// 对end向下取整到cache line边界
unsigned long aligned_end = end & (~line_mask);
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
// 只有当有完整的cache line需要处理时才进行操作
if (aligned_start < aligned_end) {
HAL_FlushDCache_by_Addr((uint32_t *)aligned_start, (aligned_end - aligned_start));
HAL_InvalidateDCache_by_Addr((uint32_t *)aligned_start, (aligned_end - aligned_start));
}
// 对不对齐的部分进行单独处理
if (start < aligned_start) {
// 处理start到aligned_start之间的数据
// 这里需要更细粒度的处理方式
}
if (end > aligned_end) {
// 处理aligned_end到end之间的数据
// 这里需要更细粒度的处理方式
}
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
}
void cache_dma_fast_inv_stage1(unsigned long start, unsigned long end){
unsigned long line_size;
unsigned long old_start = start;
unsigned long old_end = end;
line_size = HAL_DCACHE_CFG_LINE_SIZE;
start = start & (~(line_size - 1));
end = (end + line_size - 1) & (~(line_size - 1));
if (start == end)
return;
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
if (start != old_start) {
HAL_FlushDCache_by_Addr((uint32_t *)start, line_size);
}
if (end != old_end) {
HAL_FlushDCache_by_Addr((uint32_t *)(end - line_size), line_size);
}
HAL_InvalidateDCache_by_Addr((uint32_t *)start, (end - start));
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
}
// void cache_dma_fast_inv_stage2(unsigned long start, unsigned long end){
// }
// dcache_clean_range(buff_addr, buff_addr + blk_sz * blk_cnt);
// gm_cpu_clean_dcache_range(q->payload, q->len);
// gm_cpu_dcache_invalidate_range(q->payload, q->len);
// cache_dma_fast_inv_stage1(buff_addr, buff_addr + blk_sz * blk_cnt);
// dcache_clean_range(buff_addr, buff_addr + blk_sz * blk_cnt);
// // usually called after transferring data to memory (NOT cache-line-aligned) via DMA
void cache_dma_fast_inv_stage2(unsigned long start, unsigned long end)
{
unsigned long line_size;
unsigned long old_start = start;
unsigned long old_end = end;
static unsigned char cache_line_buf[32];
line_size = HAL_DCACHE_CFG_LINE_SIZE;
start = start & (~(line_size - 1));
end = (end + line_size - 1) & (~(line_size - 1));
if (start == end)
return;
int use_lock = 0;
// interrupt enabled, and not in interrupt context
if(start != old_start || end != old_end)
use_lock = 1;
if (use_lock) {
disable_GINT();
}
// 原子地清除 MIE 位并返回旧值
unsigned long mstatus = __RV_CSR_READ_CLEAR(CSR_MSTATUS, MSTATUS_MIE);
if (start != old_start) {
unaligned_cache_line_move((unsigned char*) start, cache_line_buf, old_start - start);
HAL_InvalidateDCache_by_Addr((uint32_t *)start, line_size);
unaligned_cache_line_move(cache_line_buf, (unsigned char*) start, old_start - start);
}
if (end != old_end) {
unaligned_cache_line_move((unsigned char*) old_end, cache_line_buf, end - old_end);
HAL_InvalidateDCache_by_Addr((uint32_t *)(end - line_size), line_size);
unaligned_cache_line_move(cache_line_buf, (unsigned char*) old_end, end - old_end);
}
// 如果之前中断是开启的,恢复 MIE 位
if (mstatus & MSTATUS_MIE) {
__RV_CSR_SET(CSR_MSTATUS, MSTATUS_MIE);
}
if (use_lock) {
enable_GINT();
}
}

View File

@@ -0,0 +1,69 @@
#include "arcs_ap.h"
#include <stdio.h>
#include <stdbool.h>
#if CONFIG_MODULE_FREERTOS
#include "FreeRTOS.h"
#include "task.h"
#if configUSE_IDLE_HOOK
void vApplicationIdleHook(void)
{
__WFI();
}
#endif//configUSE_IDLE_HOOK
#if configUSE_MALLOC_FAILED_HOOK
void vApplicationMallocFailedHook(void)
{
// ASSERT(false, "MallocFailed@%s", x_task_name(NULL));
printf("MallocFailed@%s\r\n", xPortIsInsideInterrupt() ? "<ISR>" : pcTaskGetName(xTaskGetCurrentTaskHandle()));
__builtin_trap();
}
#endif//configUSE_MALLOC_FAILED_HOOK
#if configCHECK_FOR_STACK_OVERFLOW
void vApplicationStackOverflowHook(TaskHandle_t task, char *name)
{
// ASSERT(false, "StackOverflow@%s", name);
// printf("StackOverflow@%s\r\n", name);
printf("StackOverflow@%s\r\n", name);
__builtin_trap();
}
#endif//configCHECK_FOR_STACK_OVERFLOW
#if configUSE_TICK_INITAL_HOOK
TickType_t portTickInitalHook( TickType_t tick )
{
// Enable force wakeup
IP_SYSCTRL->REG_RTC_FORCE_WAKEUP.bit.FORCE_WAKEUP = 0x1;
while(!IP_CALENDAR->REG_STATUS.bit.FORCE_WAKEUP);
// Disable CALENDAR interrupt
IP_CALENDAR->REG_CMD.bit.ALARM_ENABLE_CLR = 0x1;
while(IP_CALENDAR->REG_CMD.bit.ALARM_ENABLE_CLR);
IP_CALENDAR->REG_CMD.bit.ITV_IRQ_MASK_CLR = 0x1;
while(IP_CALENDAR->REG_CMD.bit.ITV_IRQ_MASK_CLR);
// Clear IRQ pending status
IP_CALENDAR->REG_CMD.bit.ITV_IRQ_CLR = 0x1;
IP_CALENDAR->REG_CMD.bit.ALARM_CLR = 0x1;
volatile uint32_t days = IP_CALENDAR->REG_CUR_VAL_H.bit.DAY;
volatile uint32_t hour = IP_CALENDAR->REG_CUR_VAL_L.bit.HOUR;
volatile uint32_t mint = IP_CALENDAR->REG_CUR_VAL_L.bit.MIN;
volatile uint32_t secs = IP_CALENDAR->REG_CUR_VAL_L.bit.SEC;
volatile uint32_t msec = (((days * 24 + hour) * 60 + mint) * 60 + secs) * 1000;
return msec / portTICK_PERIOD_MS;
}
#endif
#endif

View File

@@ -0,0 +1,89 @@
#ifndef __ARCS_MEMAP_HEADER__
#define __ARCS_MEMAP_HEADER__
#if CONFIG_MEM_CONFIG
/* sram */
#define MEM_SRAM_BASE CONFIG_MEM_SRAM_BASE
#define MEM_SRAM_SIZE CONFIG_MEM_SRAM_SIZE
/* psram */
#define MEM_PSRAM_BASE CONFIG_MEM_PSRAM_BASE
#define MEM_PSRAM_SIZE CONFIG_MEM_PSRAM_SIZE
/* luna */
#define MEM_LUNA_BASE CONFIG_MEM_LUNA_BASE
#define MEM_LUNA_SIZE CONFIG_MEM_LUNA_SIZE
/* BT */
#define MEM_BTRAM_BASE CONFIG_MEM_BTRAM_BASE
#define MEM_BTRAM_SIZE CONFIG_MEM_BTRAM_SIZE
/* flash */
#if CONFIG_BOOT
#define MEM_FLASH_BASE (CONFIG_MEM_FLASH_BASE + CONFIG_BOOT_FLASH_SIZE)
#define MEM_FLASH_SIZE (CONFIG_MEM_FLASH_SIZE - CONFIG_BOOT_FLASH_SIZE)
#else
#define MEM_FLASH_BASE CONFIG_MEM_FLASH_BASE
#define MEM_FLASH_SIZE CONFIG_MEM_FLASH_SIZE
#endif
#if CONFIG_MEM_WFRAM_ISOLATED
/* wifi */
#define MEM_WFRAM_BASE CONFIG_MEM_WFRAM_BASE
#define MEM_WFRAM_SIZE CONFIG_MEM_WFRAM_SIZE
#endif
/* ilm */
#define MEM_ILM_BASE CONFIG_MEM_ILM_BASE
#define MEM_ILM_SIZE CONFIG_MEM_ILM_SIZE
/* dlm */
#define MEM_DLM_BASE CONFIG_MEM_DLM_BASE
#define MEM_DLM_SIZE CONFIG_MEM_DLM_SIZE
#if CONFIG_MEM_IPC_ISOLATED
/* ipc */
#define MEM_IPC_BASE CONFIG_MEM_IPC_BASE
#define MEM_IPC_SIZE CONFIG_MEM_IPC_SIZE
#endif
#define MEM_WIFI_CALIBRATION_SIZE CONFIG_MEM_WIFI_CALIBRATION_SIZE
#define MEM_WIFI_TRACE_SIZE CONFIG_MEM_WIFI_TRACE_SIZE
#define MEM_INTERRUPT_STACK_SIZE CONFIG_MEM_INTERRUPT_STACK_SIZE
#else
#define MEM_SRAM_BASE 0x20050000
#define MEM_SRAM_SIZE (384 * 1024)
#define MEM_PSRAM_BASE 0x28000000
#define MEM_PSRAM_SIZE (8 * 1024 * 1024)
#if CONFIG_BOOT
#define MEM_FLASH_BASE (0x30000000 + CONFIG_BOOT_FLASH_SIZE)
#define MEM_FLASH_SIZE (8 * 1024 * 1024 - CONFIG_BOOT_FLASH_SIZE)
#else
#define MEM_FLASH_BASE 0x30000000
#define MEM_FLASH_SIZE (8 * 1024 * 1024)
#define MEM_FLASH_EX_BASE 0x31000000
#define MEM_FLASH_EX_SIZE (__MB__(16)) //外部flash大小, 目前
#endif
#define MEM_WFRAM_BASE 0x20000000
#define MEM_WFRAM_SIZE (256 * 1024)
#define MEM_ILM_BASE 0x00080000
#define MEM_ILM_SIZE (16 * 1024)
#define MEM_DLM_BASE 0x00100000
#define MEM_DLM_SIZE (8 * 1024)
#define MEM_WIFI_CALIBRATION_SIZE (16 * 1024)
#define MEM_WIFI_TRACE_SIZE (8 * 1024)
#define MEM_INTERRUPT_STACK_SIZE (4 * 1024)
#endif
#endif//__ARCS_MEMAP_HEADER__

View File

@@ -0,0 +1,7 @@
#include <stdio.h>
__attribute__((weak)) void pre_main_hook(void)
{
}

View File

@@ -0,0 +1,47 @@
#include <stdint.h>
extern uint32_t __scat_copy_base, __scat_copy_last, __scat_zero_base, __scat_zero_last;
extern uint32_t __psram_scat_copy_base, __psram_scat_copy_last, __psram_scat_zero_base, __psram_scat_zero_last;
typedef struct { uint32_t len, *vma, *lma; } scat_copy_item_t;
typedef struct { uint32_t len, *vma; } scat_zero_item_t;
__attribute__((section(".init")))
static void _scatload(uint32_t *dst, const uint32_t *src, uint32_t cnt)
{
while (cnt--) *dst++ = *src++;
}
__attribute__((section(".init")))
static void _scatfill(uint32_t *dst, uint32_t fill, int cnt)
{
while (cnt--) *dst++ = fill;
}
__attribute__((section(".init")))
void scatload(void)
{
for (scat_copy_item_t *item = (void *)&__scat_copy_base; (uint32_t *)item < &__scat_copy_last; item++)
if (item->vma && item->len >= sizeof(uint32_t) && item->vma != item->lma)
_scatload(item->vma, item->lma, item->len >> 2);
for (scat_zero_item_t *item = (void *)&__scat_zero_base; (uint32_t *)item < &__scat_zero_last; item++)
if (item->vma && item->len >= sizeof(uint32_t))
_scatfill(item->vma, 0, item->len >> 2);
}
void scatload_psram(void)
{
for (scat_copy_item_t *item = (void *)&__psram_scat_copy_base; (uint32_t *)item < &__psram_scat_copy_last; item++) {
if (item->vma && item->len >= sizeof(uint32_t) && item->vma != item->lma) {
_scatload(item->vma, item->lma, item->len >> 2);
}
}
for (scat_zero_item_t *item = (void *)&__psram_scat_zero_base; (uint32_t *)item < &__psram_scat_zero_last; item++) {
if (item->vma && item->len >= sizeof(uint32_t)) {
_scatfill(item->vma, 0, item->len >> 2);
}
}
}

View File

@@ -0,0 +1,266 @@
/*
* Copyright (c) 2019 Nuclei Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed 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
*
* 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.
*/
/******************************************************************************
* \file startup_demosoc.S
* \brief NMSIS Nuclei N/NX Class Core based Core Device Startup File for
* Nuclei Demo SoC which support Nuclei N/NX class cores
* \version V1.00
* \date 17. Dec 2019
*
******************************************************************************/
#include "riscv_encoding.h"
/* If BOOT_HARTID is not defined, default value is 0 */
#ifndef BOOT_HARTID
.equ BOOT_HARTID, 0
#endif
.macro DECLARE_INT_HANDLER INT_HDL_NAME
#if defined(__riscv_xlen) && (__riscv_xlen == 32)
.word \INT_HDL_NAME
#else
.dword \INT_HDL_NAME
#endif
.endm
.section .vtable
.globl vector_base
.type vector_base, @object
vector_base:
#ifndef VECTOR_TABLE_REMAPPED
j _start /* 0: Reserved, Jump to _start when reset for vector table not remapped cases.*/
.align LOG_REGBYTES /* Need to align 4 byte for RV32, 8 Byte for RV64 */
#else
DECLARE_INT_HANDLER Interrupt0_Handler /* 0: Reserved, default handler for vector table remapped cases */
#endif
DECLARE_INT_HANDLER Interrupt1_Handler /* 1: Reserved */
DECLARE_INT_HANDLER Interrupt2_Handler /* 2: Reserved */
#ifndef CFG_RTOS
DECLARE_INT_HANDLER Interrupt3_Handler /* 3: Machine software interrupt */
#else
DECLARE_INT_HANDLER eclic_msip_handler /* 3: Machine software interrupt, vector mode for FreeRTOS implementation */
#endif
DECLARE_INT_HANDLER Interrupt4_Handler /* 4: Reserved */
DECLARE_INT_HANDLER Interrupt5_Handler /* 5: Reserved */
DECLARE_INT_HANDLER Interrupt6_Handler /* 6: Reserved */
DECLARE_INT_HANDLER Interrupt7_Handler /* 7: Machine timer interrupt */
DECLARE_INT_HANDLER Interrupt8_Handler /* 8: Reserved */
DECLARE_INT_HANDLER Interrupt9_Handler /* 9: Reserved */
DECLARE_INT_HANDLER Interrupt10_Handler /* 10: Reserved */
DECLARE_INT_HANDLER Interrupt11_Handler /* 11: Reserved */
DECLARE_INT_HANDLER Interrupt12_Handler /* 12: Reserved */
DECLARE_INT_HANDLER Interrupt13_Handler /* 13: Reserved */
DECLARE_INT_HANDLER Interrupt14_Handler /* 14: Reserved */
DECLARE_INT_HANDLER Interrupt15_Handler /* 15: Reserved */
DECLARE_INT_HANDLER Interrupt16_Handler /* 16: Reserved */
DECLARE_INT_HANDLER Interrupt17_Handler /* 17: Reserved */
DECLARE_INT_HANDLER Interrupt18_Handler /* 18: Reserved */
DECLARE_INT_HANDLER Interrupt19_Handler /* 19: Interrupt 19 */
DECLARE_INT_HANDLER Interrupt20_Handler /* 20: Interrupt 20 */
DECLARE_INT_HANDLER Interrupt21_Handler /* 21: Interrupt 21 */
DECLARE_INT_HANDLER Interrupt22_Handler /* 22: Interrupt 22 */
DECLARE_INT_HANDLER Interrupt23_Handler /* 23: Interrupt 23 */
DECLARE_INT_HANDLER Interrupt24_Handler /* 24: Interrupt 24 */
DECLARE_INT_HANDLER Interrupt25_Handler /* 25: Interrupt 25 */
DECLARE_INT_HANDLER Interrupt26_Handler /* 26: Interrupt 26 */
DECLARE_INT_HANDLER Interrupt27_Handler /* 27: Interrupt 27 */
DECLARE_INT_HANDLER Interrupt28_Handler /* 28: Interrupt 28 */
DECLARE_INT_HANDLER Interrupt29_Handler /* 29: Interrupt 29 */
DECLARE_INT_HANDLER Interrupt30_Handler /* 30: Interrupt 30 */
DECLARE_INT_HANDLER Interrupt31_Handler /* 31: Interrupt 31 */
DECLARE_INT_HANDLER Interrupt32_Handler /* 32: Interrupt 32 */
DECLARE_INT_HANDLER Interrupt33_Handler /* 33: Interrupt 33 */
DECLARE_INT_HANDLER Interrupt34_Handler /* 34: Interrupt 34 */
DECLARE_INT_HANDLER Interrupt35_Handler /* 35: Interrupt 35 */
DECLARE_INT_HANDLER Interrupt36_Handler /* 36: Interrupt 36 */
DECLARE_INT_HANDLER Interrupt37_Handler /* 37: Interrupt 37 */
DECLARE_INT_HANDLER Interrupt38_Handler /* 38: Interrupt 38 */
DECLARE_INT_HANDLER Interrupt39_Handler /* 39: Interrupt 39 */
DECLARE_INT_HANDLER Interrupt40_Handler /* 40: Interrupt 40 */
DECLARE_INT_HANDLER Interrupt41_Handler /* 41: Interrupt 41 */
DECLARE_INT_HANDLER Interrupt42_Handler /* 42: Interrupt 42 */
DECLARE_INT_HANDLER Interrupt43_Handler /* 43: Interrupt 43 */
DECLARE_INT_HANDLER Interrupt44_Handler /* 44: Interrupt 44 */
DECLARE_INT_HANDLER Interrupt45_Handler /* 45: Interrupt 45 */
DECLARE_INT_HANDLER Interrupt46_Handler /* 46: Interrupt 46 */
DECLARE_INT_HANDLER Interrupt47_Handler /* 47: Interrupt 47 */
DECLARE_INT_HANDLER Interrupt48_Handler /* 48: Interrupt 48 */
DECLARE_INT_HANDLER Interrupt49_Handler /* 49: Interrupt 49 */
DECLARE_INT_HANDLER Interrupt50_Handler /* 50: Interrupt 50 */
DECLARE_INT_HANDLER Interrupt51_Handler /* 51: Interrupt 51 */
DECLARE_INT_HANDLER Interrupt52_Handler /* 52: Interrupt 52 */
DECLARE_INT_HANDLER Interrupt53_Handler /* 53: Interrupt 53 */
DECLARE_INT_HANDLER Interrupt54_Handler /* 54: Interrupt 54 */
DECLARE_INT_HANDLER Interrupt55_Handler /* 55: Interrupt 55 */
DECLARE_INT_HANDLER Interrupt56_Handler /* 56: Interrupt 56 */
DECLARE_INT_HANDLER Interrupt57_Handler /* 57: Interrupt 57 */
DECLARE_INT_HANDLER Interrupt58_Handler /* 58: Interrupt 58 */
DECLARE_INT_HANDLER Interrupt59_Handler /* 59: Interrupt 59 */
DECLARE_INT_HANDLER Interrupt60_Handler /* 60: Interrupt 60 */
DECLARE_INT_HANDLER Interrupt61_Handler /* 61: Interrupt 61 */
DECLARE_INT_HANDLER Interrupt62_Handler /* 62: Interrupt 62 */
DECLARE_INT_HANDLER Interrupt63_Handler /* 63: Interrupt 63 */
DECLARE_INT_HANDLER Interrupt64_Handler /* 64: Interrupt 64 */
DECLARE_INT_HANDLER Interrupt65_Handler /* 65: Interrupt 65 */
DECLARE_INT_HANDLER Interrupt66_Handler /* 66: Interrupt 66 */
DECLARE_INT_HANDLER Interrupt67_Handler /* 67: Interrupt 67 */
DECLARE_INT_HANDLER Interrupt68_Handler /* 68: Interrupt 68 */
DECLARE_INT_HANDLER Interrupt69_Handler /* 69: Interrupt 69 */
DECLARE_INT_HANDLER Interrupt70_Handler /* 70: Interrupt 70 */
DECLARE_INT_HANDLER Interrupt71_Handler /* 71: Interrupt 71 */
DECLARE_INT_HANDLER Interrupt72_Handler /* 72: Interrupt 72 */
DECLARE_INT_HANDLER Interrupt73_Handler /* 73: Interrupt 73 */
DECLARE_INT_HANDLER Interrupt74_Handler /* 74: Interrupt 74 */
DECLARE_INT_HANDLER Interrupt75_Handler /* 75: Interrupt 75 */
DECLARE_INT_HANDLER Interrupt76_Handler /* 76: Interrupt 76 */
DECLARE_INT_HANDLER Interrupt77_Handler /* 77: Interrupt 77 */
.word 0 /* 78: reserved */
.word 0 /* 79: reserved */
/* Header */
.ascii "Hr" /* byte(0~1): header mark */
.byte 0x01, 0x04 /* byte(2~3): header version 1.4 */
.word 0 /* byte(4~7): image size */
.word vector_base /* byte(8~11): image vma */
.byte 0x01, 0x00, 0x03 /* byte(12~14): image version 1.0.1 */
.byte 0x00 /* byte(15~15): image flags */
.ascii "ARCS", "_APP", "\0\0\0\0" /* byte(16~27): image name */
.short 0x00 /* byte(28~29): patch_offset*/
.short 0x00 /* byte(30~31): gpt_offset */
.word 0 /* byte(32~59): reserved */
.word 0 /* byte(36~39): reserved */
.word 0 /* byte(40~43): reserved */
.word 0 /* byte(44~47): reserved */
.word 0 /* byte(48~51): reserved */
.word 0 /* byte(52~55): reserved */
.word 0 /* byte(56~59): reserved */
.short 0x0 /* byte(60~61): header check sum */
.short 0x0 /* byte(62~63): vector check sum */
/* Reset Handler called on controller reset */
.section .init
.section .init
.section .init
.globl _start
.type _start, @function
_start:
/* ===== Startup Stage 1 ===== */
/* Disable Global Interrupt */
csrc CSR_MSTATUS, MSTATUS_MIE
/* Initialize GP and TP */
.option push
.option norelax
la gp, __global_pointer$
la tp, __tls_base
.option pop
/* Set correct sp for current cpu */
la sp, __StackTop
/* Set the the NMI base mnvec to share with mtvec by setting CSR_MMISC_CTL bit 9 NMI_CAUSE_FFF to 1 */
li t0, MMISC_CTL_NMI_CAUSE_FFF
csrs CSR_MMISC_CTL, t0
/* Intialize ECLIC vector interrupt base address mtvt to vector_base */
la t0, vector_base
csrw CSR_MTVT, t0
/* Set ECLIC non-vector entry to be controlled by mtvt2 CSR register.
* Intialize ECLIC non-vector interrupt base address mtvt2 to irq_entry. */
la t0, irq_entry
csrw CSR_MTVT2, t0
csrs CSR_MTVT2, 0x1
/* Set Exception Entry MTVEC to early_exc_entry Due to settings above, Exception and NMI will share common entry.
* This early_exc_entry is only used during early boot stage before main */
la t0, early_exc_entry
csrw CSR_MTVEC, t0
/* Set the interrupt processing mode to ECLIC mode */
li t0, 0x3f
csrc CSR_MTVEC, t0
csrs CSR_MTVEC, 0x3
/* ===== Startup Stage 2 ===== */
/* Enable FPU and Vector Unit if f/d/v exist in march */
#if defined(__riscv_flen) && __riscv_flen > 0
/* Enable FPU, and set state to initial */
li t0, MSTATUS_FS
csrc mstatus, t0
li t0, MSTATUS_FS_INITIAL
csrs mstatus, t0
#endif
#if defined(__riscv_vector)
/* Enable Vector, and set state to initial */
li t0, MSTATUS_VS
csrc mstatus, t0
li t0, MSTATUS_VS_INITIAL
csrs mstatus, t0
#endif
/* Enable mcycle and minstret counter */
csrci CSR_MCOUNTINHIBIT, 0x5
/*call platform pre startup*/
call platform_pre_startup
/* ===== Startup Stage 3 ===== */
/* Load each prev-stage section from ROM to RAM when the LMA!=VMA and LEN > 0 */
call scatload
/* Call vendor defined SystemInit to initialize the micro-controller system
* SystemInit will just be called by boot cpu */
call SystemInit
/* When all initialization steps done set exception entry to correct exception entry and jump to main.
* And set the interrupt processing mode to ECLIC mode */
la t0, exc_entry
csrw CSR_MTVEC, t0
li t0, 0x3f
csrc CSR_MTVEC, t0
csrs CSR_MTVEC, 0x3
/* BPU cold bringup need time, so enable BPU before enter to main */
li t0, MMISC_CTL_BPU
csrs CSR_MMISC_CTL, t0
/* 防止在RTOS未启动前发生exception无法正常回朔 */
/* 注意,这里从中断栈的底部加上1024字节作为回溯时栈空间 */
/* 如果触发异常前, 栈已经使用到了这个空间, 则可能导致回溯失败 */
la t0, __StackTop
addi t0, t0, 1024
csrw CSR_MSCRATCH, t0
/* Call Application Entry */
call entry
/* Early boot exception entry before main */
.align 6
.global early_exc_entry
.type early_exc_entry, @function
early_exc_entry:
wfi
j early_exc_entry

View File

@@ -0,0 +1,229 @@
/*
* Copyright (c) 2025, LISTENAI
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @file sys_init.c
* @brief ARCS System Initialization Framework - Core Implementation
*/
#include "sys_init.h"
#include <stddef.h>
#include <string.h>
#define LEVEL_TABLE_SIZE (SYS_INIT_LEVEL_MAX) /* Total number of levels */
/* ========================================================================
* Linker Symbol Declarations
* ======================================================================== */
/* Declare section start/end symbols for each level */
extern sys_init_entry_t __sys_init_start[];
extern sys_init_entry_t __sys_init_end[];
/* PRE_SYSTEM_INIT: level=0, sub=00-99 */
extern sys_init_entry_t __sys_init_0_start[];
extern sys_init_entry_t __sys_init_0_end[];
/* PRE_DEVICES_INIT: level=1, sub=00-99 */
extern sys_init_entry_t __sys_init_1_start[];
extern sys_init_entry_t __sys_init_1_end[];
/* PRE_KERNEL: level=2, sub=00-99 */
extern sys_init_entry_t __sys_init_2_start[];
extern sys_init_entry_t __sys_init_2_end[];
/* POST_KERNEL: level=3, sub=00-99 */
extern sys_init_entry_t __sys_init_3_start[];
extern sys_init_entry_t __sys_init_3_end[];
/* PRE_APPLICATION: level=4, sub=00-99 */
extern sys_init_entry_t __sys_init_4_start[];
extern sys_init_entry_t __sys_init_4_end[];
/* ========================================================================
* Internal Data Structures
* ======================================================================== */
/**
* @brief Level information structure
*/
typedef struct {
sys_init_entry_t *start; /* Section start address */
sys_init_entry_t *end; /* Section end address */
const char *name; /* Level name */
} level_info_t;
/**
* @brief Get level information - inline function to avoid global array
*
* IMPORTANT: This function is designed to work BEFORE scatload!
* - Uses only stack variables (no .data access)
* - No global array (avoids .data.rel.ro section)
* - Safe to call from PRE_SYSTEM_INIT context
*/
static inline void get_level_info(uint8_t level, level_info_t *info)
{
/* Switch statement compiles to constants - no .data access */
switch (level) {
case SYS_INIT_LEVEL_PRE_SYSTEM_INIT:
info->start = __sys_init_0_start;
info->end = __sys_init_0_end;
info->name = "PRE_SYSTEM_INIT";
break;
case SYS_INIT_LEVEL_PRE_DEVICES_INIT:
info->start = __sys_init_1_start;
info->end = __sys_init_1_end;
info->name = "PRE_DEVICES_INIT";
break;
case SYS_INIT_LEVEL_PRE_KERNEL:
info->start = __sys_init_2_start;
info->end = __sys_init_2_end;
info->name = "PRE_KERNEL";
break;
case SYS_INIT_LEVEL_POST_KERNEL:
info->start = __sys_init_3_start;
info->end = __sys_init_3_end;
info->name = "POST_KERNEL";
break;
case SYS_INIT_LEVEL_PRE_APPLICATION:
info->start = __sys_init_4_start;
info->end = __sys_init_4_end;
info->name = "PRE_APPLICATION";
break;
default:
info->start = NULL;
info->end = NULL;
info->name = NULL;
break;
}
}
/* ========================================================================
* Internal Helper Functions
* ======================================================================== */
/**
* @brief Get number of init entries at a level
*/
static inline size_t get_level_count(uint8_t level)
{
if (level >= LEVEL_TABLE_SIZE) {
return 0;
}
level_info_t info;
get_level_info(level, &info);
return (size_t)(info.end - info.start);
}
/* ========================================================================
* Public API Implementation
* ======================================================================== */
int sys_init_run_level(uint8_t level)
{
if (level >= LEVEL_TABLE_SIZE) {
return -1;
}
level_info_t info;
get_level_info(level, &info);
sys_init_entry_t *entry_start = info.start;
sys_init_entry_t *entry_end = info.end;
/* Calculate number of entries */
size_t count = entry_end - entry_start;
if (count == 0) {
return 0;
}
int success_count = 0;
int failed_count = 0;
/* Iterate and execute all init functions */
for (size_t i = 0; i < count; i++) {
sys_init_entry_t *entry = &entry_start[i];
if (entry->init_fn == NULL) {
continue;
}
/* Execute initialization function */
int ret = entry->init_fn();
if (ret == 0) {
success_count++;
} else {
failed_count++;
}
}
return success_count;
}
int sys_init_get_count(uint8_t level)
{
if (level == 0xFF) {
/* Count all levels */
int total = 0;
for (uint8_t i = 0; i < LEVEL_TABLE_SIZE; i++) {
total += (int)get_level_count(i);
}
return total;
}
if (level >= LEVEL_TABLE_SIZE) {
return -1;
}
return (int)get_level_count(level);
}
/* ========================================================================
* Debug Interface (Optional)
* ======================================================================== */
#ifdef CONFIG_SYS_INIT_DEBUG
/**
* @brief Dump all registered initialization functions
*/
void sys_init_dump_all(void)
{
printf("========================================");
printf(" Registered System Init Functions");
printf("========================================");
for (uint8_t level = 0; level < LEVEL_TABLE_SIZE; level++) {
level_info_t info;
get_level_info(level, &info);
size_t count = get_level_count(level);
printf("");
printf("[%s] - %d functions", info.name, (int)count);
if (count == 0) {
continue;
}
sys_init_entry_t *entry = info.start;
for (size_t i = 0; i < count; i++, entry++) {
printf(" [%d] %s",
entry->sub_priority,
entry->name ? entry->name : "unknown");
}
}
printf("");
printf("========================================");
}
#endif /* CONFIG_SYS_INIT_DEBUG */

View File

@@ -0,0 +1,194 @@
/*
* Copyright (c) 2025, LISTENAI
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @file sys_init.h
* @brief ARCS System Initialization Framework
*
* Provides a Zephyr SYS_INIT-like system initialization mechanism
* with multi-level priorities and sub-priorities support.
*/
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ========================================================================
* Initialization Priority Levels
* ========================================================================
*
* ARCS system initialization is divided into phases based on actual boot flow:
*
* Boot Flow:
* startup.S (_start) -> platform_pre_startup [PRE_SYSTEM_INIT] ->
* scatload -> SystemInit -> entry() -> lisa_device_init() ->
* vTaskStartScheduler() -> main_task -> main()
*
* Initialization Levels:
* - PRE_SYSTEM_INIT: BEFORE scatload (in platform_pre_startup)
* ⚠️ CRITICAL: .data NOT copied, .bss NOT zeroed!
* ⚠️ DO NOT USE GLOBAL VARIABLES!
* Interrupts disabled, no RTOS
* Use case: Critical hardware that must run before memory init
*
* - PRE_DEVICES_INIT: Before lisa_device_init(), in entry()
* Interrupts disabled, no RTOS, heap ready
* Use case: Preparation before device initialization
*
* - PRE_KERNEL: Before vTaskStartScheduler(), in entry()
* Interrupts enabled, no RTOS, all resources ready
* Use case: Final setup before kernel starts
*
* - POST_KERNEL: After vTaskStartScheduler(), in main_task
* RTOS fully running, can create tasks/semaphores
* Use case: Driver initialization requiring RTOS
*
* - PRE_APPLICATION: Before main(), in main_task
* RTOS fully running, last init before app
* Use case: Application-level initialization
*
* Within each level, sub-priority (0-99) provides fine-grained control
* ======================================================================== */
#define SYS_INIT_LEVEL_PRE_SYSTEM_INIT 0 /* BEFORE scatload ⚠️ NO GLOBALS! */
#define SYS_INIT_LEVEL_PRE_DEVICES_INIT 1 /* Before lisa_device_init() */
#define SYS_INIT_LEVEL_PRE_KERNEL 2 /* Before vTaskStartScheduler() */
#define SYS_INIT_LEVEL_POST_KERNEL 3 /* After vTaskStartScheduler() */
#define SYS_INIT_LEVEL_PRE_APPLICATION 4 /* Before main() */
#define SYS_INIT_LEVEL_MAX (SYS_INIT_LEVEL_PRE_APPLICATION + 1) /* Total number of levels */
/* Sub-priority range: 0-99 (lower value = higher priority) */
#define SYS_INIT_SUB_PRIORITY_MIN 0
#define SYS_INIT_SUB_PRIORITY_MAX 99
/* Common sub-priority constants */
#define SYS_INIT_SUB_PRIORITY_FIRST 0 /* Initialize first */
#define SYS_INIT_SUB_PRIORITY_EARLY 10 /* Early initialization */
#define SYS_INIT_SUB_PRIORITY_DEFAULT 50 /* Default priority */
#define SYS_INIT_SUB_PRIORITY_LATE 90 /* Late initialization */
#define SYS_INIT_SUB_PRIORITY_LAST 99 /* Initialize last */
/* ========================================================================
* Initialization Function Type Definition
* ======================================================================== */
/**
* @brief System initialization function type
* @return 0 on success, negative error code on failure
*/
typedef int (*sys_init_fn_t)(void);
/**
* @brief System initialization entry structure
*/
typedef struct {
sys_init_fn_t init_fn; /* Initialization function */
uint8_t level; /* Priority level (0-4) */
uint8_t sub_priority; /* Sub-priority (0-99) */
const char *name; /* Function name (for debugging) */
} sys_init_entry_t;
/* ========================================================================
* Section Attribute Definition
* ======================================================================== */
/**
* @brief Calculate section sorting value
*
* Format: level(1 digit) + sub_priority(2 digits, zero-padded)
* Example: level=1, sub=5 -> "105"
* level=2, sub=99 -> "299"
*/
#define _SYS_INIT_SECTION_NAME(level, sub_priority) \
".sys_init." #level #sub_priority
/* Section attribute macro */
#define _SYS_INIT_SECTION(level, sub_priority) \
__attribute__((used, section(_SYS_INIT_SECTION_NAME(level, sub_priority))))
/* ========================================================================
* System Initialization Registration Macro
* ========================================================================
*
* @brief Register a system initialization function
*
* @param _init_fn Initialization function, type: int (*)(void)
* @param _level Priority level (SYS_INIT_LEVEL_xxx)
* @param _sub_priority Sub-priority (0-99)
*
* @note Init function returns 0 on success, negative on failure
* @note Lower numeric value = higher priority (executes earlier)
* @note Sub-priority must be 0-99, compile error otherwise
*
* Usage example:
* @code
* static int my_early_init(void) {
* // Early initialization code
* return 0;
* }
*
* // Initialize before SystemInit, sub-priority 10
* SYS_INIT(my_early_init, SYS_INIT_LEVEL_PRE_SYSTEM_INIT, 10);
* @endcode
* ======================================================================== */
#define SYS_INIT(_init_fn, _level, _sub_priority) \
/* Compile-time check: level range */ \
_Static_assert((_level) >= SYS_INIT_LEVEL_PRE_SYSTEM_INIT && \
(_level) <= SYS_INIT_LEVEL_PRE_APPLICATION, \
"SYS_INIT level must be between 0-4"); \
/* Compile-time check: sub-priority range */ \
_Static_assert((_sub_priority) >= SYS_INIT_SUB_PRIORITY_MIN && \
(_sub_priority) <= SYS_INIT_SUB_PRIORITY_MAX, \
"SYS_INIT sub_priority must be between 0-99"); \
/* Generate unique variable name */ \
static const sys_init_entry_t \
__sys_init_entry_##_init_fn##_##_level##_##_sub_priority \
_SYS_INIT_SECTION(_level, _sub_priority) = { \
.init_fn = (_init_fn), \
.level = (_level), \
.sub_priority = (_sub_priority), \
.name = #_init_fn, \
}
/* ========================================================================
* System Initialization Management API
* ======================================================================== */
/**
* @brief Execute initialization functions at specified level
*
* Calls all init functions at the given level in priority order
*
* @param level Initialization level to execute (SYS_INIT_LEVEL_xxx)
* @return Number of successfully initialized functions, negative on error
*/
int sys_init_run_level(uint8_t level);
/**
* @brief Execute all initialization levels
*
* Executes all init functions in level and sub-priority order
*
* @return Total number of successfully initialized functions, negative on error
*/
int sys_init_run_all(void);
/**
* @brief Get system initialization statistics
*
* @param level Initialization level, pass 0xFF to get count for all levels
* @return Number of registered init functions at this level
*/
int sys_init_get_count(uint8_t level);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,14 @@
#if defined(__cplusplus)
extern "C" {
#endif
#if CONFIG_LINK_CPP_RUNTIME_SECTIONS
// 定义缺失的__dso_handle符号
void* __dso_handle = 0;
#endif //CONFIG_LINK_CPP_RUNTIME_SECTIONS
#if defined(__cplusplus)
}
#endif

View File

@@ -0,0 +1,47 @@
#ifndef __SYSEXEC_H__
#define __SYSEXEC_H__
#include <stdint.h>
struct exec_frame {
uint32_t zero;
uint32_t ra;
uint32_t sp;
uint32_t gp;
uint32_t tp;
uint32_t t0;
uint32_t t1;
uint32_t t2;
uint32_t fp;
uint32_t s1;
uint32_t a0;
uint32_t a1;
uint32_t a2;
uint32_t a3;
uint32_t a4;
uint32_t a5;
#ifndef __riscv_32e
uint32_t a6;
uint32_t a7;
uint32_t s2;
uint32_t s3;
uint32_t s4;
uint32_t s5;
uint32_t s6;
uint32_t s7;
uint32_t s8;
uint32_t s9;
uint32_t s10;
uint32_t s11;
uint32_t t3;
uint32_t t4;
uint32_t t5;
uint32_t t6;
#endif
uint32_t mcause;
uint32_t epc;
uint32_t msubm;
};
#endif

View File

@@ -0,0 +1,135 @@
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <sys/times.h>
#include <unistd.h>
#include <reent.h>
#include "core_feature_base.h"
/* Weak implementation attributes ensure these can be overridden */
/* by other implementations */
/* Base implementations of standard syscalls */
__attribute__((weak, used))
int _fstat(int file, struct stat *st) {
if ((STDOUT_FILENO == file) || (STDERR_FILENO == file)) {
st->st_mode = S_IFCHR;
return 0;
} else {
errno = EBADF;
return -1;
}
}
__attribute__((weak, used))
int _getpid(void) {
return 1;
}
__attribute__((weak, used))
int _gettimeofday(struct timeval *tp, void *tzp) {
extern volatile uint32_t SystemCoreClock; /* Defined in system.c */
if (tp != NULL) {
/* Get system tick counter and convert to seconds and microseconds */
uint64_t cycles = __get_rv_cycle();
tp->tv_sec = cycles / SystemCoreClock;
tp->tv_usec = (cycles % SystemCoreClock) * 1000000 / SystemCoreClock;
}
return 0;
}
__attribute__((weak, used))
int _isatty(int fd) {
if (fd >= 0 && fd <= 2) {
return 1;
}
errno = EBADF;
return 0;
}
__attribute__((weak, used))
int _kill(int pid, int sig) {
errno = EINVAL;
return -1;
}
__attribute__((weak, used))
int _stat(const char *file, struct stat *st) {
st->st_mode = S_IFCHR;
return 0;
}
__attribute__((weak, used))
int _lseek(int file, int ptr, int dir) {
return 0;
}
__attribute__((weak, used))
int _open(const char* name, int flags, int mode)
{
errno = ENOSYS;
return -1;
}
__attribute__((weak, used))
int _close(int file) {
return -1;
}
__attribute__((weak, used))
int _read(int file, char *ptr, int len) {
return 0;
}
__attribute__((weak, used))
_ssize_t _write(int file, char *ptr, size_t len) {
/* 实现基本的写函数,将数据写入到指定的文件描述符 */
/* 在这个简单实现中,我们假设写入总是成功的 */
return len;
}
/* Reentrant versions that call the base implementations */
__attribute__((weak, used))
int _fstat_r(struct _reent *r, int file, struct stat *st) {
return _fstat(file, st);
}
__attribute__((weak, used))
int _getpid_r(struct _reent *r) {
return _getpid();
}
__attribute__((weak, used))
int _gettimeofday_r(struct _reent *r, struct timeval *tp, void *tzp) {
return _gettimeofday(tp, tzp);
}
__attribute__((weak, used))
int _isatty_r(struct _reent *r, int fd) {
return _isatty(fd);
}
__attribute__((weak, used))
int _kill_r(struct _reent *r, int pid, int sig) {
return _kill(pid, sig);
}
__attribute__((weak, used))
int _stat_r(struct _reent *r, const char *file, struct stat *st) {
return _stat(file, st);
}
__attribute__((weak, used))
_ssize_t _write_r(struct _reent *r, int file, const void *ptr, size_t len) {
return _write(file, (char *)ptr, len);
}

View File

@@ -0,0 +1,342 @@
#include "stdint.h"
#include "log_print.h"
#include "tinyprintf.h"
#include <stdio.h>
#include <string.h>
#include "uart_reg.h"
#include "chip.h"
#include "ClockManager.h"
#include "IOMuxManager.h"
#if CONFIG_SYSLOG_UART_BACKEND
#include "lisa_device.h"
#include "lisa_uart.h"
#include "board.h"
lisa_device_t *uart_dev = NULL;
#endif
#if CONFIG_SYSLOG_UART_BACKEND
static UART_RegDef *uart = NULL;
void syslog_config_early(int dbg);
void syslog_poll_out_erayly(char data);
static uint32_t compute_gcd(uint32_t a, uint32_t c)
{
uint32_t t;
while (c != 0) {
t = a % c;
a = c;
c = t;
}
return a;
}
static int32_t __log_compute_div(int dbg, uint32_t baudrate, uint32_t *pm, uint32_t *pn, uint32_t div)
{
uint32_t gcd, m, n, tmp;
tmp = div * baudrate;
uint32_t uart_clk = 24000000;
gcd = compute_gcd(uart_clk, tmp);
m = uart_clk / gcd;
n = tmp / gcd;
if ((m > 1023) || (n > 511)) {
return -1;
}
*pm = m;
*pn = n;
return 0;
}
static int32_t log_compute_div(int dbg, uint32_t baudrate, uint32_t *pm, uint32_t *pn, uint32_t *pdiv)
{
int32_t ret = 0;
do {
if (__log_compute_div(dbg, baudrate, pm, pn, 4) == 0) {
*pdiv = 4;
break;
}
if (__log_compute_div(dbg, baudrate, pm, pn, 16) == 0) {
*pdiv = 16;
break;
}
ret = -1;
} while (0);
return ret;
}
int syslog_write(const char *data, int len)
{
static bool device_ready_status = false;
if (uart == NULL || data == NULL || len == 0) {
return 0;
}
// 如果设备还未ready,持续检测直到ready
if (!device_ready_status) {
if (uart_dev == NULL) {
#if defined(CONFIG_SYSLOG_UART_DEVICE_UART0)
uart_dev = lisa_device_get("uart0");
#elif defined(CONFIG_SYSLOG_UART_DEVICE_UART1)
uart_dev = lisa_device_get("uart1");
#elif defined(CONFIG_SYSLOG_UART_DEVICE_UART2)
uart_dev = lisa_device_get("uart2");
#endif
}
device_ready_status = lisa_device_ready(uart_dev);
// 设备刚ready时立即配置
if (device_ready_status) {
lisa_uart_config_t config = LISA_UART_CONFIG_DEFAULT();
config.baudrate = CONFIG_SYSLOG_UART_BAUDRATE;
lisa_uart_configure(uart_dev, &config);
}
}
if (device_ready_status) {
for (int i = 0; i < len; i++) {
lisa_uart_poll_out(uart_dev, data[i]);
}
} else {
for (int i = 0; i < len; i++) {
syslog_poll_out_erayly(data[i]);
}
}
return len;
}
int syslog_init_early(void)
{
int dbg = 0;
#if defined(CONFIG_SYSLOG_UART_DEVICE_UART0)
lisa_uart0_pinmux();
dbg = 0;
#elif defined(CONFIG_SYSLOG_UART_DEVICE_UART1)
lisa_uart1_pinmux();
dbg = 1;
#elif defined(CONFIG_SYSLOG_UART_DEVICE_UART2)
lisa_uart2_pinmux();
dbg = 2;
#endif
syslog_config_early(dbg);
return 0;
}
void syslog_poll_out_erayly(char data)
{
uart->REG_RXTX_BUFFER.all = data;
while (!uart->REG_STATUS.bit.TX_FIFO_SPACE)
;
}
void syslog_config_early(int dbg)
{
uint32_t m, n, div;
if (log_compute_div(dbg, CONFIG_SYSLOG_UART_BAUDRATE, &m, &n, &div) < 0) {
return;
}
switch (dbg) {
case 0:
uart = (UART_RegDef *)UART0_BASE;
__HAL_CRM_UART0_CLK_ENABLE();
HAL_CRM_SetUart0ClkDiv(n, m);
break;
case 1:
uart = (UART_RegDef *)UART1_BASE;
__HAL_CRM_UART1_CLK_ENABLE();
HAL_CRM_SetUart1ClkDiv(n, m);
break;
case 2:
uart = (UART_RegDef *)UART2_BASE;
__HAL_CRM_UART2_CLK_ENABLE();
HAL_CRM_SetUart2ClkDiv(n, m);
break;
default:
break;
}
uart->REG_IRQ_MASK.all = 0;
uart->REG_CTRL.all = 0;
if (div == 16) {
uart->REG_CTRL.bit.DIVISOR_MODE = 1; // 0: sclk/4; 1: sclk/16
} else {
uart->REG_CTRL.bit.DIVISOR_MODE = 0;
}
uart->REG_CMD_SET.bit.TX_FIFO_RESET = 1; // reset tx fifo
uart->REG_CMD_SET.bit.RX_FIFO_RESET = 1; // reset rx fifo
uart->REG_CTRL.bit.DATA_BITS = 1; // 8bits
uart->REG_CTRL.bit.ENABLE = 1; // enable uart
uart->REG_STATUS.all = 1; // clear line error bits
}
#else
int syslog_init_early(void){
return 0;
}
__attribute__((weak)) int syslog_write(const char *data, int len)
{
return 0;
}
#endif // CONFIG_SYSLOG_UART_BACKEND
void (*syslog_output_hook)(const char *, va_list) = NULL;
int syslog_hook_set(void (*hook)(const char *, va_list))
{
syslog_output_hook = hook;
return 0;
}
void syslog_output_default(const char *format, va_list args)
{
static char buffer[512] = {0};
uint32_t len = vsnprintf(buffer, 512 - 1, format, args);
buffer[len] = '\0';
syslog_write((const char *)buffer, len);
}
void syslog_raw_output_v(const char *format, va_list args)
{
if (syslog_output_hook) {
syslog_output_hook(format, args);
} else {
syslog_output_default(format, args);
}
}
int vprintk(const char *format, va_list args)
{
#if CONFIG_SYSLOG_PRINTK_REDIRECT
if (syslog_output_hook) {
syslog_output_hook(format, args);
} else {
syslog_output_default(format, args);
}
#else
syslog_output_default(format, args);
#endif
return 0;
}
int printk(const char *format, ...)
{
va_list args;
va_start(args, format);
vprintk(format, args);
va_end(args);
return 0;
}
void tfp_vprintf(const char *fmt, va_list ap)
{
if (syslog_output_hook) {
syslog_output_hook(fmt, ap);
} else {
syslog_output_default(fmt, ap);
}
}
void tfp_printf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
tfp_vprintf(fmt, args);
va_end(args);
}
#if CONFIG_SYSLOG_STDOUT
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
#define STDERR_FILENO 2
#endif
#if CONFIG_SYSLOG_PRINTF_REDIRECT
#define PRINTF_TEMP_BUF_CHUNK_SIZE 128
static void redirect_printf_output(const char *format, ...)
{
va_list dummy_args;
va_start(dummy_args, format);
syslog_raw_output_v(format, dummy_args);
va_end(dummy_args);
}
static void redirect_printf(void *buf, size_t cnt)
{
char temp_buf[PRINTF_TEMP_BUF_CHUNK_SIZE + 1]; // +1 for null terminator
char *input = (char *)buf;
size_t remaining = cnt;
size_t offset = 0;
va_list dummy_args;
memset(&dummy_args, 0, sizeof(dummy_args));
// 分批处理数据
while (remaining > 0) {
size_t chunk_len = (remaining > PRINTF_TEMP_BUF_CHUNK_SIZE) ? PRINTF_TEMP_BUF_CHUNK_SIZE : remaining;
memcpy(temp_buf, input + offset, chunk_len);
temp_buf[chunk_len] = '\0';
redirect_printf_output(temp_buf, dummy_args);
offset += chunk_len;
remaining -= chunk_len;
}
}
#endif
_ssize_t _write_r(struct _reent *ptr, int fd, void *buf, size_t cnt)
{
extern int _write(int file, char *data, int len);
if (!buf || cnt == 0) {
return 0;
}
switch (fd) {
case STDOUT_FILENO:
case STDERR_FILENO:
#if CONFIG_SYSLOG_PRINTF_REDIRECT
redirect_printf(buf, cnt);
#else
syslog_write(buf, cnt);
#endif
return cnt;
default:
return _write(fd, buf, cnt);
}
}
#endif
void __assert_func(const char *file, int line, const char *func, const char *expr)
{
CLOG_FLUSH();
CLOG("assert at file:%s:%d, expr:%s\r\n", file, line, expr);
__builtin_trap();
}

View File

@@ -0,0 +1,13 @@
#ifndef __SYSLOG_H__
#define __SYSLOG_H__
#include <stdarg.h>
#include <stdint.h>
int syslog_init_early(void);
int syslog_write(const char *data, int len);
int syslog_hook_set(void (*hook)(const char *, va_list));
void syslog_raw_output_v(const char *format, va_list args);
int printk(const char *format, ...);
#endif

View File

@@ -0,0 +1,167 @@
#include <stdio.h>
#include <stdint.h>
#include "arcs_ap.h"
#include "log_print.h"
#include "syslog.h"
#include "sdk_version.h"
#if CONFIG_SYS_INIT
#include "sys_init.h"
#endif
#if CONFIG_ARCS_AP_CORE
#include "rf_cali.h"
#endif
#if CONFIG_MODULE_FREERTOS
#include "FreeRTOS.h"
#include "task.h"
#include "memap.h"
#if !defined(CONFIG_MODULE_HEAP)
#error "CONFIG_MODULE_HEAP must be defined"
#endif
#include "sysheap.h"
#endif
#if CONFIG_MODULE_FREERTOS
void main_task(void *pvParameters)
{
/* PRE_APPLICATION initialization - before main() */
#if CONFIG_SYS_INIT
sys_init_run_level(SYS_INIT_LEVEL_PRE_APPLICATION); /* SYS_INIT_LEVEL_PRE_APPLICATION */
#endif
int main(int argc, char *argv[]);
main(0, NULL);
vTaskDelete(NULL);
}
#endif
#if CONFIG_SYSLOG_BANNER
__attribute__((weak)) void boot_banner(void)
{
printf("\n********Arcs SDK %s @ %s********\n", SDK_VERSION_STRING, BUILD_VERSION);
printf("Running on hart-id: %ld\n", (unsigned long)__get_hart_id());
}
#endif
#if CONFIG_LOG
__attribute__((weak)) int lisa_log_init(void)
{
printf("warning, lisa_log_init is not implemented\n");
return 0;
}
#endif
__always_inline static void cpp_init(void)
{
#if CONFIG_LINK_CPP_RUNTIME_SECTIONS
/* 调用C++全局构造函数 */
extern void atexit(void (*function)(void));
extern void __libc_init_array(void);
extern void __libc_fini_array(void);
/* 纯 C函数调用初始化C++全局构造函数 */
atexit(__libc_fini_array);
__libc_init_array();
#endif //CONFIG_LINK_CPP_RUNTIME_SECTIONS
#if CONFIG_CPP_EXCEPTIONS
struct object {
long placeholder[ 10 ];
};
void __register_frame_info(const void *begin, struct object * ob);
extern char __eh_frame[];
static struct object ob;
__register_frame_info(__eh_frame, &ob);
#endif // CONFIG_CPP_EXCEPTIONS
}
__attribute__((weak)) void abort(void)
{
assert(0);
}
__attribute__((weak, noreturn)) void entry(void)
{
syslog_init_early();
log_print_hook_set(syslog_raw_output_v);
#if CONFIG_WATCHDOG_ENABLE
boot_watchdog_init();
#elif CONFIG_BOOT_WITH_WATCHDOG
boot_watchdog_init();
boot_watchdog_enable(0);
#endif
#if CONFIG_SYSLOG_BANNER
boot_banner();
#endif
#if CONFIG_MODULE_FREERTOS
#if CONFIG_PSRAM_INIT
/* prepare PSRAM */
uint32_t rdly = 18, wdly = 22;
if (PSRAM_Initialize(&rdly, &wdly, 1) == 0) {
CLOGD("PSRAM initialize success");
}
HAL_InvalidateDCache_by_Addr((void *)MEM_PSRAM_BASE, MEM_PSRAM_SIZE);
#endif
scatload_psram();
sysheap_init();
#if CONFIG_LOG
lisa_log_init();
#endif
/* PRE_DEVICES_INIT initialization - before device init */
#if CONFIG_SYS_INIT
extern int sys_init_run_level(uint8_t level);
sys_init_run_level(SYS_INIT_LEVEL_PRE_DEVICES_INIT); /* SYS_INIT_LEVEL_PRE_DEVICES_INIT */
#endif
#if CONFIG_LISA_DEVICE
#if !CONFIG_LISA_DEVICE_MANUAL_INIT
lisa_device_init();
#endif
#endif
extern void pre_main_hook(void);
pre_main_hook();
/* PRE_KERNEL initialization - before scheduler starts */
#if CONFIG_SYS_INIT
sys_init_run_level(SYS_INIT_LEVEL_PRE_KERNEL); /* SYS_INIT_LEVEL_PRE_KERNEL */
#endif
cpp_init();
/* POST_KERNEL initialization - RTOS is now running */
#if CONFIG_SYS_INIT
sys_init_run_level(SYS_INIT_LEVEL_POST_KERNEL); /* SYS_INIT_LEVEL_POST_KERNEL */
#endif
xTaskCreate(main_task, "main", CONFIG_MAIN_TASK_STACK_SIZE, NULL, CONFIG_MAIN_TASK_PRIORITY, NULL);
vTaskStartScheduler();
/* POST_KERNEL initialization - RTOS is now running */
#if CONFIG_SYS_INIT
sys_init_run_level(SYS_INIT_LEVEL_POST_KERNEL); /* SYS_INIT_LEVEL_POST_KERNEL */
#endif
while(1) {
}
#else
int main(int argc, char *argv[]);
main(0, NULL);
while (1) {
}
#endif
}

View File

@@ -0,0 +1,773 @@
/*
* Copyright (c) 2019 Nuclei Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed 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
*
* 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.
*/
/******************************************************************************
* @file system_demosoc.c
* @brief NMSIS Nuclei Core Device Peripheral Access Layer Source File for
* Nuclei Demo SoC which support Nuclei N/NX class cores
* @version V1.00
* @date 22. Nov 2019
******************************************************************************/
#include <stdint.h>
#include <stdio.h>
#include "arcs_ap.h"
#include "cache.h"
#include "log_print.h"
#include "ClockManager.h"
#if CONFIG_SYS_INIT
#include "sys_init.h"
#endif
#include "sysexec.h"
#if CFG_MEMDUMP
#include "memdump.h"
#endif
enum {
NORMAL_MODE = 0,
INTERRUPT_MODE,
EXCE_MODE,
NMI_MODE,
};
/*----------------------------------------------------------------------------
Define clocks
*----------------------------------------------------------------------------*/
/* ToDo: add here your necessary defines for device initialization
following is an example for different system frequencies */
#ifndef SYSTEM_CLOCK
#define SYSTEM_CLOCK (24000000UL)
#endif
/**
* \defgroup NMSIS_Core_SystemConfig System Device Configuration
* \brief Functions for system and clock setup available in system_<device>.c.
* \details
* Nuclei provides a template file **system_Device.c** that must be adapted by
* the silicon vendor to match their actual device. As a <b>minimum requirement</b>,
* this file must provide:
* - A device-specific system configuration function, \ref SystemInit.
* - A global variable that contains the system frequency, \ref SystemCoreClock.
* - A global eclic configuration initialization, \ref ECLIC_Init.
* - Global c library \ref _init and \ref _fini functions called right before calling main function.
* - Vendor customized interrupt, exception and nmi handling code, see \ref NMSIS_Core_IntExcNMI_Handling
*
* The file configures the device and, typically, initializes the oscillator (PLL) that is part
* of the microcontroller device. This file might export other functions or variables that provide
* a more flexible configuration of the microcontroller system.
*
* And this file also provided common interrupt, exception and NMI exception handling framework template,
* Silicon vendor can customize these template code as they want.
*
* \note Please pay special attention to the static variable \c SystemCoreClock. This variable might be
* used throughout the whole system initialization and runtime to calculate frequency/time related values.
* Thus one must assure that the variable always reflects the actual system clock speed.
*
* \attention
* Be aware that a value stored to \c SystemCoreClock during low level initialization (i.e. \c SystemInit()) might get
* overwritten by C libray startup code and/or .bss section initialization.
* Thus its highly recommended to call \ref SystemCoreClockUpdate at the beginning of the user \c main() routine.
*
* @{
*/
/*----------------------------------------------------------------------------
System Core Clock Variable
*----------------------------------------------------------------------------*/
/* ToDo: initialize SystemCoreClock with the system core clock frequency value
achieved after system intitialization.
This means system core clock frequency after call to SystemInit() */
/**
* \brief Variable to hold the system core clock value
* \details
* Holds the system core clock, which is the system clock frequency supplied to the SysTick
* timer and the processor core clock. This variable can be used by debuggers to query the
* frequency of the debug timer or to configure the trace clock speed.
*
* \attention
* Compilers must be configured to avoid removing this variable in case the application
* program is not using it. Debugging systems require the variable to be physically
* present in memory so that it can be examined to configure the debugger.
*/
volatile uint32_t SystemCoreClock = SYSTEM_CLOCK; /* System Clock Frequency (Core Clock) */
volatile int HARTID = -1;
/*----------------------------------------------------------------------------
Clock functions
*----------------------------------------------------------------------------*/
/**
* \brief Function to update the variable \ref SystemCoreClock
* \details
* Updates the variable \ref SystemCoreClock and must be called whenever the core clock is changed
* during program execution. The function evaluates the clock register settings and calculates
* the current core clock.
*/
void SystemCoreClockUpdate(void) /* Get Core Clock Frequency */
{
/* ToDo: add code to calculate the system frequency based upon the current
* register settings.
* Note: This function can be used to retrieve the system core clock frequeny
* after user changed register settings.
*/
SystemCoreClock = CRM_GetSrcFreq(CRM_IpSrcCoreClk);//SYSTEM_CLOCK;
}
/**
* \defgroup NMSIS_Core_IntExcNMI_Handling Interrupt and Exception and NMI Handling
* \brief Functions for interrupt, exception and nmi handle available in system_<device>.c.
* \details
* Nuclei provide a template for interrupt, exception and NMI handling. Silicon Vendor could adapat according
* to their requirement. Silicon vendor could implement interface for different exception code and
* replace current implementation.
*
* @{
*/
/** \brief Max exception handler number, don't include the NMI(0xFFF) one */
#define MAX_SYSTEM_EXCEPTION_NUM 16
/**
* \brief Store the exception handlers for each exception ID
* \note
* - This SystemExceptionHandlers are used to store all the handlers for all
* the exception codes Nuclei N/NX core provided.
* - Exception code 0 - 11, totally 12 exceptions are mapped to SystemExceptionHandlers[0:11]
* - Exception for NMI is also re-routed to exception handling(exception code 0xFFF) in startup code configuration, the handler itself is mapped to SystemExceptionHandlers[MAX_SYSTEM_EXCEPTION_NUM]
*/
static unsigned long SystemExceptionHandlers[MAX_SYSTEM_EXCEPTION_NUM + 1];
/**
* \brief Exception Handler Function Typedef
* \note
* This typedef is only used internal in this system_<Device>.c file.
* It is used to do type conversion for registered exception handler before calling it.
*/
typedef void (*EXC_HANDLER)(unsigned long cause, unsigned long sp);
/**
* \brief System Default Exception Handler
* \details
* This function provides a default exception and NMI handler for all exception ids.
* By default, It will just print some information for debug, Vendor can customize it according to its requirements.
* \param [in] mcause code indicating the reason that caused the trap in machine mode
* \param [in] sp stack pointer
*/
static void system_default_exception_handler(unsigned long mcause, unsigned long sp)
{
unsigned long mstatus = __RV_CSR_READ(CSR_MSTATUS);
unsigned long mstratch = __RV_CSR_READ(CSR_MSCRATCH);
uint8_t trap_before = (CSR_MSUBM_Type){.d=__RV_CSR_READ(CSR_MSUBM)}.b.ptyp;
#if defined(CONFIG_LOG)
lisa_log_panic_mode_enable();
#endif
// 在异常处理期间,需要确保日志输出的及时性,禁用异步日志以避免数据丢失
#if defined(CONFIG_SDK_MODULE_EASYLOGGER) && defined(CONFIG_EASYLOGGER_LOG_MODE_ASYNC)
#include "elog.h"
elog_async_enabled(false); // 切换到同步模式确保异常信息不会丢失
#endif
// 关闭可能存在的后端,比如shell
/*由于AP核有核间日志代理,不能关闭日志后端*/
#if defined(CONFIG_LOG) && defined(CONFIG_ARCS_CP_CORE)
lisa_log_backend_resume(CONFIG_LOG_BACKEND_SYS_NAME);
#endif
__disable_irq();
CLOG_FLUSH();
printf("\n");
printf("*******************system exception******************\n");
/* TODO: Uncomment this if you have implement printf function */
printf("MCAUSE : 0x%08lx\n", (unsigned long)mcause);
printf("MDCAUSE: 0x%08lx\n", (unsigned long)__RV_CSR_READ(CSR_MDCAUSE));
printf("MEPC : 0x%08lx\n", (unsigned long)__RV_CSR_READ(CSR_MEPC));
printf("MTVAL : 0x%08lx\n", (unsigned long)__RV_CSR_READ(CSR_MTVAL));
printf("MSTATUS: 0x%08lx\n", (unsigned long)mstatus);
printf("HARTID : %lu\r\n", (unsigned long)(__RV_CSR_READ(CSR_MHARTID) & 0xFF));
printf("SP : %lx\r\n", (unsigned long)sp);
printf("MSTACK_CTL: 0x%08lx\r\n", (unsigned long)__RV_CSR_READ(mstack_ctl));
printf("MSTACK_BASE: 0x%08lx\r\n", (unsigned long)__RV_CSR_READ(mstack_base));
printf("MSTACK_bound: 0x%08lx\r\n", (unsigned long)__RV_CSR_READ(mstack_bound));
printf("\n");
if(trap_before == NMI_MODE || trap_before == EXCE_MODE){
printf("*** NESTED EXCEPTION DETECTED ***\r\n");
while(1);
}
Exception_DumpFrame(sp, PRV_M, mstatus, mstratch);
#if defined(SIMULATION_MODE)
// directly exit if in SIMULATION
extern void simulation_exit(int status);
simulation_exit(1);
#else
#if CFG_MEMDUMP
memdump_process(MDUMP_PATH_FLASH);
#else
volatile bool flag = true;
while (flag);
#endif
#endif
}
/**
* \brief Initialize all the default core exception handlers
* \details
* The core exception handler for each exception id will be initialized to \ref system_default_exception_handler.
* \note
* Called in \ref _init function, used to initialize default exception handlers for all exception IDs
* SystemExceptionHandlers contains NMI, but SystemExceptionHandlers_S not, because NMI can't be delegated to S-mode.
*/
static void Exception_Init(void)
{
for (int i = 0; i < MAX_SYSTEM_EXCEPTION_NUM; i++) {
SystemExceptionHandlers[i] = (unsigned long)system_default_exception_handler;
}
SystemExceptionHandlers[MAX_SYSTEM_EXCEPTION_NUM] = (unsigned long)system_default_exception_handler;
}
__attribute__((unused)) static void hex_dump_word(uint32_t *data, size_t cnt) {
for (size_t i = 0; i < cnt; i++, data++) {
if (i % 4 == 0) {
printf("\n");
}
printf("%08lx ", (unsigned long)*data);
}
printf("\n");
}
const char *reg_name[32] = {
"x0", "ra", "sp", "gp", "tp", "t0", "t1", "t2", "fp", "s1", "a0", "a1", "a2", "a3", "a4", "a5",
"a6", "a7", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "t3", "t4", "t5", "t6",
};
static void dump_reg(uint32_t *data, size_t cnt) {
if (cnt >= 32) {
cnt = 32;
}
for (size_t i = 0; i < cnt; i += 4) {
printf("%-4s: 0x%08lx\t", reg_name[i+0], (unsigned long)data[i+0]);
printf("%-4s: 0x%08lx\t", reg_name[i+1], (unsigned long)data[i+1]);
printf("%-4s: 0x%08lx\t", reg_name[i+2], (unsigned long)data[i+2]);
printf("%-4s: 0x%08lx\n", reg_name[i+3], (unsigned long)data[i+3]);
}
printf("\n");
}
static unsigned long user_exc_handler = 0;
void Exception_DumpFrame(unsigned long sp, uint8_t mode, unsigned long mstatus, unsigned long mstratch)
{
struct exec_frame *exc_frame = (struct exec_frame *)sp;
if (user_exc_handler) {
((void(*)(void))user_exc_handler)();
}
printf("**************general purpose registers**************\n");
dump_reg((uint32_t *)sp, 32);
if (PRV_M == mode) {
/* msubm is exclusive to machine mode */
printf("msubm: 0x%08lx\n", (unsigned long)exc_frame->msubm);
}
#if CONFIG_EXCEPTION_REBOOT_IMMEDIATELY
sys_platform_sw_full_reset();
#endif
#ifdef CFG_BACK_TRACE
extern void rv_backtrace_fault(uint32_t sp, struct exec_frame *frame, uint32_t mstatus, uint32_t mstratch);
rv_backtrace_fault(sp, exc_frame, mstatus, mstratch);
#endif
}
void Exception_User_Register_EXC(unsigned long exc_handler)
{
user_exc_handler = exc_handler;
return;
}
/**
* \brief Register an exception handler for exception code EXCn
* \details
* - For EXCn < \ref MAX_SYSTEM_EXCEPTION_NUM, it will be registered into SystemExceptionHandlers[EXCn-1].
* - For EXCn == NMI_EXCn, it will be registered into SystemExceptionHandlers[MAX_SYSTEM_EXCEPTION_NUM].
* \param [in] EXCn See \ref EXCn_Type
* \param [in] exc_handler The exception handler for this exception code EXCn
*/
void Exception_Register_EXC(uint32_t EXCn, unsigned long exc_handler)
{
if (EXCn < MAX_SYSTEM_EXCEPTION_NUM) {
SystemExceptionHandlers[EXCn] = exc_handler;
} else if (EXCn == NMI_EXCn) {
SystemExceptionHandlers[MAX_SYSTEM_EXCEPTION_NUM] = exc_handler;
}
}
/**
* \brief Get current exception handler for exception code EXCn
* \details
* - For EXCn < \ref MAX_SYSTEM_EXCEPTION_NUM, it will return SystemExceptionHandlers[EXCn-1].
* - For EXCn == NMI_EXCn, it will return SystemExceptionHandlers[MAX_SYSTEM_EXCEPTION_NUM].
* \param [in] EXCn See \ref EXCn_Type
* \return Current exception handler for exception code EXCn, if not found, return 0.
*/
unsigned long Exception_Get_EXC(uint32_t EXCn)
{
if (EXCn < MAX_SYSTEM_EXCEPTION_NUM) {
return SystemExceptionHandlers[EXCn];
} else if (EXCn == NMI_EXCn) {
return SystemExceptionHandlers[MAX_SYSTEM_EXCEPTION_NUM];
} else {
return 0;
}
}
/**
* \brief Common NMI and Exception handler entry
* \details
* This function provided a command entry for NMI and exception. Silicon Vendor could modify
* this template implementation according to requirement.
* \param [in] mcause code indicating the reason that caused the trap in machine mode
* \param [in] sp stack pointer
* \remarks
* - RISCV provided common entry for all types of exception. This is proposed code template
* for exception entry function, Silicon Vendor could modify the implementation.
* - For the core_exception_handler template, we provided exception register function \ref Exception_Register_EXC
* which can help developer to register your exception handler for specific exception number.
*/
uint32_t core_exception_handler(unsigned long mcause, unsigned long sp)
{
uint32_t EXCn = (uint32_t)(mcause & 0X00000fff);
EXC_HANDLER exc_handler;
if (EXCn < MAX_SYSTEM_EXCEPTION_NUM) {
exc_handler = (EXC_HANDLER)SystemExceptionHandlers[EXCn];
} else if (EXCn == NMI_EXCn) {
exc_handler = (EXC_HANDLER)SystemExceptionHandlers[MAX_SYSTEM_EXCEPTION_NUM];
} else {
exc_handler = (EXC_HANDLER)system_default_exception_handler;
}
if (exc_handler != NULL) {
exc_handler(mcause, sp);
}
return 0;
}
/** @} */ /* End of Doxygen Group NMSIS_Core_ExceptionAndNMI */
/**
* \brief initialize eclic config
* \details
* ECLIC needs be initialized after boot up,
* Vendor could also change the initialization
* configuration.
*/
void ECLIC_Init(void)
{
/* Global Configuration about MTH and NLBits.
* TODO: Please adapt it according to your system requirement.
* This function is called in _init function */
ECLIC_SetMth(0);
ECLIC_SetCfgNlbits(__ECLIC_INTCTLBITS);
}
/**
* \brief Initialize a specific IRQ and register the handler
* \details
* This function set vector mode, trigger mode and polarity, interrupt level and priority,
* assign handler for specific IRQn.
* \param [in] IRQn NMI interrupt handler address
* \param [in] shv \ref ECLIC_NON_VECTOR_INTERRUPT means non-vector mode, and \ref ECLIC_VECTOR_INTERRUPT is vector mode
* \param [in] trig_mode see \ref ECLIC_TRIGGER_Type
* \param [in] lvl interupt level
* \param [in] priority interrupt priority
* \param [in] handler interrupt handler, if NULL, handler will not be installed
* \return -1 means invalid input parameter. 0 means successful.
* \remarks
* - This function use to configure specific eclic interrupt and register its interrupt handler and enable its interrupt.
* - If the vector table is placed in read-only section(FLASHXIP mode), handler could not be installed
*/
int32_t ECLIC_Register_IRQ(IRQn_Type IRQn, uint8_t shv, ECLIC_TRIGGER_Type trig_mode, uint8_t lvl, uint8_t priority, void* handler)
{
if ((IRQn >= IRQ_MAX) || (shv > ECLIC_VECTOR_INTERRUPT) \
|| (trig_mode > ECLIC_NEGTIVE_EDGE_TRIGGER)) {
return -1;
}
/* set interrupt vector mode */
ECLIC_SetShvIRQ(IRQn, shv);
/* set interrupt trigger mode and polarity */
ECLIC_SetTrigIRQ(IRQn, trig_mode);
/* set interrupt level */
ECLIC_SetLevelIRQ(IRQn, lvl);
/* set interrupt priority */
ECLIC_SetPriorityIRQ(IRQn, priority);
if (handler != NULL) {
/* set interrupt handler entry to vector table */
ECLIC_SetVector(IRQn, (rv_csr_t)handler);
}
/* enable interrupt */
ECLIC_EnableIRQ(IRQn);
return 0;
}
/** @} */ /* End of Doxygen Group NMSIS_Core_ExceptionAndNMI */
#define FALLBACK_DEFAULT_ECLIC_BASE 0x0C000000UL
#define FALLBACK_DEFAULT_SYSTIMER_BASE 0x02000000UL
volatile IRegion_Info_Type SystemIRegionInfo;
static void _get_iregion_info(volatile IRegion_Info_Type *iregion)
{
unsigned long mcfg_info;
if (iregion == NULL) {
return;
}
mcfg_info = __RV_CSR_READ(CSR_MCFG_INFO);
if (mcfg_info & MCFG_INFO_IREGION_EXIST) { // IRegion Info present
iregion->iregion_base = (__RV_CSR_READ(CSR_MIRGB_INFO) >> 10) << 10;
iregion->eclic_base = iregion->iregion_base + IREGION_ECLIC_OFS;
iregion->systimer_base = iregion->iregion_base + IREGION_TIMER_OFS;
iregion->smp_base = iregion->iregion_base + IREGION_SMP_OFS;
iregion->idu_base = iregion->iregion_base + IREGION_IDU_OFS;
} else {
iregion->eclic_base = FALLBACK_DEFAULT_ECLIC_BASE;
iregion->systimer_base = FALLBACK_DEFAULT_SYSTIMER_BASE;
}
}
/**
* \brief do the init for trap(interrupt and exception) entry for supervisor mode
* \details
* This function provide initialization of CSR_STVT CSR_STVT2 and CSR_STVEC.
*/
static void Trap_Init(void)
{
}
/**
* \brief do the init for memory protection entry, total 16 entries.
* \details
* This function provide initialization physical memory protection.
*/
static void PMP_Init(void)
{
// [R]Read; [W]Write; [X]eXecute
// [L]Lock: 0: No lock; 1: Lock Until Next Reset
// > the L bit also indicates whether the R/W/X permissions are enforced on M-mode accesses
// [A]AddressMatching(NA4 or NAPOT added automatically, OFF and TOR not considered here):
// > 0-OFF: Null Region, means disabled
// > 1-TOR: Top Of Range, range from previous end address to configured address
// > 2-NA4: Naturally Aligned 4-bytes Region, always 4 bytes
// > 3-NAPOT: Naturally Aligned Power-Of-Two Regison, >= 8bytes
// also note that:
// 1. small index has higher priority
// 2. total 8 entries
// 3. base_addr should aligned to 2^order
const uint32_t hm = HARTID << 21;
pmp_config regions[8] = { // max items = __PMP_ENTRY_NUM / 2
{ .base_addr = 0x00080000|hm, .order = 14, .protection = PMP_L|PMP_R|PMP_W|PMP_X }, // +APILM:16KB
{ .base_addr = 0x00100000|hm, .order = 13, .protection = PMP_L|PMP_R|PMP_W }, // +APDLM:8KB
{ .base_addr = 0x200B0000, .order = 16, .protection = PMP_L|PMP_R|PMP_W|PMP_X }, // -SRAM:64KB
{ .base_addr = 0x200C0000, .order = 15, .protection = PMP_L|PMP_R|PMP_W|PMP_X }, // +SRAM:32KB for BT EM
{ .base_addr = 0x20000000, .order = 20, .protection = PMP_L|PMP_R|PMP_W|PMP_X }, // +SRAM:1MB
{ .base_addr = 0x28000000, .order = 24, .protection = PMP_L|PMP_R|PMP_W|PMP_X }, // +PSRAM:16MB
{ .base_addr = 0x30000000, .order = 25, .protection = PMP_L|PMP_R|PMP_W|PMP_X }, // +FLASH:32MB
{ .base_addr = 0x00000000, .order = 30, .protection = PMP_L }, // -MEM:1GB
};
for (int i = 0; i < sizeof(regions)/sizeof(regions[0]); i++) __set_PMPENTRYx(i, &regions[i]);
}
static void ClockInit(void)
{
extern void BootClock_Init();
#if CONFIG_CLOCK_INIT
BootClock_Init();
__FENCE_I();
#endif
SystemCoreClockUpdate();
__HAL_CRM_MTIME_CLK_ENABLE();
}
void platform_pre_startup(void)
{
/* ============================================================================
* WARNING: This runs BEFORE scatload!
* ============================================================================
*
* At this point:
* - Stack pointer (SP) is set
* - Global pointer (GP) is set
* - .data section is NOT copied (all initialized globals are WRONG!)
* - .bss section is NOT zeroed (all uninitialized globals are RANDOM!)
*
* DO NOT use global variables in PRE_SYSTEM_INIT level functions!
* Use only:
* - Local variables (on stack)
* - Constants (in .rodata)
* - Direct hardware register access
*
* ============================================================================ */
#if CONFIG_SYS_INIT
extern int sys_init_run_level(uint8_t level);
sys_init_run_level(0); /* SYS_INIT_LEVEL_PRE_SYSTEM_INIT */
#endif
}
/**
* \brief Function to Initialize the system.
* \details
* Initializes the microcontroller system. Typically, this function configures the
* oscillator (PLL) that is part of the microcontroller device. For systems
* with a variable clock speed, it updates the variable \ref SystemCoreClock.
* SystemInit is called from the file <b>startup<i>_device</i></b>.
*/
void SystemInit(void)
{
HARTID = __RV_CSR_READ(CSR_MHARTID) & 0xff;
/* ToDo: add code to initialize the system
* Warn: do not use global variables because this function is called before
* reaching pre-main. RW section maybe overwritten afterwards.
*/
SystemCoreClock = SYSTEM_CLOCK;
_get_iregion_info(&SystemIRegionInfo);
/* Vector Initialize */
extern void irq_vectors_init(void);
irq_vectors_init();
/* Clock Initialize */
ClockInit();
/* CACHE Initialize */
#if CONFIG_ICACHE_ENABLE
#if defined(__ICACHE_PRESENT) && (__ICACHE_PRESENT == 1)
if (ICachePresent())
HAL_EnableICache();
#endif
#else
HAL_DisableICache();
#endif
#if CONFIG_DCACHE_ENABLE
HAL_EnableDCache();
#else
HAL_DisableDCache();
#endif
non_cacheable_region_enable(WIFI_RAM_REGION, (CMN_PSRAM_REGION - WIFI_RAM_REGION));
/* PMP Initialize*/
#if defined(__PMP_PRESENT)
PMP_Init();
#endif
/* Initialize exception default handlers */
Exception_Init();
/* ECLIC initialization, mainly MTH and NLBIT */
ECLIC_Init();
/* TRAP Initialize */
Trap_Init();
}
////////////////////////////////////////////////////////////////////////////////
__attribute__((aligned (64))) void* OS_CPU_Vector_Table[IRQ_MAX] = { 0 };
void eclic_msip_handler(void) __attribute__((weak));
void eclic_mtip_handler(void) __attribute__((weak));
void irq_vectors_init(void)
{
OS_CPU_Vector_Table[SysTimerSW_IRQn] = &eclic_msip_handler;
OS_CPU_Vector_Table[SysTimer_IRQn] = &eclic_mtip_handler;
}
// Register ISR into Interrupt Vector Table
void register_ISR(uint32_t irq_no, ISR isr, ISR* isr_old)
{
if (irq_no >= IRQ_MAX) return;
ECLIC_SetShvIRQ(irq_no, ECLIC_NON_VECTOR_INTERRUPT);
/* set interrupt trigger mode */
ECLIC_SetTrigIRQ(irq_no, ECLIC_LEVEL_TRIGGER);
if (isr_old) *isr_old = (ISR)(OS_CPU_Vector_Table[irq_no]);
OS_CPU_Vector_Table[irq_no] = isr;
// default interrupt priority is 0, we assume that
// 0 indicates the interrupt has not been initialized before...
if (ECLIC_GetPriorityIRQ(irq_no) == 0){
/* set interrupt level */
ECLIC_SetLevelIRQ(irq_no, 0);
/* set interrupt priority */
ECLIC_SetPriorityIRQ(irq_no, 0);
}
}
void non_cacheable_region_enable(uint32_t base_addr, uint32_t len){
if (base_addr % len){
return;
}
uint32_t mnocm = ~(len - 1);
// Set cache region mask
__RV_CSR_WRITE(CSR_MNOCM, mnocm);
// Set base physical address and enable
__RV_CSR_WRITE(CSR_MNOCB, base_addr | 0x1);
}
void non_cacheable_region_disable(void){
// disable cache region
__RV_CSR_WRITE(CSR_MNOCB, 0x0);
}
void device_region_enable(uint32_t base_addr, uint32_t len)
{
if (base_addr % len) {
return;
}
uint32_t mnocm = ~(len - 1);
// Set dev region mask
__RV_CSR_WRITE(CSR_MDEVM, mnocm);
// Set base physical address and enable
__RV_CSR_WRITE(CSR_MDEVB, base_addr | 0x1);
}
void device_region_disable(void){
// disable device region
__RV_CSR_WRITE(CSR_MDEVB, 0x0);
}
extern void default_intexc_handler(void);
// Function template of all interrupt handlers
#define DEFINE_INTERRUPT_HANDLER(irq) \
void Interrupt##irq##_Handler(void) \
{ \
if (OS_CPU_Vector_Table[irq] != NULL) \
((ISR)(OS_CPU_Vector_Table[irq]))(); \
else \
default_intexc_handler(); \
}
// define interrupt handler functions
DEFINE_INTERRUPT_HANDLER(0);
DEFINE_INTERRUPT_HANDLER(1);
DEFINE_INTERRUPT_HANDLER(2);
DEFINE_INTERRUPT_HANDLER(3);
DEFINE_INTERRUPT_HANDLER(4);
DEFINE_INTERRUPT_HANDLER(5);
DEFINE_INTERRUPT_HANDLER(6);
DEFINE_INTERRUPT_HANDLER(7);
DEFINE_INTERRUPT_HANDLER(8);
DEFINE_INTERRUPT_HANDLER(9);
DEFINE_INTERRUPT_HANDLER(10);
DEFINE_INTERRUPT_HANDLER(11);
DEFINE_INTERRUPT_HANDLER(12);
DEFINE_INTERRUPT_HANDLER(13);
DEFINE_INTERRUPT_HANDLER(14);
DEFINE_INTERRUPT_HANDLER(15);
DEFINE_INTERRUPT_HANDLER(16);
DEFINE_INTERRUPT_HANDLER(17);
DEFINE_INTERRUPT_HANDLER(18);
DEFINE_INTERRUPT_HANDLER(19);
DEFINE_INTERRUPT_HANDLER(20);
DEFINE_INTERRUPT_HANDLER(21);
DEFINE_INTERRUPT_HANDLER(22);
DEFINE_INTERRUPT_HANDLER(23);
DEFINE_INTERRUPT_HANDLER(24);
DEFINE_INTERRUPT_HANDLER(25);
DEFINE_INTERRUPT_HANDLER(26);
DEFINE_INTERRUPT_HANDLER(27);
DEFINE_INTERRUPT_HANDLER(28);
DEFINE_INTERRUPT_HANDLER(29);
DEFINE_INTERRUPT_HANDLER(30);
DEFINE_INTERRUPT_HANDLER(31);
DEFINE_INTERRUPT_HANDLER(32);
DEFINE_INTERRUPT_HANDLER(33);
DEFINE_INTERRUPT_HANDLER(34);
DEFINE_INTERRUPT_HANDLER(35);
DEFINE_INTERRUPT_HANDLER(36);
DEFINE_INTERRUPT_HANDLER(37);
DEFINE_INTERRUPT_HANDLER(38);
DEFINE_INTERRUPT_HANDLER(39);
DEFINE_INTERRUPT_HANDLER(40);
DEFINE_INTERRUPT_HANDLER(41);
DEFINE_INTERRUPT_HANDLER(42);
DEFINE_INTERRUPT_HANDLER(43);
DEFINE_INTERRUPT_HANDLER(44);
DEFINE_INTERRUPT_HANDLER(45);
DEFINE_INTERRUPT_HANDLER(46);
DEFINE_INTERRUPT_HANDLER(47);
DEFINE_INTERRUPT_HANDLER(48);
DEFINE_INTERRUPT_HANDLER(49);
DEFINE_INTERRUPT_HANDLER(50);
DEFINE_INTERRUPT_HANDLER(51);
DEFINE_INTERRUPT_HANDLER(52);
DEFINE_INTERRUPT_HANDLER(53);
DEFINE_INTERRUPT_HANDLER(54);
DEFINE_INTERRUPT_HANDLER(55);
DEFINE_INTERRUPT_HANDLER(56);
DEFINE_INTERRUPT_HANDLER(57);
DEFINE_INTERRUPT_HANDLER(58);
DEFINE_INTERRUPT_HANDLER(59);
DEFINE_INTERRUPT_HANDLER(60);
DEFINE_INTERRUPT_HANDLER(61);
DEFINE_INTERRUPT_HANDLER(62);
DEFINE_INTERRUPT_HANDLER(63);
DEFINE_INTERRUPT_HANDLER(64);
DEFINE_INTERRUPT_HANDLER(65);
DEFINE_INTERRUPT_HANDLER(66);
DEFINE_INTERRUPT_HANDLER(67);
DEFINE_INTERRUPT_HANDLER(68);
DEFINE_INTERRUPT_HANDLER(69);
DEFINE_INTERRUPT_HANDLER(70);
DEFINE_INTERRUPT_HANDLER(71);
DEFINE_INTERRUPT_HANDLER(72);
DEFINE_INTERRUPT_HANDLER(73);
DEFINE_INTERRUPT_HANDLER(74);
DEFINE_INTERRUPT_HANDLER(75);
DEFINE_INTERRUPT_HANDLER(76);
DEFINE_INTERRUPT_HANDLER(77);
/** @} */ /* End of Doxygen Group NMSIS_Core_SystemAndClock */
#define REBOOT_PASS_PIN 0xCAFE000A
/* API for software reboot/full_reset */
void sys_platform_sw_full_reset(void)
{
IP_AON_CTRL->REG_AON_SW_RESET.all = REBOOT_PASS_PIN;
}

View File

@@ -0,0 +1,133 @@
/*
* Copyright (c) 2009-2018 Arm Limited. All rights reserved.
* Copyright (c) 2019 Nuclei Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed 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
*
* 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.
*/
/*******************************************************************************
* @file system_demosoc.h
* @brief NMSIS Nuclei N/NX Device Peripheral Access Layer Header File for
* Device <Device>
* @version V1.00
* @date 17. Dec 2019
******************************************************************************/
#ifndef __SYSTEM_DEMOSOC_H__ /* ToDo: replace '<Device>' with your device name */
#define __SYSTEM_DEMOSOC_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
extern volatile uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */
typedef struct EXC_Frame {
unsigned long ra; /* ra: x1, return address for jump */
unsigned long tp; /* tp: x4, thread pointer */
unsigned long t0; /* t0: x5, temporary register 0 */
unsigned long t1; /* t1: x6, temporary register 1 */
unsigned long t2; /* t2: x7, temporary register 2 */
unsigned long a0; /* a0: x10, return value or function argument 0 */
unsigned long a1; /* a1: x11, return value or function argument 1 */
unsigned long a2; /* a2: x12, function argument 2 */
unsigned long a3; /* a3: x13, function argument 3 */
unsigned long a4; /* a4: x14, function argument 4 */
unsigned long a5; /* a5: x15, function argument 5 */
unsigned long cause; /* cause: machine/supervisor mode cause csr register */
unsigned long epc; /* epc: machine/ supervisor mode exception program counter csr register */
unsigned long msubm; /* msubm: machine sub-mode csr register, nuclei customized, exclusive to machine mode */
#ifndef __riscv_32e
unsigned long a6; /* a6: x16, function argument 6 */
unsigned long a7; /* a7: x17, function argument 7 */
unsigned long t3; /* t3: x28, temporary register 3 */
unsigned long t4; /* t4: x29, temporary register 4 */
unsigned long t5; /* t5: x30, temporary register 5 */
unsigned long t6; /* t6: x31, temporary register 6 */
#endif
} EXC_Frame_Type;
void platform_pre_startup(void);
/**
* \brief Setup the microcontroller system.
* \details
* Initialize the System and update the SystemCoreClock variable.
*/
extern void SystemInit(void);
/**
* \brief Update SystemCoreClock variable.
* \details
* Updates the SystemCoreClock with current core Clock retrieved from cpu registers.
*/
extern void SystemCoreClockUpdate(void);
/**
* \brief Dump Exception Frame
*/
void Exception_DumpFrame(unsigned long sp, uint8_t mode, unsigned long mstatus, unsigned long mstratch);
/**
* \brief Register an exception handler for exception code EXCn
*/
extern void Exception_Register_EXC(uint32_t EXCn, unsigned long exc_handler);
/**
* \brief Get current exception handler for exception code EXCn
*/
extern unsigned long Exception_Get_EXC(uint32_t EXCn);
/**
* \brief Initialize eclic config
*/
extern void ECLIC_Init(void);
/**
* \brief Initialize a specific IRQ and register the handler
* \details
* This function set vector mode, trigger mode and polarity, interrupt level and priority,
* assign handler for specific IRQn.
*/
extern int32_t ECLIC_Register_IRQ(IRQn_Type IRQn, uint8_t shv, ECLIC_TRIGGER_Type trig_mode, uint8_t lvl, uint8_t priority, void* handler);
#if defined(__TEE_PRESENT) && (__TEE_PRESENT == 1)
/**
* \brief Register an exception handler for exception code EXCn of supervisor mode
*/
extern void Exception_Register_EXC_S(uint32_t EXCn, unsigned long exc_handler);
/**
* \brief Get current exception handler for exception code EXCn of supervisor mode
*/
extern unsigned long Exception_Get_EXC_S(uint32_t EXCn);
/**
* \brief Initialize a specific IRQ and register the handler of supervisor mode
* \details
* This function set vector mode, trigger mode and polarity, interrupt level and priority,
* assign handler for specific IRQn.
*/
extern int32_t ECLIC_Register_IRQ_S(IRQn_Type IRQn, uint8_t shv, ECLIC_TRIGGER_Type trig_mode, uint8_t lvl, uint8_t priority, void* handler);
#endif
#ifdef __cplusplus
}
#endif
#endif /* __SYSTEM_DEMOSOC_H__ */

View File

@@ -0,0 +1,655 @@
/*
* Copyright (c) 2019 Nuclei Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed 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
*
* 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.
*/
/******************************************************************************
* @file gcc_evalsoc_ilm.ld
* @brief GNU Linker Script for Nuclei N/NX based device
* @version V1.0.0
* @date 17. Dec 2019
******************************************************************************/
OUTPUT_ARCH("riscv")
ENTRY(_start)
////////////////////////////////////////////////////////////////////////////////
/*
* R - Read-only sections.
* W - Read/write sections.
* X - Sections containing executable code.
* A - Allocated sections.
* I/L - Initialized sections.
* ! - Invert the sense of any of the following attributes.
*/
#include "memap.h"
MEMORY {
PSRAM(rwxa ) : ORIGIN = MEM_PSRAM_BASE, LENGTH = MEM_PSRAM_SIZE
FLASH(rxa!w) : ORIGIN = MEM_FLASH_BASE, LENGTH = MEM_FLASH_SIZE
SRAM(rwxa ) : ORIGIN = MEM_SRAM_BASE, LENGTH = MEM_SRAM_SIZE
ILM(rwx ) : ORIGIN = MEM_ILM_BASE, LENGTH = MEM_ILM_SIZE
DLM(rw ) : ORIGIN = MEM_DLM_BASE, LENGTH = MEM_DLM_SIZE
BTRAM(rwxa ) : ORIGIN = MEM_BTRAM_BASE, LENGTH = MEM_BTRAM_SIZE
LUNA_RAM(rwxa) : ORIGIN = MEM_LUNA_BASE, LENGTH = MEM_LUNA_SIZE
#if defined(MEM_FLASH_EX_BASE)
FLASH_EX(rxa!w) : ORIGIN = MEM_FLASH_EX_BASE, LENGTH = MEM_FLASH_EX_SIZE
#endif
#if defined(MEM_IPC_BASE)
/* 共享内存 */
IPC_RAM(rwx) : ORIGIN = MEM_IPC_BASE, LENGTH = MEM_IPC_SIZE
#endif
#if defined(MEM_WFRAM_BASE)
/* 这段内存预留给WIFI使用 */
WIFI_RAM (rwx) : ORIGIN = MEM_WFRAM_BASE, LENGTH = MEM_WFRAM_SIZE
#endif
}
REGION_ALIAS("ITCM", ILM)
REGION_ALIAS("DTCM", DLM)
REGION_ALIAS("ROM", FLASH)
REGION_ALIAS("RAM", SRAM)
REGION_ALIAS("LUNA", LUNA_RAM)
REGION_ALIAS("RAM_BT", BTRAM)
#if defined(MEM_FLASH_EX_BASE)
REGION_ALIAS("ROM_EX", FLASH_EX)
#endif
/* 如果不定义 MEM_WFRAM_BASE 的话, wifi ram从sram中分配 */
#if !defined(MEM_WFRAM_BASE)
REGION_ALIAS("WIFI_RAM", SRAM)
#endif
/* 如果不定义 MEM_IPC_BASE 的话, ipc shared ram从sram中分配 */
#if !defined(MEM_IPC_BASE)
REGION_ALIAS("IPC_RAM", SRAM)
#endif
#define SCATCOPY(LEN,VMA,LMA) LONG(LEN) LONG(VMA) LONG(LMA)
#define SCATLOAD(SCT) LONG(SIZEOF(SCT)) LONG(ADDR(SCT)) LONG(LOADADDR(SCT))
#define SCATZERO(SCT) LONG(SIZEOF(SCT)) LONG(ADDR(SCT))
SECTIONS {
PROVIDE(__STACK_SIZE = MEM_INTERRUPT_STACK_SIZE);
PROVIDE(__HEAP_SIZE = 512);
PROVIDE(__BT_HEAP_SIZE = 24K);
/* wifi 校准数据预留大小 */
PROVIDE(_lcali = MEM_WIFI_CALIBRATION_SIZE);
/* wifi 跟踪数据预留大小 */
PROVIDE(_trace_len = MEM_WIFI_TRACE_SIZE);
PROVIDE(psram_start = ORIGIN(PSRAM));
PROVIDE(psram_end = ORIGIN(PSRAM) + LENGTH(PSRAM));
/* 优先将这个段放在前面, 确保wifi ram自动从sram分配时, 前面的地址给wifi使用 */
.wifi.noinit (NOLOAD):
{
. = ALIGN(4);
_wifi_ram_start = . ;
*(WIFI_CALI)
#if CONFIG_WIFI_CALI_BUF
_scali = .;
. += _lcali;
_ecali = .;
#endif
_trace_start = .;
. += _trace_len;
_trace_end = .;
_sshram = . ;
*(SHAREDRAMIPC)
*(IPC_WIFI_SHARE)
*(SHAREDRAM)
_eshram = . ;
. = ALIGN(4);
_wifi_ram_end = . ;
} > WIFI_RAM
/* WIFI外设只能访问 0x20000000 - 0x20000000 + 256 * 1024这段内存 */
ASSERT ((_wifi_ram_start >= (0x20000000)), "error: wifi ram start must be greater than 0x20000000")
ASSERT ((_wifi_ram_end <= (0x20000000 + 256 * 1024)), "error: wifi ram end must be less than 0x20000000 + 256 * 1024")
.init : {
/* Default Vector Table */
. = ALIGN(4);
PROVIDE(_rom_code_start = .);
* (.vtable)
/* Starup Initialition Region */
. = ALIGN(4);
KEEP(startup.* (SORT_NONE(.init)))
KEEP(scatload.* (SORT(.init)))
PROVIDE(_rom_code_end = .);
} >ROM AT>ROM
.scatab : ALIGN(4) {
/* Prev Scatter Copy/Load Table */
. = ALIGN(4);
PROVIDE(__scat_copy_base = .);
SCATLOAD(.itcm);
SCATLOAD(.dtcm);
SCATLOAD(.fast.text);
SCATLOAD(.fast.rodata);
SCATLOAD(.fast.data);
SCATLOAD(.text);
SCATLOAD(.rodata);
SCATLOAD(.data);
SCATLOAD(.shell);
SCATLOAD(.mapi);
SCATLOAD(.luna.text);
SCATLOAD(.luna.data);
PROVIDE(__scat_copy_last = .);
/* Scatter Zero-Fill Table */
. = ALIGN(4);
PROVIDE(__scat_zero_base = .);
SCATZERO(.dtcm.bss);
SCATZERO(.fast.bss);
SCATZERO(.bss);
SCATZERO(.luna.bss);
PROVIDE(__scat_zero_last = .);
. = ALIGN(4);
} >ROM AT>ROM
.psram_scatab : ALIGN(4) {
/* Prev Scatter Copy/Load Table */
. = ALIGN(4);
PROVIDE(__psram_scat_copy_base = .);
SCATLOAD(.psram.text);
SCATLOAD(.psram.data);
SCATLOAD(.psram.rodata);
PROVIDE(__psram_scat_copy_last = .);
/* Scatter Zero-Fill Table */
. = ALIGN(4);
PROVIDE(__psram_scat_zero_base = .);
SCATZERO(.psram.bss);
PROVIDE(__psram_scat_zero_last = .);
. = ALIGN(4);
} >ROM AT>ROM
.psram.data : ALIGN(4) {
. = ALIGN(4);
PROVIDE(__psram_data_start = .);
* (.psram.data)
* (.psram.data.*)
*psram*.a: (.data .data.*)
. = ALIGN(4);
PROVIDE(__psram_data_end = .);
} >PSRAM AT>ROM
.psram.bss(NOLOAD): ALIGN(4) {
. = ALIGN(4);
PROVIDE(__psram_bss_start = .);
* (.psram.bss)
* (.psram.bss.*)
*psram*.a: (.sbss .sbss.* .bss .bss.*)
. = ALIGN(4);
PROVIDE(__psram_bss_end = .);
} >PSRAM
.psram.noinit(NOLOAD) : ALIGN(4) {
. = ALIGN(4);
PROVIDE(__psram_noinit_start = .);
* (.psram.noinit)
* (.psram.noinit.*)
*psram*.a: (.noinit .noinit.*)
. = ALIGN(4);
PROVIDE(__psram_noinit_end = .);
} >PSRAM
#if CONFIG_WIFI
.wifi_la_dump (NOLOAD) : {
_slaram = .;
. += CONFIG_MEM_WIFI_LA_DUMP_SIZE;
_elaram = .;
} > PSRAM
#endif
.luna.text : ALIGN(8) {
. = ALIGN(8);
*(.sharedmem.text)
} >LUNA AT>ROM
.luna.data : ALIGN(8) {
. = ALIGN(8);
*(.sharedmem.data)
} >LUNA AT>ROM
.luna.bss(NOLOAD) : ALIGN(8) {
. = ALIGN(8);
*(.sharedmem.bss)
} >LUNA
////////////////////////////////////////////////////////////////////////////
// ROM/RAM => FAST/RAM
.fast.text : ALIGN(4) {
. = ALIGN(4);
PROVIDE(_ram_code_start = .);
* (.ramcode)
* (.text.irq .text.xPortTaskSwitch .text.eclic_mtip_handler)
* (.fast_text .fast_text.*)
* (.pm.ramcode)
/* *heap.a: (.text .text.*) */
*mapi.o (.text .text.*)
PROVIDE(_ram_code_end = .);
. = ALIGN(4);
} >SRAM AT>ROM
.itcm : ALIGN(4) {
. = ALIGN(4);
PROVIDE(_itcm_code_start = .);
* (.itcm_text .itcm_text.* .itcm*)
* (._wf_critical ._wf_critical.*)
*(.text.pm)
PROVIDE(_itcm_code_end = .);
. = ALIGN(4);
} >ITCM AT>ROM
.dtcm : ALIGN(4) {
. = ALIGN(4);
* (.dtcm .dtcm.*)
. = ALIGN(4);
} >DTCM AT>ROM
.dtcm.bss (NOLOAD) : ALIGN(4) {
. = ALIGN(4);
* (.dtcm.bss .dtcm.bss*)
. = ALIGN(4);
} >DTCM
.fast.rodata : ALIGN(4) {
. = ALIGN(4);
* (.fast_rodata .fast_rodata.*)
. = ALIGN(4);
} >RAM AT>ROM
.fast.data : ALIGN(4) {
. = ALIGN(4);
* (.fast_data .fast_data.*)
. = ALIGN(4);
} >RAM AT>ROM
.fast.bss(NOLOAD) : ALIGN(4) {
. = ALIGN(4);
* (.fast_bss .fast_bss.*)
. = ALIGN(4);
} >RAM AT>RAM
////////////////////////////////////////////////////////////////////////////
// ROM => ROM
.shell : ALIGN(4) {
. = ALIGN(4);
_shell_items_start = .;
KEEP(* (.shell.user))
KEEP(* (.shell.priv))
. = ALIGN(4);
} >ROM AT>ROM
.shell_command :
{
_shell_command_start = .;
KEEP (*(shellCommand))
_shell_command_end = .;
} >ROM AT>ROM
.psram.text : ALIGN(4) {
. = ALIGN(4);
PROVIDE(__psram_text_start = .);
* (.psram.text)
* (.psram.text.*)
*libmodules_lvgl.a:*(.text .text.* .stext .stext.*)
. = ALIGN(4);
PROVIDE(__psram_text_end = .);
} >PSRAM AT>ROM
.text : ALIGN(4) {
. = ALIGN(4);
PROVIDE(_rom_code2_start = .);
* (.stext .stext.*)
* (.text .text.*)
* (.gnu.linkonce.t.*)
. = ALIGN(4);
PROVIDE(_rom_code2_end = .);
} >ROM AT>ROM
#if CONFIG_LINK_CPP_RUNTIME_SECTIONS
.fini :
{
KEEP (*(SORT_NONE(.fini)))
} >ROM AT>ROM
.preinit_array :
{
PROVIDE_HIDDEN (__preinit_array_start = .);
KEEP (*(.preinit_array))
PROVIDE_HIDDEN (__preinit_array_end = .);
} >ROM AT>ROM
.init_array :
{
PROVIDE_HIDDEN (__init_array_start = .);
KEEP (*(SORT_BY_INIT_PRIORITY(.init_array.*) SORT_BY_INIT_PRIORITY(.ctors.*)))
KEEP (*(.init_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .ctors))
PROVIDE_HIDDEN (__init_array_end = .);
} >ROM AT>ROM
.fini_array :
{
PROVIDE_HIDDEN (__fini_array_start = .);
KEEP (*(SORT_BY_INIT_PRIORITY(.fini_array.*) SORT_BY_INIT_PRIORITY(.dtors.*)))
KEEP (*(.fini_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .dtors))
PROVIDE_HIDDEN (__fini_array_end = .);
} >ROM AT>ROM
.ctors :
{
/* gcc uses crtbegin.o to find the start of
* the constructors, so we make sure it is
* first. Because this is a wildcard, it
* doesn't matter if the user does not
* actually link against crtbegin.o; the
* linker won't look for a file to match a
* wildcard. The wildcard also means that it
* doesn't matter which directory crtbegin.o
* is in.
*/
KEEP (*crtbegin.o(.ctors))
KEEP (*crtbegin?.o(.ctors))
/* We don't want to include the .ctor section from
* the crtend.o file until after the sorted ctors.
* The .ctor section from the crtend file contains the
* end of ctors marker and it must be last
*/
KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .ctors))
KEEP (*(SORT(.ctors.*)))
KEEP (*(.ctors))
} >ROM AT>ROM
.dtors :
{
KEEP (*crtbegin.o(.dtors))
KEEP (*crtbegin?.o(.dtors))
KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .dtors))
KEEP (*(SORT(.dtors.*)))
KEEP (*(.dtors))
} >ROM AT>ROM
/* C++ 异常处理支持 */
.eh_frame_hdr :
{
*(.eh_frame_hdr)
*(.eh_frame_entry .eh_frame_entry.*)
} >ROM AT>ROM
.eh_frame :
{
. = ALIGN(4);
PROVIDE(__eh_frame = .);
KEEP(*(.eh_frame))
/**
* As we are not linking with crtend.o, which includes the CIE terminator
* (see __FRAME_END__ in libgcc sources), it is manually provided here.
*/
LONG(0)
} >ROM AT>ROM
.gcc_except_table :
{
*(.gcc_except_table .gcc_except_table.*)
} >ROM AT>ROM
/* C++ 标准库静态数据 */
.rodata.cst4 :
{
*(.rodata.cst4)
} >ROM AT>ROM
.rodata.cst8 :
{
*(.rodata.cst8)
} >ROM AT>ROM
#endif // CONFIG_LINK_OPTION_NONE_SPECS
#if defined(MEM_FLASH_EX_BASE)
.extflash : {
. = ALIGN(4);
__ext_data_start = .;
KEEP (*(.extflash.*))
. = ALIGN(4);
__ext_data_end = .;
} >ROM_EX AT>ROM_EX
#endif
.psram.rodata : ALIGN(4) {
. = ALIGN(4);
* (.psram.rodata)
* (.psram.rodata.*)
. = ALIGN(4);
} >PSRAM AT>ROM
.rodata : ALIGN(4) {
. = ALIGN(4);
* (EXCLUDE_FILE(*spiflash.c.obj) .rodata)
* (EXCLUDE_FILE(*arcs_flash.c.obj) .rodata .rodata.*)
* (.rodata .rodata.*)
* (.strdat)
. = ALIGN(4);
} >ROM AT>ROM
.lisaui_apps : {
. = ALIGN(4);
__lisaui_apps_start = .;
KEEP (*(.lisaui*))
. = ALIGN(4);
__lisaui_apps_end = .;
} >ROM AT>ROM
/* MCP工具静态注册段 */
.mcp_tool : {
. = ALIGN(4);
__mcp_tool_start = .;
KEEP (*(.mcp_tool))
. = ALIGN(4);
__mcp_tool_end = .;
} >ROM AT>ROM
/* LISA Device 设备注册段 */
.lisa_device_registry : {
. = ALIGN(4);
__lisa_device_registry_start = .;
KEEP (*(.lisa_device_registry))
KEEP (*(SORT(.lisa_device_registry.*)))
. = ALIGN(4);
__lisa_device_registry_end = .;
} >ROM AT>ROM
/* System Init 系统初始化段
* Use two-step sorting to handle sub_priority 0-99 correctly:
* Step 1: Process 0-9 (single digit)
* Step 2: Process 10-99 (double digit)
* This ensures correct numeric order despite lexicographic sorting */
.sys_init : {
. = ALIGN(4);
__sys_init_start = .;
/* PRE_SYSTEM_INIT: level=0, sub_priority=0-99
* BEFORE scatload - NO GLOBAL VARIABLES! */
__sys_init_0_start = .;
KEEP (*(SORT(.sys_init.0[0-9]))) /* sub_priority 0-9 */
KEEP (*(SORT(.sys_init.0[1-9][0-9]))) /* sub_priority 10-99 */
__sys_init_0_end = .;
/* PRE_DEVICES_INIT: level=1, sub_priority=0-99
* Before lisa_device_init() */
__sys_init_1_start = .;
KEEP (*(SORT(.sys_init.1[0-9]))) /* sub_priority 0-9 */
KEEP (*(SORT(.sys_init.1[1-9][0-9]))) /* sub_priority 10-99 */
__sys_init_1_end = .;
/* PRE_KERNEL: level=2, sub_priority=0-99
* Before vTaskStartScheduler() */
__sys_init_2_start = .;
KEEP (*(SORT(.sys_init.2[0-9]))) /* sub_priority 0-9 */
KEEP (*(SORT(.sys_init.2[1-9][0-9]))) /* sub_priority 10-99 */
__sys_init_2_end = .;
/* POST_KERNEL: level=3, sub_priority=0-99
* After vTaskStartScheduler() */
__sys_init_3_start = .;
KEEP (*(SORT(.sys_init.3[0-9]))) /* sub_priority 0-9 */
KEEP (*(SORT(.sys_init.3[1-9][0-9]))) /* sub_priority 10-99 */
__sys_init_3_end = .;
/* PRE_APPLICATION: level=4, sub_priority=0-99
* Before main() */
__sys_init_4_start = .;
KEEP (*(SORT(.sys_init.4[0-9]))) /* sub_priority 0-9 */
KEEP (*(SORT(.sys_init.4[1-9][0-9]))) /* sub_priority 10-99 */
__sys_init_4_end = .;
. = ALIGN(4);
__sys_init_end = .;
} >ROM AT>ROM
////////////////////////////////////////////////////////////////////////////
// ROM => RAM
.mapi : ALIGN(4) {
. = ALIGN(4);
PROVIDE_HIDDEN(__mod_stdc = .);
KEEP(* (SORT(.mod.0.*)))
PROVIDE_HIDDEN(__mod_rtos = .);
KEEP(* (SORT(.mod.?.*)))
PROVIDE_HIDDEN(__mod_ends = .);
. = ALIGN(4);
} >RAM AT>ROM
.trace : ALIGN(4) {
. = ALIGN(4);
_trace_start = .;
KEEP(*(TRACE))
_trace_end = .;
. = ALIGN(4);
} >RAM AT>ROM
.data : ALIGN(8) {
. = ALIGN(8);
* (.data .data.*)
* (.gnu.linkonce.d.*)
. = ALIGN(8);
PROVIDE(__global_pointer$ = . + 0x800);
* (.sdata .sdata.*)
* (.gnu.linkonce.s.*)
. = ALIGN(8);
* (.rdata .rdata.*)
*spiflash.c.obj(.rodata .rodata.*)
*arcs_flash.c.obj(.rodata .rodata.*)
* (.gnu.linkonce.r.*)
* (.srodata .srodata.*)
} >RAM AT>ROM
#if defined(MEM_IPC_BASE)
/* ipc shared RAM */
.ipc.shared (NOLOAD):
{
_ipcshram = . ;
*(SHAREDRAM_AMP_IPC_ENV)
*(SHAREDRAM_AMP_IPC)
KEEP(*(SORT(.ipc.*)))
_eipcshram = . ;
*(.ic_lock_shared_mem)
} > IPC_RAM
#endif
PROVIDE(__tls_base = .);
.psram.nocache_heap ORIGIN(PSRAM) (NOLOAD):{
. = ALIGN(0x100000);
PROVIDE(__psram_nocache_heap_start = .);
* (.psram.nocache_heap)
. = ALIGN(4);
PROVIDE(__psram_nocache_heap_end = .);
} >PSRAM
////////////////////////////////////////////////////////////////////////////
// ZERO => RAM
.bss(NOLOAD) : ALIGN(8) {
. = ALIGN(8);
* (.sbss .sbss.*)
* (.gnu.linkonce.sb.*)
* (.bss .bss.*)
* (.gnu.linkonce.b.*)
* (COMMON)
. = ALIGN(4);
} >RAM AT>RAM
.noinit (NOLOAD): ALIGN(4) {
. = ALIGN(4);
* (.noinit)
* (.noinit.*)
. = ALIGN(4);
} >RAM
////////////////////////////////////////////////////////////////////////////
// ROM => ROM
.stub : {
KEEP (* (.stub))
} >ROM AT>ROM
PROVIDE( _end = . );
PROVIDE( end = . );
////////////////////////////////////////////////////////////////////////////
///* RTOS Heap Region (8 bytes aligned at least) */
//.rtosheap(NOLOAD) : ALIGN(16) {
// . = ALIGN(ORIGIN(RAM) + LENGTH(RAM) - __HEAP_SIZE - __STACK_SIZE, 16);
//} >RAM AT>RAM
//PROVIDE(__vmaof_osheap = ADDR(.rtosheap));
//PROVIDE(__lenof_osheap = SIZEOF(.rtosheap));
/* Nuclei C Runtime Library requirements:
* 1. heap need to be align at 16 bytes
* 2. __heap_start and __heap_end symbol need to be defined
* 3. reserved at least __HEAP_SIZE space for heap
* 4. reserved at least __STACK_SIZE space for stack */
.heapstack(NOLOAD) : ALIGN(16) {
. = ALIGN(16);
PROVIDE(__heap_start = .);
. += __HEAP_SIZE;
. = ALIGN(16);
PROVIDE(__heap_end = .);
PROVIDE(_sstack = .);
PROVIDE(__StackLimit = .);
. += __STACK_SIZE;
. = ALIGN(16);
PROVIDE(__StackTop = .);
PROVIDE(_estack = .);
} >RAM AT>RAM
#if CONFIG_BLE
/* BT Heap in PSRAM */
.bt_heap (NOLOAD): ALIGN(16) {
. = ALIGN(16);
PROVIDE( __ext_ram_start = . );
. = . + __BT_HEAP_SIZE;
PROVIDE( __ext_ram_end = . );
} >PSRAM
#endif
}

View File

@@ -0,0 +1,72 @@
#include "ClockManager.h"
#include "systick.h"
static _systick_info systick_info = {
.interval = 0,
.systick_value = 0,
};
__attribute__((weak)) void SysTick_Handler(void){
systick_info.systick_value++;
}
__attribute__((weak)) void SysTick_Open(uint64_t interval){
systick_info.systick_value = 0;
systick_info.interval = interval;
register_ISR(7, SysTick_Handler,NULL);
SysTick_Config(interval);
SysTimer_Start();
}
__attribute__((weak)) void SysTick_Close(void){
SysTimer_Stop();
}
__attribute__((weak)) uint32_t SysTick_Time(void){
uint32_t SysTick_VAL;
SysTick_VAL = SysTimer_GetLoadValue();
return (uint32_t)(systick_info.interval * systick_info.systick_value + SysTick_VAL);
}
__attribute__((weak)) uint32_t SysTick_Value(void){
return (uint32_t)(systick_info.systick_value);
}
__attribute__((weak)) void SysTick_Delay_Ms(uint32_t nms){
uint64_t start_mtime, delta_mtime;
uint64_t delay_ticks = (CRM_GetMtimeFreq() * (uint64_t)nms) / 1000;
start_mtime = SysTimer_GetLoadValue();
do {
delta_mtime = SysTimer_GetLoadValue() - start_mtime;
} while (delta_mtime < delay_ticks);
}
__attribute__((weak)) void SysTick_Delay_Us(uint32_t nus){
uint64_t start_mtime, delta_mtime;
uint64_t delay_ticks = (CRM_GetMtimeFreq() * (uint64_t)nus) / 1000000;
start_mtime = SysTimer_GetLoadValue();
do {
delta_mtime = SysTimer_GetLoadValue() - start_mtime;
} while (delta_mtime < delay_ticks);
}
__attribute__((section(".ipc.sys.time.base"), used)) volatile uint32_t sys_time_base_cp = 0;
void SysTimeBaseSetCP(uint32_t ms)
{
sys_time_base_cp = ms;
}
uint32_t SysTimeMsGet(void)
{
#if CONFIG_ARCS_AP_CORE
return __get_rv_time() / 1000;
#else
return sys_time_base_cp + __get_rv_time() / 1000;
#endif
}

View File

@@ -0,0 +1,22 @@
#ifndef __SYSUTILS_H__
#define __SYSUTILS_H__
#define __weak__ __attribute__((weak))
#define __cmn_sram_bss__ __attribute__((section(".cmn_sram.bss")))
#define __itcm_text__ __attribute__((section(".itcm.text")))
#define __dtcm_data__ __attribute__((section(".dtcm.data")))
#define __dtcm_bss__ __attribute__((section(".dtcm.bss")))
#define __psram_data__ __attribute__((section(".psram.data")))
#define __psram_bss__ __attribute__((section(".psram.bss")))
#define __psram_code__ __attribute__((section(".psram.text")))
#define __psram_noinit__ __attribute__((section(".psram.noinit")))
#define __noinit__ __attribute__((section(".noinit")))
#define __alias__(fn) __attribute__((alias(#fn)))
#endif

View File

@@ -0,0 +1,81 @@
include(ExternalProject)
add_dependencies(${LISTENAI_EXECUTABLE_NAME} boot)
# 允许外部指定生成 app.bin 的 target,默认为 mkhdr
if(NOT DEFINED LISTENAI_BOOT_APP_BIN_TARGET)
set(LISTENAI_BOOT_APP_BIN_TARGET "mkhdr")
endif()
set(boot_bin_path ${CMAKE_BINARY_DIR}/boot/boot.bin)
set(app_bin_path ${CMAKE_BINARY_DIR}/${LISTENAI_EXECUTABLE_NAME}.bin)
set(MERGED_BINARY_PATH ${CMAKE_BINARY_DIR}/${LISTENAI_EXECUTABLE_NAME}_with_boot.bin)
set(FILL_DATA_PATH ${CMAKE_BINARY_DIR}/fill_data.bin)
math(EXPR FIRMWARE_SIZE "${CONFIG_BOOT_FLASH_SIZE}")
if (NOT DEFINED CONFIG_MEM_CONFIG)
if (NOT DEFINED CONFIG_BOOT_CP_ENTRY)
message(FATAL_ERROR "CONFIG_BOOT_CP_ENTRY is not defined")
endif()
math(EXPR CP_ENTRY "${CONFIG_BOOT_CP_ENTRY}")
math(EXPR EXPECT_CP_ENTRY "0x30000000 + ${CONFIG_BOOT_FLASH_SIZE}")
to_hex(${EXPECT_CP_ENTRY} EXPECT_CP_ENTRY_HEX)
if (NOT ${CP_ENTRY} STREQUAL ${EXPECT_CP_ENTRY})
message(FATAL_ERROR "CONFIG_BOOT_CP_ENTRY:${CONFIG_BOOT_CP_ENTRY} is not config correctly, expect entry:${EXPECT_CP_ENTRY_HEX}")
endif()
else()
math(EXPR CP_ENTRY "${CONFIG_MEM_FLASH_BASE} + ${CONFIG_BOOT_FLASH_SIZE}")
endif()
to_hex(${CP_ENTRY} CP_ENTRY_HEX)
get_cmake_property(VARS VARIABLES)
set(BOOT_CONFIGS "")
foreach(VAR IN LISTS VARS)
if(VAR MATCHES "^CONFIG_BOOT")
message(STATUS "${VAR} = ${${VAR}}")
list(APPEND BOOT_CONFIGS "${VAR}=${${VAR}}")
endif()
endforeach()
list(APPEND BOOT_CONFIGS "CONFIG_BOOT_CP_ENTRY=${CP_ENTRY_HEX}")
# 收集需要传递给 boot 的额外编译定义
set(BOOT_EXTRA_DEFINES "")
if(DEFINED CONFIG_MEM_FLASH_BASE)
list(APPEND BOOT_EXTRA_DEFINES "CONFIG_MEM_FLASH_BASE=${CONFIG_MEM_FLASH_BASE}")
endif()
set(BOOT_APP_CONFIG_FILE ${CMAKE_BINARY_DIR}/boot/app.config)
foreach(config IN LISTS BOOT_CONFIGS)
file(APPEND ${BOOT_APP_CONFIG_FILE} "${config}\n")
endforeach()
# 将列表转换为字符串传递
string(REPLACE ";" "|" BOOT_EXTRA_DEFINES_STR "${BOOT_EXTRA_DEFINES}")
ExternalProject_Add(
boot
SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}/boot
BINARY_DIR ${CMAKE_BINARY_DIR}/boot
CMAKE_ARGS
-DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}
-DCONFIG_FILES=${BOOT_APP_CONFIG_FILE}
-DBOOT_EXTRA_DEFINES=${BOOT_EXTRA_DEFINES_STR}
BUILD_COMMAND ${CMAKE_COMMAND} --build .
INSTALL_COMMAND ${CMAKE_COMMAND} --install .
)
add_custom_target(
merge_boot
ALL
COMMAND truncate -s ${FIRMWARE_SIZE} ${boot_bin_path}
COMMAND ${CMAKE_COMMAND} -E echo "-- Merging boot and app binary files"
COMMAND ${CMAKE_COMMAND} -E cat ${boot_bin_path} ${app_bin_path} > ${MERGED_BINARY_PATH}
COMMAND ${CMAKE_COMMAND} -E rename ${LISTENAI_EXECUTABLE_NAME}.bin ${LISTENAI_EXECUTABLE_NAME}.bin.without.boot
COMMAND ${CMAKE_COMMAND} -E rename ${MERGED_BINARY_PATH} ${LISTENAI_EXECUTABLE_NAME}.bin
DEPENDS boot ${LISTENAI_BOOT_APP_BIN_TARGET}
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)

View File

@@ -0,0 +1,14 @@
cmake_minimum_required(VERSION 3.13)
set(LISTENAI_MODULES_DIR_LIST
${CMAKE_CURRENT_SOURCE_DIR}/src
)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
find_package(listenai-cmake REQUIRED HINTS $ENV{ARCS_BASE})
project(boot)
listenai_add_executable(${PROJECT_NAME})
listenai_set_linker_script(${CMAKE_CURRENT_SOURCE_DIR}/src/linker.ld)

View File

@@ -0,0 +1,2 @@
osource "$LISTENAI_MODULES"
rsource "Kconfig.boot"

View File

@@ -0,0 +1,49 @@
config BOOT_AP_ENTRY
hex "AP entry"
default 0
config BOOT_CP_ENTRY
hex "CP entry"
default 0
depends on !MEM_CONFIG
config BOOT_FLASH_SIZE
hex "Flash size"
default 0x4000
choice
prompt "boot log level"
default BOOT_LOG_LVL_ERR
config BOOT_LOG_LVL_NON
bool "non"
config BOOT_LOG_LVL_ERR
bool "err"
config BOOT_LOG_LVL_WRN
bool "wrn"
config BOOT_LOG_LVL_INF
bool "inf"
config BOOT_LOG_LVL_DBG
bool "dbg"
config BOOT_UART_PORT
int "boot log port"
default SYSLOG_UART_PORT if BOOT
default 0
config BOOT_UART_TX_PIN
int "boot uart tx pin"
default SYSLOG_UART_TX_PIN if BOOT
default 3
config BOOT_UART_BAUDRATE
int "boot log baud rate"
default SYSLOG_UART_BAUDRATE if BOOT
default 921600
config BOOT_UART_PIN_FUNC_SEL
int "boot log pin func sel"
default SYSLOG_UART_TX_PIN_FUNC_SEL if BOOT
default 2
endchoice

177
arcs-sdk/startup/boot/build.sh Executable file
View File

@@ -0,0 +1,177 @@
#!/bin/bash
set -e
usage() {
echo "使用方式: $0 [选项]"
echo "选项:"
echo " -S, --Source <path> 指定项目源码路径 (默认为当前脚本所在目录)"
echo " -t, --target <target> 指定构建目标 (如 menuconfig)"
echo " -C, --Clean 清理构建目录"
echo " -B, --build 构建输出目录"
echo " -h, --help 显示此帮助信息"
echo " -r, --release 以 Release 模式构建 (移除 DEBUG_PATH 信息)"
echo " -w, --warnings-as-errors 将警告视为错误"
echo " -D<var>=<value> 传递 CMake 变量 (可多次使用)"
echo ""
echo "示例:"
echo " $0 -S samples/helloworld -DBOARD=arcs_mini 指定板型构建"
echo " $0 -S samples/helloworld -DBOARD=arcs_evb 使用 EVB 板型"
echo " $0 -S samples/helloworld -t menuconfig -DBOARD=arcs_mini 运行 menuconfig"
echo " $0 -C -S samples/helloworld -DBOARD=arcs_mini 清理并重新构建"
echo " $0 -S samples/helloworld -DBOARD=my_board -DBOARD_SEARCH_PATH=/path/to/boards 使用自定义板型"
exit 1
}
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
PROJECT_PATH="$SCRIPT_DIR"
TARGET=""
CLEAN=false
OUTPUT="build"
WARNINGS_AS_ERRORS=false
RELEASE=false
ARCS_BASE_DIR_NAME="arcs-sdk"
ARCS_DEV_TOOLS_DIR_NAME="listenai-dev-tools"
ARCS_DEV_TOOL_TOOLCHAIN_DIR_NAME="gcc"
ARCS_DEV_TOOL_LISTENAI_TOOLS_DIR_NAME="listenai-tools"
find_arcs_base() {
local current_dir=$(cd "$(dirname "$0")" && pwd)
local dir_name="$ARCS_BASE_DIR_NAME"
while [ "$current_dir" != "/" ]; do
if [ -d "$current_dir/$dir_name" ]; then
echo "Found ARCS_BASE: $current_dir/$dir_name"
export ARCS_BASE="$current_dir/$dir_name"
return 0
fi
current_dir=$(dirname "$current_dir")
done
echo "ARCS_BASE not found, Please add ARCS_BASE environment variable or set ARCS_BASE_DIR_NAME to the correct directory."
echo "Current Target ARCS_BASE directory name: $ARCS_BASE_DIR_NAME."
exit 1
}
find_dev_tools() {
local current_dir=$(cd "$(dirname "$0")" && pwd)
local dir_name="$ARCS_DEV_TOOLS_DIR_NAME"
echo "trying to find $dir_name in parent directories..."
while [ "$current_dir" != "/" ]; do
if [ -d "$current_dir/$dir_name" ]; then
echo "Found $dir_name: $current_dir/$dir_name"
if [ -d "$current_dir/$dir_name/$ARCS_DEV_TOOL_LISTENAI_TOOLS_DIR_NAME" ]; then
echo "Found LISTENAI_TOOLS_PATH: $current_dir/$dir_name/$ARCS_DEV_TOOL_LISTENAI_TOOLS_DIR_NAME"
export LISTENAI_TOOLS_PATH="$current_dir/$dir_name/$ARCS_DEV_TOOL_LISTENAI_TOOLS_DIR_NAME"
fi
if [ -d "$current_dir/$dir_name/$ARCS_DEV_TOOL_TOOLCHAIN_DIR_NAME" ]; then
echo "Found NUCLEI_TOOLCHAIN_PATH: $current_dir/$dir_name/$ARCS_DEV_TOOL_TOOLCHAIN_DIR_NAME"
export NUCLEI_TOOLCHAIN_PATH="$current_dir/$dir_name/$ARCS_DEV_TOOL_TOOLCHAIN_DIR_NAME"
fi
return 0
fi
current_dir=$(dirname "$current_dir")
done
}
while [[ $# -gt 0 ]]; do
case $1 in
-S|--Source)
PROJECT_PATH="$2"
shift 2
;;
-B|--build)
OUTPUT="$2"
shift 2
;;
-t|--target)
TARGET="$2"
shift 2
;;
-C|--Clean)
CLEAN=true
shift 1
;;
-w|--warnings-as-errors)
WARNINGS_AS_ERRORS=true
shift 1
;;
-h|--help)
usage
;;
-r|--release)
RELEASE=true
shift 1
;;
-D*)
CMAKE_VARS+=("$1")
shift 1
;;
*)
echo "未知参数: $1"
usage
;;
esac
done
echo "Source: $PROJECT_PATH"
echo "Target: $TARGET"
echo "Clean : $CLEAN"
if [ -z "$LISTENAI_TOOLS_PATH" ] || [ -z "$NUCLEI_TOOLCHAIN_PATH" ]; then
find_dev_tools
fi
if [ -z "${LISTENAI_TOOLS_PATH}" ]; then
export LISTENAI_TOOLS_PATH="请添加 LISTENAI_TOOLS_PATH 环境变量,或在此行设置正确的路径"
echo "请添加 LISTENAI_TOOLS_PATH 环境变量或者修改脚本后, 注释脚本第 $LINENO 行";exit 1;
fi
if [ -z "${NUCLEI_TOOLCHAIN_PATH}" ]; then
export NUCLEI_TOOLCHAIN_PATH="请添加 NUCLEI_TOOLCHAIN_PATH 环境变量,或在此行设置正确的路径"
echo "请添加 NUCLEI_TOOLCHAIN_PATH 环境变量或者修改脚本后, 注释脚本第 $LINENO 行";exit 1;
fi
############### 下面代码不用修改 ##################
# 构建工具的位置
CMAKE_PROGRAM="$LISTENAI_TOOLS_PATH/cmake/bin/cmake"
NINJA_PROGRAM="$LISTENAI_TOOLS_PATH/ninja/ninja"
# 配置环境变量 ARCS_BASE
if [ -z "$ARCS_BASE" ]; then
find_arcs_base
fi
if [ "$CLEAN" = true ]; then
rm -rf $OUTPUT
fi
# Initialize CMAKE_VARS array if it doesn't exist
declare -a CMAKE_VARS
# Add warnings-as-errors flag if enabled
if [ "$WARNINGS_AS_ERRORS" = true ]; then
CMAKE_VARS+=("-DCMAKE_C_FLAGS=-Werror")
CMAKE_VARS+=("-DCMAKE_CXX_FLAGS=-Werror")
echo "Treating warnings as errors"
fi
# Add release flags if enabled
if [ "$RELEASE" = true ]; then
CMAKE_VARS+=("-DENABLE_DEBUG_PATH=OFF")
echo "Release mode enabled (-DENABLE_DEBUG_PATH=OFF)"
fi
$CMAKE_PROGRAM -B "$OUTPUT" -G Ninja -S "$PROJECT_PATH" \
-DCMAKE_MAKE_PROGRAM="$NINJA_PROGRAM" \
"${CMAKE_VARS[@]}"
if [ -z "$TARGET" ]; then
$CMAKE_PROGRAM --build "$OUTPUT" -j4
else
$CMAKE_PROGRAM --build "$OUTPUT" --target "$TARGET"
fi

View File

@@ -0,0 +1,2 @@
# 项目可根据需要在此文件中设置对应的配置
CONFIG_LINK_OPTION_LISTENAI_LIBRARY_NONE=y

View File

@@ -0,0 +1,4 @@
tests:
startup.boot:
build_only: true

View File

@@ -0,0 +1,50 @@
enable_language(ASM)
listenai_library_named(boot_app)
listenai_compile_definitions(-DCHIP=4 -DIC_BOARD=1 -DPSRAM_LOG_CHECK=0)
# 添加从父项目传递的额外编译定义
if(DEFINED BOOT_EXTRA_DEFINES)
string(REPLACE "|" ";" BOOT_EXTRA_DEFINES_LIST "${BOOT_EXTRA_DEFINES}")
foreach(define IN LISTS BOOT_EXTRA_DEFINES_LIST)
listenai_compile_definitions(${define})
endforeach()
endif()
set(ENV{ARCS_SOC_BASE} $ENV{ARCS_BASE}/soc/arcs)
listenai_include_directories(
$ENV{ARCS_SOC_BASE}/hal/chip/arcs/bsp
$ENV{ARCS_SOC_BASE}/hal/chip/arcs/include
$ENV{ARCS_SOC_BASE}/hal/include/bsp
$ENV{ARCS_SOC_BASE}/hal/include/NMSIS/Core/Include
$ENV{ARCS_SOC_BASE}/hal/include/bsp
$ENV{ARCS_SOC_BASE}/hal/include/NMSIS/Core/Include
$ENV{ARCS_SOC_BASE}/hal/include/NMSIS/DSP/Include
$ENV{ARCS_SOC_BASE}/hal/include/NMSIS/DSP/Include/dsp
$ENV{ARCS_SOC_BASE}/hal/include/NMSIS/DSP/PrivateInclude
$ENV{ARCS_SOC_BASE}/hal/chip/arcs/bsp/
$ENV{ARCS_SOC_BASE}/hal/chip/arcs/include/
$ENV{ARCS_SOC_BASE}/hal/chip/arcs/include/utils
$ENV{ARCS_SOC_BASE}/hal/chip/arcs/include/register
$ENV{ARCS_SOC_BASE}/hal/chip/arcs/driver/private_include
$ENV{ARCS_SOC_BASE}/hal/modules/debug/include/
$ENV{ARCS_SOC_BASE}/hal/modules/debug/
)
listenai_include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/
)
listenai_library_sources(
boot.S
boot.c
boot_log.c
cache.c
$ENV{ARCS_SOC_BASE}/hal/chip/arcs/driver/system/PSRAMManager.c
$ENV{ARCS_SOC_BASE}/hal/chip/arcs/driver/cmu/clock_config.c
$ENV{ARCS_SOC_BASE}/hal/chip/arcs/driver/cmu/ClockManager.c
$ENV{ARCS_SOC_BASE}/hal/chip/arcs/driver/iomux/IOMuxManager.c
)

View File

@@ -0,0 +1,212 @@
#include "riscv_encoding.h"
.macro DECLARE_INT_HANDLER INT_HDL_NAME
#if defined(__riscv_xlen) && (__riscv_xlen == 32)
.word \INT_HDL_NAME
#else
.dword \INT_HDL_NAME
#endif
.endm
.section .vtable
.globl vector_base
.type vector_base, @object
vector_base:
#ifndef VECTOR_TABLE_REMAPPED
j _start /* 0: Reserved, Jump to _start when reset for vector table not remapped cases.*/
.align LOG_REGBYTES /* Need to align 4 byte for RV32, 8 Byte for RV64 */
#else
DECLARE_INT_HANDLER irq_default_handler /* 0: Reserved, default handler for vector table remapped cases */
#endif
DECLARE_INT_HANDLER irq_default_handler /* 1: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 2: Reserved */
#ifndef CFG_RTOS
DECLARE_INT_HANDLER irq_default_handler /* 3: Machine software interrupt */
#else
DECLARE_INT_HANDLER irq_default_handler /* 3: Machine software interrupt, vector mode for FreeRTOS implementation */
#endif
DECLARE_INT_HANDLER irq_default_handler /* 4: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 5: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 6: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 7: Machine timer interrupt */
DECLARE_INT_HANDLER irq_default_handler /* 8: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 9: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 10: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 11: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 12: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 13: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 14: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 15: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 16: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 17: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 18: Reserved */
DECLARE_INT_HANDLER irq_default_handler /* 19: Interrupt 19 */
DECLARE_INT_HANDLER irq_default_handler /* 20: Interrupt 20 */
DECLARE_INT_HANDLER irq_default_handler /* 21: Interrupt 21 */
DECLARE_INT_HANDLER irq_default_handler /* 22: Interrupt 22 */
DECLARE_INT_HANDLER irq_default_handler /* 23: Interrupt 23 */
DECLARE_INT_HANDLER irq_default_handler /* 24: Interrupt 24 */
DECLARE_INT_HANDLER irq_default_handler /* 25: Interrupt 25 */
DECLARE_INT_HANDLER irq_default_handler /* 26: Interrupt 26 */
DECLARE_INT_HANDLER irq_default_handler /* 27: Interrupt 27 */
DECLARE_INT_HANDLER irq_default_handler /* 28: Interrupt 28 */
DECLARE_INT_HANDLER irq_default_handler /* 29: Interrupt 29 */
DECLARE_INT_HANDLER irq_default_handler /* 30: Interrupt 30 */
DECLARE_INT_HANDLER irq_default_handler /* 31: Interrupt 31 */
DECLARE_INT_HANDLER irq_default_handler /* 32: Interrupt 32 */
DECLARE_INT_HANDLER irq_default_handler /* 33: Interrupt 33 */
DECLARE_INT_HANDLER irq_default_handler /* 34: Interrupt 34 */
DECLARE_INT_HANDLER irq_default_handler /* 35: Interrupt 35 */
DECLARE_INT_HANDLER irq_default_handler /* 36: Interrupt 36 */
DECLARE_INT_HANDLER irq_default_handler /* 37: Interrupt 37 */
DECLARE_INT_HANDLER irq_default_handler /* 38: Interrupt 38 */
DECLARE_INT_HANDLER irq_default_handler /* 39: Interrupt 39 */
DECLARE_INT_HANDLER irq_default_handler /* 40: Interrupt 40 */
DECLARE_INT_HANDLER irq_default_handler /* 41: Interrupt 41 */
DECLARE_INT_HANDLER irq_default_handler /* 42: Interrupt 42 */
DECLARE_INT_HANDLER irq_default_handler /* 43: Interrupt 43 */
DECLARE_INT_HANDLER irq_default_handler /* 44: Interrupt 44 */
DECLARE_INT_HANDLER irq_default_handler /* 45: Interrupt 45 */
DECLARE_INT_HANDLER irq_default_handler /* 46: Interrupt 46 */
DECLARE_INT_HANDLER irq_default_handler /* 47: Interrupt 47 */
DECLARE_INT_HANDLER irq_default_handler /* 48: Interrupt 48 */
DECLARE_INT_HANDLER irq_default_handler /* 49: Interrupt 49 */
DECLARE_INT_HANDLER irq_default_handler /* 50: Interrupt 50 */
DECLARE_INT_HANDLER irq_default_handler /* 51: Interrupt 51 */
DECLARE_INT_HANDLER irq_default_handler /* 52: Interrupt 52 */
DECLARE_INT_HANDLER irq_default_handler /* 53: Interrupt 53 */
DECLARE_INT_HANDLER irq_default_handler /* 54: Interrupt 54 */
DECLARE_INT_HANDLER irq_default_handler /* 55: Interrupt 55 */
DECLARE_INT_HANDLER irq_default_handler /* 56: Interrupt 56 */
DECLARE_INT_HANDLER irq_default_handler /* 57: Interrupt 57 */
DECLARE_INT_HANDLER irq_default_handler /* 58: Interrupt 58 */
DECLARE_INT_HANDLER irq_default_handler /* 59: Interrupt 59 */
DECLARE_INT_HANDLER irq_default_handler /* 60: Interrupt 60 */
DECLARE_INT_HANDLER irq_default_handler /* 61: Interrupt 61 */
DECLARE_INT_HANDLER irq_default_handler /* 62: Interrupt 62 */
DECLARE_INT_HANDLER irq_default_handler /* 63: Interrupt 63 */
DECLARE_INT_HANDLER irq_default_handler /* 64: Interrupt 64 */
DECLARE_INT_HANDLER irq_default_handler /* 65: Interrupt 65 */
DECLARE_INT_HANDLER irq_default_handler /* 66: Interrupt 66 */
DECLARE_INT_HANDLER irq_default_handler /* 67: Interrupt 67 */
DECLARE_INT_HANDLER irq_default_handler /* 68: Interrupt 68 */
DECLARE_INT_HANDLER irq_default_handler /* 69: Interrupt 69 */
DECLARE_INT_HANDLER irq_default_handler /* 70: Interrupt 70 */
DECLARE_INT_HANDLER irq_default_handler /* 71: Interrupt 71 */
DECLARE_INT_HANDLER irq_default_handler /* 72: Interrupt 72 */
DECLARE_INT_HANDLER irq_default_handler /* 73: Interrupt 73 */
DECLARE_INT_HANDLER irq_default_handler /* 74: Interrupt 74 */
DECLARE_INT_HANDLER irq_default_handler /* 75: Interrupt 75 */
DECLARE_INT_HANDLER irq_default_handler /* 76: Interrupt 76 */
DECLARE_INT_HANDLER irq_default_handler /* 77: Interrupt 77 */
.word 0 /* 78: reserved */
.word 0 /* 79: reserved */
/* Header */
.ascii "Hr" /* byte(0~1): header mark */
.byte 0x01, 0x04 /* byte(2~3): header version 1.4 */
.word 0 /* byte(4~7): image size */
.word vector_base /* byte(8~11): image vma */
.byte 0x01, 0x00, 0x03 /* byte(12~14): image version 1.0.1 */
.byte 0x00 /* byte(15~15): image flags */
.ascii "ARCS", "_APP", "\0\0\0\0" /* byte(16~27): image name */
.short 0x00 /* byte(28~29): patch_offset*/
.short 0x00 /* byte(30~31): gpt_offset */
.word 0 /* byte(32~59): reserved */
.word 0 /* byte(36~39): reserved */
.word 0 /* byte(40~43): reserved */
.word 0 /* byte(44~47): reserved */
.word 0 /* byte(48~51): reserved */
.word 0 /* byte(52~55): reserved */
.word 0 /* byte(56~59): reserved */
.short 0x0 /* byte(60~61): header check sum */
.short 0x0 /* byte(62~63): vector check sum */
/* Reset Handler called on controller reset */
.section .init
.section .init
.section .init
.globl _start
.type _start, @function
_start:
/* ===== Startup Stage 1 ===== */
/* Disable Global Interrupt */
csrc CSR_MSTATUS, MSTATUS_MIE
/* Initialize GP and TP */
.option push
.option norelax
la gp, __global_pointer$
la tp, __tls_base
.option pop
/* Set correct sp for current cpu */
la sp, __StackTop
/* Set the the NMI base mnvec to share with mtvec by setting CSR_MMISC_CTL bit 9 NMI_CAUSE_FFF to 1 */
li t0, MMISC_CTL_NMI_CAUSE_FFF
csrs CSR_MMISC_CTL, t0
/* Intialize ECLIC vector interrupt base address mtvt to vector_base */
la t0, vector_base
csrw CSR_MTVT, t0
/* Set ECLIC non-vector entry to be controlled by mtvt2 CSR register.
* Intialize ECLIC non-vector interrupt base address mtvt2 to irq_entry. */
la t0, irq_entry
csrw CSR_MTVT2, t0
csrs CSR_MTVT2, 0x1
/* Set Exception Entry MTVEC to early_exc_entry Due to settings above, Exception and NMI will share common entry.
* This early_exc_entry is only used during early boot stage before main */
la t0, early_exc_entry
csrw CSR_MTVEC, t0
/* Set the interrupt processing mode to ECLIC mode */
li t0, 0x3f
csrc CSR_MTVEC, t0
csrs CSR_MTVEC, 0x3
/* ===== Startup Stage 2 ===== */
/* Enable FPU and Vector Unit if f/d/v exist in march */
#if defined(__riscv_flen) && __riscv_flen > 0
/* Enable FPU, and set state to initial */
li t0, MSTATUS_FS
csrc mstatus, t0
li t0, MSTATUS_FS_INITIAL
csrs mstatus, t0
#endif
#if defined(__riscv_vector)
/* Enable Vector, and set state to initial */
li t0, MSTATUS_VS
csrc mstatus, t0
li t0, MSTATUS_VS_INITIAL
csrs mstatus, t0
#endif
/* Enable mcycle and minstret counter */
csrci CSR_MCOUNTINHIBIT, 0x5
call boot_run
/* Early boot exception entry before main */
.align 6
.global early_exc_entry
.type early_exc_entry, @function
early_exc_entry:
wfi
j early_exc_entry
.align 6
.global irq_entry
.type irq_entry, @function
irq_entry:
wfi
j irq_entry

View File

@@ -0,0 +1,151 @@
#include "chip.h"
#include "memap.h"
#include "PSRAMManager.h"
#include "ClockManager.h"
#include "boot_log.h"
#include <stdint.h>
extern uint32_t __scat_copy_base, __scat_copy_last, __scat_zero_base, __scat_zero_last;
extern uint32_t __psram_scat_copy_base, __psram_scat_copy_last, __psram_scat_zero_base, __psram_scat_zero_last;
typedef struct {
uint32_t len, *vma, *lma;
} scat_copy_item_t;
typedef struct {
uint32_t len, *vma;
} scat_zero_item_t;
static __attribute__((section(".init"))) void _scatload(uint32_t *dst, const uint32_t *src, uint32_t cnt)
{
while (cnt--) {
*dst++ = *src++;
}
}
static __attribute__((section(".init"))) void _scatfill(uint32_t *dst, uint32_t fill, int cnt)
{
while (cnt--) {
*dst++ = fill;
}
}
static __attribute__((section(".init"))) void scatload(void)
{
for (scat_copy_item_t *item = (void *)&__scat_copy_base; (uint32_t *)item < &__scat_copy_last; item++) {
if (item->vma && item->len >= sizeof(uint32_t) && item->vma != item->lma) {
_scatload(item->vma, item->lma, item->len >> 2);
}
}
for (scat_zero_item_t *item = (void *)&__scat_zero_base; (uint32_t *)item < &__scat_zero_last; item++) {
if (item->vma && item->len >= sizeof(uint32_t)) {
_scatfill(item->vma, 0, item->len >> 2);
}
}
}
static void scatload_psram(void)
{
for (scat_copy_item_t *item = (void *)&__psram_scat_copy_base; (uint32_t *)item < &__psram_scat_copy_last; item++) {
if (item->vma && item->len >= sizeof(uint32_t) && item->vma != item->lma) {
_scatload(item->vma, item->lma, item->len >> 2);
}
}
for (scat_zero_item_t *item = (void *)&__psram_scat_zero_base; (uint32_t *)item < &__psram_scat_zero_last; item++) {
if (item->vma && item->len >= sizeof(uint32_t)) {
_scatfill(item->vma, 0, item->len >> 2);
}
}
}
void irq_default_handler(void)
{
}
#define FALLBACK_DEFAULT_ECLIC_BASE 0x0C000000UL
#define FALLBACK_DEFAULT_SYSTIMER_BASE 0x02000000UL
volatile IRegion_Info_Type SystemIRegionInfo;
static void _get_iregion_info(volatile IRegion_Info_Type *iregion)
{
unsigned long mcfg_info;
if (iregion == NULL) {
return;
}
mcfg_info = __RV_CSR_READ(CSR_MCFG_INFO);
if (mcfg_info & MCFG_INFO_IREGION_EXIST) { // IRegion Info present
iregion->iregion_base = (__RV_CSR_READ(CSR_MIRGB_INFO) >> 10) << 10;
iregion->eclic_base = iregion->iregion_base + IREGION_ECLIC_OFS;
iregion->systimer_base = iregion->iregion_base + IREGION_TIMER_OFS;
iregion->smp_base = iregion->iregion_base + IREGION_SMP_OFS;
iregion->idu_base = iregion->iregion_base + IREGION_IDU_OFS;
} else {
iregion->eclic_base = FALLBACK_DEFAULT_ECLIC_BASE;
iregion->systimer_base = FALLBACK_DEFAULT_SYSTIMER_BASE;
}
}
static const uint32_t psram_size[] = {0, 32, 0, 64, 0, 128, 512, 256};
void boot_run(void)
{
__disable_irq();
scatload();
_get_iregion_info(&SystemIRegionInfo);
extern void BootClock_Init();
BootClock_Init();
__FENCE_I();
bootlog_init(CONFIG_BOOT_UART_PORT, CONFIG_BOOT_UART_BAUDRATE);
bootlog_dbg("main clk: %d Hz\n", CRM_GetSrcFreq(CRM_IpSrcCoreClk));
bootlog_dbg("psram clk: %d Hz\n", CRM_GetPsramFreq());
uint32_t rdly = 18, wdly = 22;
int r;
r = PSRAM_Initialize(&rdly, &wdly, 1);
if (r != 0) {
bootlog_err("psram error, code: %d\n", r);
while(1);
}
uint32_t density = ((IP_PSRAM_CTRL->REG_MR2.all & 0xff) >> 0) & 0x07;
if (density < sizeof(psram_size)/ sizeof(psram_size[0])) {
bootlog_dbg("psram inf, size: %d Mbit, w: %d, r: %d\n", psram_size[density], wdly, rdly);
} else {
bootlog_dbg("psram inf, size: unknown, w: %d, r: %d\n", wdly, rdly);
}
for (int i = 0; i < IRQ_MAX; i++) {
disable_IRQ(i);
clear_IRQ(i);
}
#if defined CONFIG_BOOT_CP_ENTRY
IP_CMN_SYS->REG_N300_CP_RST_ADDR.all = (uint32_t)CONFIG_BOOT_CP_ENTRY;
IP_SYSCTRL->REG_SW_RESET_CP0.all = 0xCAFE000A;
bootlog_dbg("cp: 0x%x\n", CONFIG_BOOT_CP_ENTRY);
#endif
#if defined CONFIG_BOOT_AP_ENTRY
if (CONFIG_BOOT_AP_ENTRY) {
void (*ap_core_start)(void) = (void (*)(void))CONFIG_BOOT_AP_ENTRY;
ap_core_start();
bootlog_dbg("ap: 0x%x\n", CONFIG_BOOT_AP_ENTRY);
}
#endif
bootlog_inf("ap: none\n");
while (1) {
__WFI();
}
}

View File

@@ -0,0 +1,258 @@
#include "stdint.h"
#include "log_print.h"
#include <stdio.h>
#include "uart_reg.h"
#include "chip.h"
#include "ClockManager.h"
#include "IOMuxManager.h"
static UART_RegDef *uart = NULL;
static uint32_t compute_gcd(uint32_t a, uint32_t c)
{
uint32_t t;
while (c != 0) {
t = a % c;
a = c;
c = t;
}
return a;
}
static int32_t __log_compute_div(int dbg, uint32_t baudrate, uint32_t *pm, uint32_t *pn, uint32_t div)
{
uint32_t gcd, m, n, tmp;
int32_t ret = 0;
tmp = div * baudrate;
uint32_t uart_clk;
if (dbg == 0) {
uart_clk = 24000000;
} else if (dbg == 1) {
uart_clk = 24000000;
}
gcd = compute_gcd(uart_clk, tmp);
m = uart_clk / gcd;
n = tmp / gcd;
if ((m > 1023) || (n > 511)) {
return -1;
}
*pm = m;
*pn = n;
return 0;
}
static int32_t log_compute_div(int dbg, uint32_t baudrate, uint32_t *pm, uint32_t *pn, uint32_t *pdiv)
{
int32_t ret = 0;
do {
if (__log_compute_div(dbg, baudrate, pm, pn, 4) == 0) {
*pdiv = 4;
break;
}
if (__log_compute_div(dbg, baudrate, pm, pn, 16) == 0) {
*pdiv = 16;
break;
}
ret = -1;
} while (0);
return ret;
}
#define CONFIG_SYSLOG_UART_TX_PIN 3
#define CONFIG_SYSLOG_UART_TX_PIN_FUNC_SEL 0x2
static void __log_io_config(int dbg)
{
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, CONFIG_SYSLOG_UART_TX_PIN, CONFIG_SYSLOG_UART_TX_PIN_FUNC_SEL);
}
int syslog_write(const char *data, int len)
{
if (uart == NULL || data == NULL || len == 0) {
return 0;
}
for (int i = 0; i < len; i++) {
uart->REG_RXTX_BUFFER.all = data[i];
while (!uart->REG_STATUS.bit.TX_FIFO_SPACE)
;
}
return len;
}
int bootlog_init(int dbg, uint32_t baudrate)
{
uint32_t m, n, div, uart_base, cmn_reg;
if (log_compute_div(dbg, baudrate, &m, &n, &div) < 0) {
return -1;
}
__log_io_config(dbg);
switch (dbg) {
case 0:
uart = (UART_RegDef *)UART0_BASE;
__HAL_CRM_UART0_CLK_ENABLE();
HAL_CRM_SetUart0ClkDiv(n, m);
break;
case 1:
default:
uart = (UART_RegDef *)UART1_BASE;
__HAL_CRM_UART1_CLK_ENABLE();
HAL_CRM_SetUart1ClkDiv(n, m);
break;
}
uart->REG_IRQ_MASK.all = 0;
uart->REG_CTRL.all = 0;
if (div == 16) {
uart->REG_CTRL.bit.DIVISOR_MODE = 1; // 0: sclk/4; 1: sclk/16
} else {
uart->REG_CTRL.bit.DIVISOR_MODE = 0;
}
uart->REG_CMD_SET.bit.TX_FIFO_RESET = 1; // reset tx fifo
uart->REG_CMD_SET.bit.RX_FIFO_RESET = 1; // reset rx fifo
uart->REG_CTRL.bit.DATA_BITS = 1; // 8bits
uart->REG_CTRL.bit.ENABLE = 1; // enable uart
uart->REG_STATUS.all = 1; // clear line error bits
return 0;
}
static void int_to_str(int value, char *buf, size_t *written)
{
if (value < 0) {
buf[(*written)++] = '-';
value = -value;
}
if (value == 0) {
buf[(*written)++] = '0';
return;
}
char temp[10];
size_t index = 0;
while (value > 0) {
temp[index++] = (value % 10) + '0';
value /= 10;
}
for (size_t i = 0; i < index; i++) {
if (*written < 512 - 1) {
buf[(*written)++] = temp[index - 1 - i];
}
}
}
static void uint_to_hex_str(unsigned int value, char *buf, size_t *written)
{
if (value == 0) {
buf[(*written)++] = '0';
return;
}
char temp[8];
size_t index = 0;
while (value > 0) {
unsigned int digit = value % 16;
temp[index++] = (digit < 10) ? (digit + '0') : (digit - 10 + 'a');
value /= 16;
}
for (size_t i = 0; i < index; i++) {
if (*written < 512 - 1) {
buf[(*written)++] = temp[index - 1 - i];
}
}
}
int bootlog_vsnprintf(char *buf, size_t size, const char *format, va_list args)
{
size_t written = 0;
const char *p;
for (p = format; *p != '\0'; p++) {
if (*p != '%') {
if (written < size - 1) {
buf[written++] = *p;
}
continue;
}
p++;
switch (*p) {
case 'd': {
int value = va_arg(args, int);
int_to_str(value, buf, &written);
break;
}
case 'x': {
unsigned int value = va_arg(args, unsigned int);
uint_to_hex_str(value, buf, &written);
break;
}
case 's': {
const char *str = va_arg(args, const char *);
while (*str && written < size - 1) {
buf[written++] = *str++;
}
break;
}
default:
if (written < size - 1) {
buf[written++] = '%';
buf[written++] = *p;
}
break;
}
}
if (written < size) {
buf[written] = '\0';
} else if (size > 0) {
buf[size - 1] = '\0';
}
return written;
}
void bootlog_output(const char *format, va_list args)
{
static uint8_t buffer[512] = {0};
uint32_t len = bootlog_vsnprintf((char *)buffer, 512 - 1, format, args);
buffer[len] = '\0';
syslog_write(buffer, len);
}
int vprintk(const char *format, va_list args)
{
bootlog_output(format, args);
return 0;
}
int printk(const char *format, ...)
{
va_list args;
va_start(args, format);
vprintk(format, args);
va_end(args);
return 0;
}

View File

@@ -0,0 +1,66 @@
#ifndef __BOOT_LOG_H__
#define __BOOT_LOG_H__
int printk(const char *format, ...);
int bootlog_init(int dbg, uint32_t baudrate);
#define BOOTLOG_LVL_NON 0
#define BOOTLOG_LVL_ERR 1
#define BOOTLOG_LVL_WRN 2
#define BOOTLOG_LVL_INF 3
#define BOOTLOG_LVL_DBG 4
#if CONFIG_BOOT_LOG_LVL_NON
#define BOOTLOG_LVL BOOTLOG_LVL_NON
#elif CONFIG_BOOT_LOG_LVL_ERR
#define BOOTLOG_LVL BOOTLOG_LVL_ERR
#elif CONFIG_BOOT_LOG_LVL_WRN
#define BOOTLOG_LVL BOOTLOG_LVL_WRN
#elif CONFIG_BOOT_LOG_LVL_INF
#define BOOTLOG_LVL BOOTLOG_LVL_INF
#elif CONFIG_BOOT_LOG_LVL_DBG
#define BOOTLOG_LVL BOOTLOG_LVL_DBG
#endif
#ifndef BOOTLOG_LVL
#define BOOTLOG_LVL BOOTLOG_LVL_ERR
#endif
#if BOOTLOG_LVL >= BOOTLOG_LVL_ERR
#define bootlog_err(fmt, args...) \
do { \
printk("[boot] err: " fmt, ##args); \
} while (0)
#else
#define bootlog_err(fmt, args...)
#endif
#if BOOTLOG_LVL >= BOOTLOG_LVL_WRN
#define bootlog_wrn(fmt, args...) \
do { \
printk("[boot] wrn: " fmt, ##args); \
} while (0)
#else
#define bootlog_wrn(fmt, args...)
#endif
#if BOOTLOG_LVL >= BOOTLOG_LVL_INF
#define bootlog_inf(fmt, args...) \
do { \
printk("[boot] inf: " fmt, ##args); \
} while (0)
#else
#define bootlog_inf(fmt, args...)
#endif
#if BOOTLOG_LVL >= BOOTLOG_LVL_DBG
#define bootlog_dbg(fmt, args...) \
do { \
printk("[boot] dbg: " fmt, ##args); \
} while (0)
#else
#define bootlog_dbg(fmt, args...)
#endif
#endif

View File

@@ -0,0 +1,545 @@
/*
* cache_ap.c
*
* Created on: Jul 10, 2020
*
*/
#include <assert.h>
#include "chip.h"
#include "nmsis_core.h"
#include "cache.h"
/**
* @brief Enables the CPU instruction cache.
*
* This function activates the internal instruction cache of the CPU
* to enhance the execution speed of programs. It is part of the Hardware
* Abstraction Layer (HAL), providing an interface to manage hardware-specific
* features such as caching operations. Enabling the instruction cache allows
* for faster access to frequently executed instructions, which is crucial
* for performance-critical applications.
*/
void HAL_EnableICache(void){
#if HAL_ICACHE_VALID
__disable_irq();
EnableICache();
__enable_irq();
#endif
}
/**
* @brief Disables the CPU instruction cache.
*
* This function deactivates the internal instruction cache of the CPU
* to potentially aid in debugging or to meet specific system requirements
* where caching of instructions needs to be prevented. It is part of the Hardware
* Abstraction Layer (HAL), providing an interface to manage hardware-specific
* features such as caching operations. Disabling the instruction cache may be
* necessary in scenarios where precise control over instruction execution is required.
*/
void HAL_DisableICache(void){
#if HAL_ICACHE_VALID
__disable_irq();
DisableICache();
__enable_irq();
#endif
}
/**
* @brief Invalidates the CPU instruction cache.
*
* This function clears the contents of the internal instruction cache of the CPU.
* Invalidating the cache is useful to ensure that no stale or corrupted data is used
* by the CPU, which is particularly important after direct memory access (DMA) operations
* or after loading new programs into memory. It is part of the Hardware Abstraction Layer (HAL),
* providing an interface to manage hardware-specific features such as caching operations.
* This operation helps in maintaining data coherency and consistency across the system.
*/
void HAL_InvalidateICache(void){
#if HAL_ICACHE_VALID
__disable_irq();
MInvalICache();
__enable_irq();
#endif
}
/**
* @brief Invalidates a range of the CPU data cache based on address and size.
*
* This function clears a specific portion of the CPU's internal data cache. By providing
* an address and the size of the area, this function ensures that any modifications in
* memory in this specified range do not use stale or outdated cache entries. This is particularly
* useful for systems where memory regions are dynamically altered or when devices not supporting
* cache coherency modify the memory. It helps in maintaining data integrity and coherency
* especially in systems involving direct memory access (DMA) operations.
*
* @param addr Pointer to the start address of the memory region to invalidate.
* @param dsize Size of the memory region to invalidate, in bytes.
*/
void HAL_InvalidateICache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_ICACHE_VALID
__disable_irq();
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_ICACHE_CFG_LINE_SIZE + dsize + (HAL_ICACHE_CFG_LINE_SIZE - 1)) / HAL_ICACHE_CFG_LINE_SIZE;
MInvalICacheLines((unsigned long)addr, (unsigned long)cnt);
__enable_irq();
#endif
}
/**
* @brief Locks a range of the CPU instruction cache based on address and size.
*
* This function prevents the CPU instruction cache from being updated or invalidated within a specified
* range. It ensures that the cache entries in this range remain fixed and are not replaced or
* evicted. This can be useful in scenarios where instruction stability is critical and should not be
* changed by other operations or processes.
*
* @param addr Pointer to the start address of the memory region to lock.
* @param dsize Size of the memory region to lock, in bytes.
*/
void HAL_LockICache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_ICACHE_VALID
__disable_irq();
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_ICACHE_CFG_LINE_SIZE + dsize + (HAL_ICACHE_CFG_LINE_SIZE - 1)) / HAL_ICACHE_CFG_LINE_SIZE;
MLockICacheLines((unsigned long)addr, (unsigned long)cnt);
__enable_irq();
#endif
}
/**
* @brief Unlocks a previously locked range of the CPU instruction cache based on address and size.
*
* This function allows the CPU instruction cache to be updated or invalidated within a previously locked
* range. It ensures that the cache entries in this range can now be replaced or evicted as needed,
* returning the cache operation to its normal behavior. This is useful when the critical operation
* requiring instruction stability is complete and normal cache operations need to resume.
*
* @param addr Pointer to the start address of the memory region to unlock.
* @param dsize Size of the memory region to unlock, in bytes.
*/
void HAL_UnLockICache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_ICACHE_VALID
__disable_irq();
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_ICACHE_CFG_LINE_SIZE + dsize + (HAL_ICACHE_CFG_LINE_SIZE - 1)) / HAL_ICACHE_CFG_LINE_SIZE;
MUnlockICacheLines((unsigned long)addr, (unsigned long)cnt);
__enable_irq();
#endif
}
/**
* @brief Enables the CPU data cache.
*
* This function activates the internal data cache of the CPU
* to enhance the execution speed and efficiency of data access and processing.
* It is part of the Hardware Abstraction Layer (HAL), providing an interface to manage
* hardware-specific features such as caching operations. Enabling the data cache helps
* improve system performance by reducing memory access times and minimizing CPU idle time
* during data fetches from main memory.
*/
void HAL_EnableDCache(void){
#if HAL_DCACHE_VALID
__disable_irq();
EnableDCache();
__enable_irq();
#endif
}
/**
* @brief Disables the CPU data cache.
*
* This function deactivates the internal data cache of the CPU.
* Disabling the data cache can be useful in scenarios where data caching may lead
* to consistency issues, such as during non-cache-coherent DMA operations or when
* the predictability of every data access is required. It is part of the Hardware
* Abstraction Layer (HAL), providing an interface to manage hardware-specific features.
* Disabling the data cache ensures that all data reads and writes are directly made to
* and from the main memory, which can be crucial for real-time and safety-critical applications.
*/
void HAL_DisableDCache(void){
#if HAL_DCACHE_VALID
__disable_irq();
DisableDCache();
__enable_irq();
#endif
}
/**
* @brief Invalidates the CPU data cache.
*
* This function clears the contents of the internal data cache of the CPU.
* Invalidating the cache is essential to prevent the use of stale or incorrect data
* that might remain after changes in memory. It is commonly used after direct memory
* access (DMA) operations or when hardware devices modify memory outside of the CPU's control.
* It is part of the Hardware Abstraction Layer (HAL), providing an interface to manage
* hardware-specific features such as caching operations. This operation ensures data coherency
* and consistency across the system, particularly in systems where memory is shared between the CPU
* and other hardware components.
*/
void HAL_InvalidateDCache(void){
#if HAL_DCACHE_VALID
__disable_irq();
MInvalDCache();
__enable_irq();
#endif
}
/**
* @brief Flushes the CPU data cache.
*
* This function ensures that all modified data within the CPU's internal data cache
* are written back to the main memory. Flushing the data cache is crucial before
* any operations that require up-to-date data from other processors or hardware
* that do not have cache coherency mechanisms. It is part of the Hardware
* Abstraction Layer (HAL), providing an interface to manage hardware-specific features
* such as caching operations. This operation helps maintain data coherency and
* consistency across different parts of the system, particularly in multi-core
* or multi-processor environments.
*/
void HAL_FlushDCache(void){
#if HAL_DCACHE_VALID
__disable_irq();
MFlushDCache();
__enable_irq();
#endif
}
/**
* @brief Flushes and invalidates the CPU data cache.
*
* This function ensures that all modified data within the CPU's internal data cache
* are written back to the main memory, and then invalidates the cache to remove all entries.
* This is particularly useful in scenarios where data coherence and consistency are critical,
* such as before DMA operations where peripheral devices need to access the latest data,
* or after updating firmware that changes the memory layout. It is part of the Hardware
* Abstraction Layer (HAL), providing an interface to manage hardware-specific features
* such as caching operations. Flushing and invalidating the data cache ensures that
* no stale data is used and all future data reads are done directly from the main memory.
*/
void HAL_FlushInvalidateDCache(void){
#if HAL_DCACHE_VALID
__disable_irq();
MFlushInvalDCache();
__enable_irq();
#endif
}
/**
* @brief Invalidates a range of the CPU data cache based on address and size.
*
* This function clears a specific portion of the CPU's internal data cache. By providing
* an address and the size of the area, this function ensures that any modifications in
* memory in this specified range do not use stale or outdated cache entries. This is particularly
* useful for systems where memory regions are dynamically altered or when devices not supporting
* cache coherency modify the memory. It helps in maintaining data integrity and coherency
* especially in systems involving direct memory access (DMA) operations.
*
* @param addr Pointer to the start address of the memory region to invalidate.
* @param dsize Size of the memory region to invalidate, in bytes.
*/
void HAL_InvalidateDCache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_DCACHE_VALID
__disable_irq();
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_DCACHE_CFG_LINE_SIZE + dsize + (HAL_DCACHE_CFG_LINE_SIZE - 1)) / HAL_DCACHE_CFG_LINE_SIZE;
MInvalDCacheLines((unsigned long)addr, (unsigned long)cnt);
__enable_irq();
#endif
}
/**
* @brief Flushes a range of the CPU data cache based on address and size.
*
* This function writes back all modified data within a specified range of the CPU's internal data cache
* to the main memory. This operation is crucial for ensuring data coherence in systems where other processors
* or hardware devices access the same memory region but do not share a cache coherency mechanism. It is typically
* used prior to DMA operations or when processors in a multi-processor system access shared data.
*
* @param addr Pointer to the start address of the memory region to flush.
* @param dsize Size of the memory region to flush, in bytes.
*/
void HAL_FlushDCache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_DCACHE_VALID
__disable_irq();
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_DCACHE_CFG_LINE_SIZE + dsize + (HAL_DCACHE_CFG_LINE_SIZE - 1)) / HAL_DCACHE_CFG_LINE_SIZE;
MFlushDCacheLines((unsigned long)addr, (unsigned long)cnt);
__enable_irq();
#endif
}
/**
* @brief Flushes and invalidates a range of the CPU data cache based on address and size.
*
* This function combines the actions of writing back all modified data within a specified range
* of the CPU's internal data cache to the main memory and then invalidating the cache entries.
* This ensures that no stale data remains and all future accesses to this memory range will be
* fetched directly from the main memory. This operation is particularly vital in systems with
* non-cache-coherent DMA operations or in multi-core systems where processors need to share
* up-to-date data without any inconsistencies.
*
* @param addr Pointer to the start address of the memory region to flush and invalidate.
* @param dsize Size of the memory region to flush and invalidate, in bytes.
*/
void HAL_FlushInvalidateDCache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_DCACHE_VALID
__disable_irq();
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_DCACHE_CFG_LINE_SIZE + dsize + (HAL_DCACHE_CFG_LINE_SIZE - 1)) / HAL_DCACHE_CFG_LINE_SIZE;
MFlushInvalDCacheLines((unsigned long)addr, (unsigned long)cnt);
__enable_irq();
#endif
}
/**
* @brief Locks a range of the CPU data cache based on address and size.
*
* This function prevents the CPU data cache from being updated or invalidated within a specified
* range. It ensures that the cache entries in this range remain fixed and are not replaced or
* evicted. This can be useful in scenarios where data stability is critical and should not be
* changed by other operations or processes.
*
* @param addr Pointer to the start address of the memory region to lock.
* @param dsize Size of the memory region to lock, in bytes.
*/
void HAL_LockDCache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_DCACHE_VALID
__disable_irq();
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_DCACHE_CFG_LINE_SIZE + dsize + (HAL_DCACHE_CFG_LINE_SIZE - 1)) / HAL_DCACHE_CFG_LINE_SIZE;
MLockDCacheLines((unsigned long)addr, (unsigned long)cnt);
__enable_irq();
#endif
}
/**
* @brief Unlocks a previously locked range of the CPU data cache based on address and size.
*
* This function allows the CPU data cache to be updated or invalidated within a previously locked
* range. It ensures that the cache entries in this range can now be replaced or evicted as needed,
* returning the cache operation to its normal behavior. This is useful when the critical operation
* requiring data stability is complete and normal cache operations need to resume.
*
* @param addr Pointer to the start address of the memory region to unlock.
* @param dsize Size of the memory region to unlock, in bytes.
*/
void HAL_UnLockDCache_by_Addr(uint32_t *addr, uint32_t dsize){
#if HAL_DCACHE_VALID
__disable_irq();
unsigned long cnt = 0;
cnt = ((uint32_t)addr % HAL_DCACHE_CFG_LINE_SIZE + dsize + (HAL_DCACHE_CFG_LINE_SIZE - 1)) / HAL_DCACHE_CFG_LINE_SIZE;
MUnlockDCacheLines((unsigned long)addr, (unsigned long)cnt);
__enable_irq();
#endif
}
// This function will be abandon
int range_is_cacheable(unsigned long start, unsigned long size){
return 0;
}
void unaligned_cache_line_move(unsigned char* src, unsigned char* dst, unsigned long len)
{
__disable_irq();
int i;
unsigned char* src_p = (unsigned char*) src;
unsigned char* dst_p = (unsigned char*) dst;
for (i = 0; i < len; ++i) {
*(dst_p + i) = *(src_p + i);
}
__enable_irq();
}
void dcache_clean_range(unsigned long start, unsigned long end){
uint32_t line_mask = HAL_DCACHE_CFG_LINE_SIZE - 1;
// 对start向上取整到cache line边界
unsigned long aligned_start = (start + line_mask) & (~line_mask);
// 对end向下取整到cache line边界
unsigned long aligned_end = end & (~line_mask);
__disable_irq();
// 只有当有完整的cache line需要处理时才进行操作
if (aligned_start < aligned_end) {
HAL_FlushDCache_by_Addr((uint32_t *)aligned_start, (aligned_end - aligned_start));
}
// 对不对齐的部分进行单独处理
if (start < aligned_start) {
// 处理start到aligned_start之间的数据
// 这里需要更细粒度的处理方式
}
if (end > aligned_end) {
// 处理aligned_end到end之间的数据
// 这里需要更细粒度的处理方式
}
__enable_irq();
}
void dcache_invalidate_range(unsigned long start, unsigned long end){
uint32_t line_mask = HAL_DCACHE_CFG_LINE_SIZE - 1;
// 对start向上取整到cache line边界
unsigned long aligned_start = (start + line_mask) & (~line_mask);
// 对end向下取整到cache line边界
unsigned long aligned_end = end & (~line_mask);
__disable_irq();
// 只有当有完整的cache line需要处理时才进行操作
if (aligned_start < aligned_end) {
HAL_InvalidateDCache_by_Addr((uint32_t *)aligned_start, (aligned_end - aligned_start));
}
// 对不对齐的部分进行单独处理
if (start < aligned_start) {
// 处理start到aligned_start之间的数据
// 这里需要更细粒度的处理方式
}
if (end > aligned_end) {
// 处理aligned_end到end之间的数据
// 这里需要更细粒度的处理方式
}
__enable_irq();
}
void dcache_flush_range(unsigned long start, unsigned long end){
uint32_t line_mask = HAL_DCACHE_CFG_LINE_SIZE - 1;
// 对start向上取整到cache line边界
unsigned long aligned_start = (start + line_mask) & (~line_mask);
// 对end向下取整到cache line边界
unsigned long aligned_end = end & (~line_mask);
__disable_irq();
// 只有当有完整的cache line需要处理时才进行操作
if (aligned_start < aligned_end) {
HAL_FlushDCache_by_Addr((uint32_t *)aligned_start, (aligned_end - aligned_start));
HAL_InvalidateDCache_by_Addr((uint32_t *)aligned_start, (aligned_end - aligned_start));
}
// 对不对齐的部分进行单独处理
if (start < aligned_start) {
// 处理start到aligned_start之间的数据
// 这里需要更细粒度的处理方式
}
if (end > aligned_end) {
// 处理aligned_end到end之间的数据
// 这里需要更细粒度的处理方式
}
__enable_irq();
}
void cache_dma_fast_inv_stage1(unsigned long start, unsigned long end){
unsigned long line_size;
unsigned long old_start = start;
unsigned long old_end = end;
line_size = HAL_DCACHE_CFG_LINE_SIZE;
start = start & (~(line_size - 1));
end = (end + line_size - 1) & (~(line_size - 1));
if (start == end)
return;
__disable_irq();
if (start != old_start) {
HAL_FlushDCache_by_Addr((uint32_t *)start, line_size);
}
if (end != old_end) {
HAL_FlushDCache_by_Addr((uint32_t *)(end - line_size), line_size);
}
HAL_InvalidateDCache_by_Addr((uint32_t *)start, (end - start));
__enable_irq();
}
// void cache_dma_fast_inv_stage2(unsigned long start, unsigned long end){
// }
// dcache_clean_range(buff_addr, buff_addr + blk_sz * blk_cnt);
// gm_cpu_clean_dcache_range(q->payload, q->len);
// gm_cpu_dcache_invalidate_range(q->payload, q->len);
// cache_dma_fast_inv_stage1(buff_addr, buff_addr + blk_sz * blk_cnt);
// dcache_clean_range(buff_addr, buff_addr + blk_sz * blk_cnt);
// // usually called after transferring data to memory (NOT cache-line-aligned) via DMA
void cache_dma_fast_inv_stage2(unsigned long start, unsigned long end)
{
unsigned long line_size;
unsigned long old_start = start;
unsigned long old_end = end;
static unsigned char cache_line_buf[32];
line_size = HAL_DCACHE_CFG_LINE_SIZE;
start = start & (~(line_size - 1));
end = (end + line_size - 1) & (~(line_size - 1));
if (start == end)
return;
int use_lock = 0;
// interrupt enabled, and not in interrupt context
if(start != old_start || end != old_end)
use_lock = 1;
if (use_lock) {
disable_GINT();
}
__disable_irq();
if (start != old_start) {
unaligned_cache_line_move((unsigned char*) start, cache_line_buf, old_start - start);
HAL_InvalidateDCache_by_Addr((uint32_t *)start, line_size);
unaligned_cache_line_move(cache_line_buf, (unsigned char*) start, old_start - start);
}
if (end != old_end) {
unaligned_cache_line_move((unsigned char*) old_end, cache_line_buf, end - old_end);
HAL_InvalidateDCache_by_Addr((uint32_t *)(end - line_size), line_size);
unaligned_cache_line_move(cache_line_buf, (unsigned char*) old_end, end - old_end);
}
__enable_irq();
if (use_lock) {
enable_GINT();
}
}

View File

@@ -0,0 +1,516 @@
/*
* Copyright (c) 2019 Nuclei Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed 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
*
* 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.
*/
/******************************************************************************
* @file gcc_evalsoc_ilm.ld
* @brief GNU Linker Script for Nuclei N/NX based device
* @version V1.0.0
* @date 17. Dec 2019
******************************************************************************/
OUTPUT_ARCH("riscv")
ENTRY(_start)
////////////////////////////////////////////////////////////////////////////////
/*
* R - Read-only sections.
* W - Read/write sections.
* X - Sections containing executable code.
* A - Allocated sections.
* I/L - Initialized sections.
* ! - Invert the sense of any of the following attributes.
*/
#include "memap.h"
MEMORY {
PSRAM(rwxa ) : ORIGIN = MEM_PSRAM_BASE, LENGTH = MEM_PSRAM_SIZE
FLASH(rxa!w) : ORIGIN = MEM_FLASH_BASE, LENGTH = MEM_FLASH_SIZE
SRAM(rwxa ) : ORIGIN = MEM_SRAM_BASE, LENGTH = MEM_SRAM_SIZE
ILM(rwx ) : ORIGIN = MEM_ILM_BASE, LENGTH = MEM_ILM_SIZE
DLM(rw ) : ORIGIN = MEM_DLM_BASE, LENGTH = MEM_DLM_SIZE
#if defined(MEM_IPC_BASE)
/* 共享内存 */
IPC_RAM(rwx) : ORIGIN = MEM_IPC_BASE, LENGTH = MEM_IPC_SIZE
#endif
#if defined(MEM_WFRAM_BASE)
/* 这段内存预留给WIFI使用 */
WIFI_RAM (rwx) : ORIGIN = MEM_WFRAM_BASE, LENGTH = MEM_WFRAM_SIZE
#endif
}
REGION_ALIAS("ITCM", ILM)
REGION_ALIAS("DTCM", DLM)
REGION_ALIAS("ROM", FLASH)
REGION_ALIAS("RAM", SRAM)
/* 如果不定义 MEM_WFRAM_BASE 的话, wifi ram从sram中分配 */
#if !defined(MEM_WFRAM_BASE)
REGION_ALIAS("WIFI_RAM", SRAM)
#endif
/* 如果不定义 MEM_IPC_BASE 的话, ipc shared ram从sram中分配 */
#if !defined(MEM_IPC_BASE)
REGION_ALIAS("IPC_RAM", SRAM)
#endif
#define SCATCOPY(LEN,VMA,LMA) LONG(LEN) LONG(VMA) LONG(LMA)
#define SCATLOAD(SCT) LONG(SIZEOF(SCT)) LONG(ADDR(SCT)) LONG(LOADADDR(SCT))
#define SCATZERO(SCT) LONG(SIZEOF(SCT)) LONG(ADDR(SCT))
SECTIONS {
PROVIDE(__STACK_SIZE = MEM_INTERRUPT_STACK_SIZE);
PROVIDE(__HEAP_SIZE = 512);
/* wifi 校准数据预留大小 */
PROVIDE(_lcali = MEM_WIFI_CALIBRATION_SIZE);
/* wifi 跟踪数据预留大小 */
PROVIDE(_trace_len = MEM_WIFI_TRACE_SIZE);
/* 优先将这个段放在前面, 确保wifi ram自动从sram分配时, 前面的地址给wifi使用 */
.wifi.noinit (NOLOAD):
{
. = ALIGN(4);
_wifi_ram_start = . ;
#if CONFIG_WIFI_CALI_BUF
_scali = .;
. += _lcali;
_ecali = .;
#endif
_trace_start = .;
. += _trace_len;
_trace_end = .;
_sshram = . ;
*(SHAREDRAMIPC)
*(SHAREDRAM)
_eshram = . ;
. = ALIGN(4);
_wifi_ram_end = . ;
} > WIFI_RAM
/* WIFI外设只能访问 0x20000000 - 0x20000000 + 256 * 1024这段内存 */
ASSERT ((_wifi_ram_start >= (0x20000000)), "error: wifi ram start must be greater than 0x20000000")
ASSERT ((_wifi_ram_end <= (0x20000000 + 256 * 1024)), "error: wifi ram end must be less than 0x20000000 + 256 * 1024")
.init : {
/* Default Vector Table */
. = ALIGN(4);
PROVIDE(_rom_code_start = .);
* (.vtable)
* (.init)
/* Starup Initialition Region */
. = ALIGN(4);
PROVIDE(_rom_code_end = .);
} >ROM AT>ROM
.scatab : ALIGN(4) {
/* Prev Scatter Copy/Load Table */
. = ALIGN(4);
PROVIDE(__scat_copy_base = .);
SCATLOAD(.itcm);
SCATLOAD(.dtcm);
SCATLOAD(.fast.text);
SCATLOAD(.fast.rodata);
SCATLOAD(.fast.data);
SCATLOAD(.text);
SCATLOAD(.rodata);
SCATLOAD(.data);
SCATLOAD(.shell);
SCATLOAD(.mapi);
PROVIDE(__scat_copy_last = .);
/* Scatter Zero-Fill Table */
. = ALIGN(4);
PROVIDE(__scat_zero_base = .);
SCATZERO(.dtcm.bss);
SCATZERO(.fast.bss);
SCATZERO(.bss);
PROVIDE(__scat_zero_last = .);
. = ALIGN(4);
} >ROM AT>ROM
.psram_scatab : ALIGN(4) {
/* Prev Scatter Copy/Load Table */
. = ALIGN(4);
PROVIDE(__psram_scat_copy_base = .);
SCATLOAD(.psram.text);
SCATLOAD(.psram.data);
SCATLOAD(.psram.rodata);
PROVIDE(__psram_scat_copy_last = .);
/* Scatter Zero-Fill Table */
. = ALIGN(4);
PROVIDE(__psram_scat_zero_base = .);
SCATZERO(.psram.bss);
PROVIDE(__psram_scat_zero_last = .);
. = ALIGN(4);
} >ROM AT>ROM
.psram.data : ALIGN(4) {
. = ALIGN(4);
PROVIDE(__psram_data_start = .);
* (.psram.data)
* (.psram.data.*)
*psram*.a: (.data .data.*)
. = ALIGN(4);
PROVIDE(__psram_data_end = .);
} >PSRAM AT>ROM
.psram.bss(NOLOAD): ALIGN(4) {
. = ALIGN(4);
PROVIDE(__psram_bss_start = .);
* (.psram.bss)
* (.psram.bss.*)
*psram*.a: (.sbss .sbss.* .bss .bss.*)
. = ALIGN(4);
PROVIDE(__psram_bss_end = .);
} >PSRAM
.psram.noinit(NOLOAD) : ALIGN(4) {
. = ALIGN(4);
PROVIDE(__psram_noinit_start = .);
* (.psram.noinit)
* (.psram.noinit.*)
*psram*.a: (.noinit .noinit.*)
. = ALIGN(4);
PROVIDE(__psram_noinit_end = .);
} >PSRAM
////////////////////////////////////////////////////////////////////////////
// ROM/RAM => FAST/RAM
.fast.text : ALIGN(4) {
. = ALIGN(4);
PROVIDE(_ram_code_start = .);
* (.ramcode)
* (.text.irq .text.xPortTaskSwitch .text.eclic_mtip_handler)
* (.fast_text .fast_text.*)
/* *heap.a: (.text .text.*) */
*mapi.o (.text .text.*)
PROVIDE(_ram_code_end = .);
. = ALIGN(4);
} >SRAM AT>ROM
.itcm : ALIGN(4) {
. = ALIGN(4);
PROVIDE(_itcm_code_start = .);
* (.itcm_text .itcm_text.* .itcm*)
PROVIDE(_itcm_code_end = .);
. = ALIGN(4);
} >ITCM AT>ROM
.dtcm : ALIGN(4) {
. = ALIGN(4);
* (.dtcm .dtcm.*)
. = ALIGN(4);
} >DTCM AT>ROM
.dtcm.bss (NOLOAD) : ALIGN(4) {
. = ALIGN(4);
* (.dtcm.bss .dtcm.bss*)
. = ALIGN(4);
} >DTCM
.fast.rodata : ALIGN(4) {
. = ALIGN(4);
* (.fast_rodata .fast_rodata.*)
*heap.a: (.rodata .rodata.*)
. = ALIGN(4);
} >RAM AT>ROM
.fast.data : ALIGN(4) {
. = ALIGN(4);
* (.fast_data .fast_data.*)
*heap.a: (.data .data.*)
. = ALIGN(4);
} >RAM AT>ROM
.fast.bss(NOLOAD) : ALIGN(4) {
. = ALIGN(4);
* (.fast_bss .fast_bss.*)
*heap.a: (.bss .bss.*)
. = ALIGN(4);
} >RAM AT>RAM
////////////////////////////////////////////////////////////////////////////
// ROM => ROM
.shell : ALIGN(4) {
. = ALIGN(4);
_shell_items_start = .;
KEEP(* (.shell.user))
KEEP(* (.shell.priv))
. = ALIGN(4);
} >ROM AT>ROM
.shell_command :
{
_shell_command_start = .;
KEEP (*(shellCommand))
_shell_command_end = .;
} >ROM AT>ROM
.psram.text : ALIGN(4) {
. = ALIGN(4);
PROVIDE(__psram_text_start = .);
* (.psram.text)
* (.psram.text.*)
*libmodules_lvgl.a:*(.text .text.* .stext .stext.*)
. = ALIGN(4);
PROVIDE(__psram_text_end = .);
} >PSRAM AT>ROM
.text : ALIGN(4) {
. = ALIGN(4);
PROVIDE(_rom_code2_start = .);
* (.stext .stext.*)
* (.text .text.*)
* (.gnu.linkonce.t.*)
. = ALIGN(4);
PROVIDE(_rom_code2_end = .);
} >ROM AT>ROM
#if CONFIG_LINK_CPP_RUNTIME_SECTIONS
.fini :
{
KEEP (*(SORT_NONE(.fini)))
} >ROM AT>ROM
.preinit_array :
{
PROVIDE_HIDDEN (__preinit_array_start = .);
KEEP (*(.preinit_array))
PROVIDE_HIDDEN (__preinit_array_end = .);
} >ROM AT>ROM
.init_array :
{
PROVIDE_HIDDEN (__init_array_start = .);
KEEP (*(SORT_BY_INIT_PRIORITY(.init_array.*) SORT_BY_INIT_PRIORITY(.ctors.*)))
KEEP (*(.init_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .ctors))
PROVIDE_HIDDEN (__init_array_end = .);
} >ROM AT>ROM
.fini_array :
{
PROVIDE_HIDDEN (__fini_array_start = .);
KEEP (*(SORT_BY_INIT_PRIORITY(.fini_array.*) SORT_BY_INIT_PRIORITY(.dtors.*)))
KEEP (*(.fini_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .dtors))
PROVIDE_HIDDEN (__fini_array_end = .);
} >ROM AT>ROM
.ctors :
{
/* gcc uses crtbegin.o to find the start of
* the constructors, so we make sure it is
* first. Because this is a wildcard, it
* doesn't matter if the user does not
* actually link against crtbegin.o; the
* linker won't look for a file to match a
* wildcard. The wildcard also means that it
* doesn't matter which directory crtbegin.o
* is in.
*/
KEEP (*crtbegin.o(.ctors))
KEEP (*crtbegin?.o(.ctors))
/* We don't want to include the .ctor section from
* the crtend.o file until after the sorted ctors.
* The .ctor section from the crtend file contains the
* end of ctors marker and it must be last
*/
KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .ctors))
KEEP (*(SORT(.ctors.*)))
KEEP (*(.ctors))
} >ROM AT>ROM
.dtors :
{
KEEP (*crtbegin.o(.dtors))
KEEP (*crtbegin?.o(.dtors))
KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .dtors))
KEEP (*(SORT(.dtors.*)))
KEEP (*(.dtors))
} >ROM AT>ROM
/* C++ 异常处理支持 */
.eh_frame_hdr :
{
*(.eh_frame_hdr)
*(.eh_frame_entry .eh_frame_entry.*)
} >ROM AT>ROM
.eh_frame :
{
. = ALIGN(4);
PROVIDE(__eh_frame = .);
KEEP(*(.eh_frame))
/**
* As we are not linking with crtend.o, which includes the CIE terminator
* (see __FRAME_END__ in libgcc sources), it is manually provided here.
*/
LONG(0)
} >ROM AT>ROM
.gcc_except_table :
{
*(.gcc_except_table .gcc_except_table.*)
} >ROM AT>ROM
/* C++ 标准库静态数据 */
.rodata.cst4 :
{
*(.rodata.cst4)
} >ROM AT>ROM
.rodata.cst8 :
{
*(.rodata.cst8)
} >ROM AT>ROM
#endif // CONFIG_LINK_OPTION_NONE_SPECS
.psram.rodata : ALIGN(4) {
. = ALIGN(4);
* (.psram.rodata)
* (.psram.rodata.*)
. = ALIGN(4);
} >PSRAM AT>ROM
.rodata : ALIGN(4) {
. = ALIGN(4);
* (.rodata .rodata.*)
* (.strdat)
. = ALIGN(4);
} >ROM AT>ROM
.lisaui_apps : {
. = ALIGN(4);
__lisaui_apps_start = .;
KEEP (*(.lisaui*))
. = ALIGN(4);
__lisaui_apps_end = .;
} >ROM AT>ROM
////////////////////////////////////////////////////////////////////////////
// ROM => RAM
.mapi : ALIGN(4) {
. = ALIGN(4);
PROVIDE_HIDDEN(__mod_stdc = .);
KEEP(* (SORT(.mod.0.*)))
PROVIDE_HIDDEN(__mod_rtos = .);
KEEP(* (SORT(.mod.?.*)))
PROVIDE_HIDDEN(__mod_ends = .);
. = ALIGN(4);
} >RAM AT>ROM
.trace : ALIGN(4) {
. = ALIGN(4);
_trace_start = .;
KEEP(*(TRACE))
_trace_end = .;
. = ALIGN(4);
} >RAM AT>ROM
.data : ALIGN(8) {
. = ALIGN(8);
* (.data .data.*)
* (.gnu.linkonce.d.*)
. = ALIGN(8);
PROVIDE(__global_pointer$ = . + 0x800);
* (.sdata .sdata.*)
* (.gnu.linkonce.s.*)
. = ALIGN(8);
* (.rdata .rdata.*)
* (.gnu.linkonce.r.*)
* (.srodata .srodata.*)
} >RAM AT>ROM
#if defined(MEM_IPC_BASE)
/* ipc shared RAM */
.ipc.shared (NOLOAD):
{
_ipcshram = . ;
*(SHAREDRAM_AMP_IPC_ENV)
*(SHAREDRAM_AMP_IPC)
*(SORT(.ipc.*))
_eipcshram = . ;
} > IPC_RAM
#endif
PROVIDE(__tls_base = .);
.psram.nocache_heap ORIGIN(PSRAM) (NOLOAD):{
. = ALIGN(0x100000);
PROVIDE(__psram_nocache_heap_start = .);
* (.psram.nocache_heap)
. = ALIGN(4);
PROVIDE(__psram_nocache_heap_end = .);
} >PSRAM
////////////////////////////////////////////////////////////////////////////
// ZERO => RAM
.bss(NOLOAD) : ALIGN(8) {
. = ALIGN(8);
* (.sbss .sbss.*)
* (.gnu.linkonce.sb.*)
* (.bss .bss.*)
* (.gnu.linkonce.b.*)
* (COMMON)
. = ALIGN(4);
} >RAM AT>RAM
.noinit (NOLOAD): ALIGN(4) {
. = ALIGN(4);
* (.noinit)
* (.noinit.*)
. = ALIGN(4);
} >RAM
////////////////////////////////////////////////////////////////////////////
// ROM => ROM
.stub : {
KEEP (* (.stub))
} >ROM AT>ROM
PROVIDE( _end = . );
PROVIDE( end = . );
////////////////////////////////////////////////////////////////////////////
///* RTOS Heap Region (8 bytes aligned at least) */
//.rtosheap(NOLOAD) : ALIGN(16) {
// . = ALIGN(ORIGIN(RAM) + LENGTH(RAM) - __HEAP_SIZE - __STACK_SIZE, 16);
//} >RAM AT>RAM
//PROVIDE(__vmaof_osheap = ADDR(.rtosheap));
//PROVIDE(__lenof_osheap = SIZEOF(.rtosheap));
/* Nuclei C Runtime Library requirements:
* 1. heap need to be align at 16 bytes
* 2. __heap_start and __heap_end symbol need to be defined
* 3. reserved at least __HEAP_SIZE space for heap
* 4. reserved at least __STACK_SIZE space for stack */
.heapstack(NOLOAD) : ALIGN(16) {
. = ALIGN(16);
PROVIDE(__heap_start = .);
. += __HEAP_SIZE;
. = ALIGN(16);
PROVIDE(__heap_end = .);
PROVIDE(_sstack = .);
PROVIDE(__StackLimit = .);
. += __STACK_SIZE;
. = ALIGN(16);
PROVIDE(__StackTop = .);
PROVIDE(_estack = .);
} >RAM AT>RAM
}

View File

@@ -0,0 +1,32 @@
#ifndef __ARCS_MEMAP_HEADER__
#define __ARCS_MEMAP_HEADER__
#define MEM_SRAM_BASE 0x20050000
#define MEM_SRAM_SIZE (384 * 1024)
#define MEM_PSRAM_BASE 0x28000000
#define MEM_PSRAM_SIZE (16 * 1024 * 1024)
#ifndef CONFIG_BOOT_FLASH_SIZE
#warning "BOOT_FLASH_SIZE is not defined"
#define CONFIG_BOOT_FLASH_SIZE (8 * 1024)
#endif
#define MEM_FLASH_BASE (CONFIG_MEM_FLASH_BASE)
#define MEM_FLASH_SIZE (CONFIG_BOOT_FLASH_SIZE)
#define MEM_WFRAM_BASE 0x20000000
#define MEM_WFRAM_SIZE (256 * 1024)
#define MEM_ILM_BASE 0x00080000
#define MEM_ILM_SIZE (16 * 1024)
#define MEM_DLM_BASE 0x00100000
#define MEM_DLM_SIZE (8 * 1024)
#define MEM_WIFI_CALIBRATION_SIZE (16 * 1024)
#define MEM_WIFI_TRACE_SIZE (8 * 1024)
#define MEM_INTERRUPT_STACK_SIZE (4 * 1024)
#endif