1 /*
2  * Copyright (c) 2006-2022, RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author            Notes
8  * 2022-07-15     Emuzit            first version
9  */
10 #include <rthw.h>
11 #include <drivers/dev_pin.h>
12 #include "board.h"
13 #include "ch56x_pfic.h"
14 #include "ch56x_uart.h"
15 
16 extern rt_uint32_t rt_thread_switch_interrupt_flag;
17 
18 /* FIXME: Use rt_interrupt_leave_hook to trigger SWI for context switch.
19  * Hopefully there's a standard riscv way instead of this clumsy patch.
20 */
irq_leave_hook(void)21 static void irq_leave_hook(void)
22 {
23     if (rt_thread_switch_interrupt_flag)
24     {
25         pfic_swi_pendset();
26     }
27 }
28 
29 /*
30  * _start -> handle_reset
31  * src/components.c/entry() -> rtthread_startup()
32  * libcpu/risc-v/common/context_gcc.S/rt_hw_interrupt_disable
33  */
rt_hw_board_init()34 void rt_hw_board_init()
35 {
36     volatile struct pfic_registers *pfic = (void *)PFIC_REG_BASE;
37 
38     /* disable all pfic interrupts */
39     pfic->IRER[0] = PFIC_IREG1_MASK;
40     pfic->IRER[1] = PFIC_IREG2_MASK;
41 
42     /* disable hwstack push/pop & nested interrupt */
43     pfic->CFGR = cfgr_nest_hwstk(CFGR_NESTCTRL_DISABLE | CFGR_HWSTKCTRL_DISABLE);
44 
45     /* disable clock input for all peripheral devices */
46     sys_slp_clk_off0(0xff, SYS_SLP_CLK_OFF);
47     sys_slp_clk_off1(0xff, SYS_SLP_CLK_OFF);
48     sys_clk_off_by_irqn(ETH_IRQn, SYS_SLP_CLK_OFF);
49     sys_clk_off_by_irqn(ECDC_IRQn, SYS_SLP_CLK_OFF);
50 
51     /* setup HCLK for systick & peripheral devices */
52     sys_hclk_set(SYS_HCLK_FREQ);
53 
54     /* set SysTick to RT_TICK_PER_SECOND with current HCLK */
55     systick_init(0);
56 
57     /* Note: keep MSTATUS_MIE disabled to prevent SysTick from processing
58      * thread scheduling, which may not be ready upon 1st systick irq.
59      * MSTATUS_MIE will be set when rt_system_scheduler_start() starts
60      * the first thread and copies mstatus from stack_frame.
61      */
62 
63 #ifdef RT_USING_HEAP
64     rt_system_heap_init((void *)HEAP_BEGIN, (void *)HEAP_END);
65 #endif
66 
67 #ifdef RT_USING_COMPONENTS_INIT
68     rt_components_board_init();
69 #endif
70 
71 #ifdef RT_USING_CONSOLE
72     rt_hw_uart_init();
73     rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
74 #endif
75 
76     rt_interrupt_leave_sethook(irq_leave_hook);
77 }
78