diff --git a/bsp/loongson/ls2k0300/.gitignore b/bsp/loongson/ls2k0300/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..96628491a066887807aae827297df65f6783466b --- /dev/null +++ b/bsp/loongson/ls2k0300/.gitignore @@ -0,0 +1,10 @@ +build/ +*.o +*.o.d +*.elf +*.bin +*.map +*.asm +.sconsign.dblite +__pycache__/ +.config diff --git a/bsp/loongson/ls2k0300/Kconfig b/bsp/loongson/ls2k0300/Kconfig new file mode 100644 index 0000000000000000000000000000000000000000..4eaec84d0fa7db336a75f15d97d7a2bf92641bfa --- /dev/null +++ b/bsp/loongson/ls2k0300/Kconfig @@ -0,0 +1,42 @@ +mainmenu "RT-Thread Configuration" + +BSP_DIR := . +RTT_DIR := ../../.. +PKGS_DIR := packages + +source "$(RTT_DIR)/Kconfig" +osource "$(PKGS_DIR)/Kconfig" + +config SOC_LS2K0300 + bool + select ARCH_LOONGARCH64 + select RT_USING_COMPONENTS_INIT + select RT_USING_USER_MAIN + select RT_USING_DEVICE + default y + +if RT_USING_DEVICE +config BSP_USING_UART0 + bool "Enable UART0" + default y + +config BSP_USING_UART1 + bool "Enable UART1" + default n + +config BSP_USING_UART_IRQ + bool "Enable UART RX interrupt" + default y + +config BSP_USING_GPIO + bool "Enable GPIO" + default y + +config BSP_USING_RTC + bool "Enable RTC" + default y + +config BSP_USING_ICU + bool "Enable on-chip interrupt controller (ICU)" + default y +endif diff --git a/bsp/loongson/ls2k0300/README.md b/bsp/loongson/ls2k0300/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c3d0795b4ed957d0546568237806303c7463f36a --- /dev/null +++ b/bsp/loongson/ls2k0300/README.md @@ -0,0 +1,190 @@ +# Loongson 2K0300 Pioneer Board Support Package + +RT-Thread BSP for the Loongson 2K0300 Pioneer (先锋派, LS2K300-PAI) board, +together with a new LoongArch64 architecture port in `libcpu/loongarch`. + +## 1. Introduction + +The 2K0300 integrates a single LoongArch LA264 core. Its ISA is **not** +binary compatible with the MIPS64 based 2K1000, so this BSP ships a new +architecture port instead of reusing `libcpu/mips`. + +| Item | Description | +| -- | -- | +| SoC | Loongson 2K0300 | +| CPU | LA264, LoongArch64, single core, dual issue, 1GHz | +| L1 cache | 32KB I-Cache / 32KB D-Cache | +| L2 cache | 512KB | +| Memory | 512MB DDR4-1600 | +| Storage | 8GB eMMC + 2MB SPI NOR (U-Boot) | +| Ethernet | 1x Gigabit (YT8511H PHY) | +| Debug UART | UART0, 115200 8N1, Type-C (CH340K) | +| USB | 4x USB2.0 host + 1x OTG | +| Display | RGB LCD, 24bit, up to 1080P | +| Expansion | 40-pin Raspberry Pi compatible header | +| Power | Type-C 5V/2A, 85mm x 56mm | + +Board images are taken from the vendor board package, copyright Loongson. + +### 1.1 Block diagram + +![block diagram](figures/block_diagram.jpg) + +### 1.2 Board interfaces + +![board interfaces](figures/board_interfaces.jpg) + +### 1.3 Pin multiplexing + +![pin mux](figures/pin_mux.png) + +## 2. Compile + +The official Loongson toolchain is Linux hosted (`loongarch64-linux-gnu-`), +the firmware is built as a freestanding image with `-nostdlib`: + +```bash +export RTT_EXEC_PATH=/opt/ls_2k0300_env/loongson-gnu-toolchain-8.3-x86_64-loongarch64-linux-gnu-rc1.6/bin +cd bsp/loongson/ls2k0300 +scons -j8 +``` + +Outputs: + +| File | Description | +| -- | -- | +| `rtthread.elf` | ELF image, can be loaded with U-Boot `bootelf` | +| `rtthread.bin` | raw binary, can be loaded with U-Boot `go` or XMODEM | +| `rtthread.map` | link map | + +The image is linked at `0x9000000000200000`, the cached direct mapping window +of physical address `0x00200000` set up by the vendor U-Boot. + +Kconfig options: `BSP_USING_UART0`, `BSP_USING_UART1`, `BSP_USING_UART_IRQ`, +`BSP_USING_ICU`, and the compile time `BSP_CONSOLE_BAUD` (default 115200) used +to derive the real UART input clock. + +## 3. Run + +### 3.1 Connect + +Debug UART: Type-C, 115200 8N1, no flow control. +Ethernet: connect to the same subnet as the TFTP server when using TFTP. + +### 3.2 Enter U-Boot + +Press `c` during the autoboot countdown (`m` enters the vendor boot menu). +The factory `bootdelay` is 0; set it to 3 once with +`setenv bootdelay 3; saveenv` so the console stays reachable. + +### 3.3 Load over TFTP + +``` +setenv ipaddr 192.168.1.10 +setenv serverip 192.168.1.100 +tftpboot 0x9000000000200000 rtthread.bin +go 0x9000000000200000 +``` + +or, when `bootelf` is available: + +``` +tftpboot 0x9000000000200000 rtthread.elf +bootelf 0x9000000000200000 +``` + +### 3.4 Load over serial (XMODEM) + +``` +loadx 0x9000000000200000 +``` + +Send `rtthread.bin` with any XMODEM capable terminal, then `go`. + +### 3.5 Install to eMMC and boot automatically + +``` +loadx 0x9000000000200000 +ext4write mmc 0:1 0x9000000000200000 /boot/rtthread.bin +setenv bootcmd 'ext4load mmc 0:${syspart} 0x9000000000200000 /boot/rtthread.bin; go 0x9000000000200000' +saveenv +reset +``` + +Every reset then boots RT-Thread while `c` still opens the U-Boot console. +Note this U-Boot has **no `run` command**, the full command must be stored in +`bootcmd`. + +### 3.6 Restore Linux + +``` +setenv bootcmd 'setenv bootargs ${bootargs} root=/dev/mmcblk0p${syspart} mtdparts=${mtdparts} fbcon=rotate:${rotate} panel=${panel};sf probe;sf read ${fdt_addr} 0xF0000 ${fdt_size};ext4load mmc 0:${syspart} ${loadaddr} /boot/uImage;bootm' +saveenv +``` + +## 4. msh commands + +`help`, `version`, `ps`, `list thread`, `free`, `list timer`, `list device`, +`reboot`, `clear`. + +`reboot` writes the PMC reset register (`0x16124000` bit 0), the same one the +Linux `syscon-reboot` node uses. + +## 5. Supported peripherals + +| Driver | Status | Note | +| -- | -- | -- | +| UART | Yes | UART0 console, optional UART1, verified on board | +| Interrupt controller | Yes | on-chip ICU, 64 sources, cascaded on HWI2, verified | +| System tick | Yes | LoongArch constant timer, 100MHz, verified | +| Reset | Yes | PMC register, `reboot` command | +| GPIO | Yes | 106 pins, 16 per group, input/output and edge/level interrupts verified; no software controllable pull | +| GMAC | Planned | DesignWare 3.70a + YT8511H | +| SPI / I2C / CAN-FD | Planned | - | +| RTC | Yes | on-chip RTC, `date` command, keeps counting across reset | +| ADC / PWM | Planned | - | + +## 6. Implementation notes + +See [docs/porting.md](docs/porting.md) (Chinese) for details. The most important +points: + +1. the vector table needs **128 entries**, CPU interrupts use + `EENTRY + (0x40 + irq) * 0x40`; +2. 16550 registers must be accessed **byte wise**, a 32bit access to `LSR` + (offset 5) raises an address alignment exception; +3. the ICU route byte is `(1 << (line + 4)) | core` with + `line = parent irq - 2`, i.e. `0x41` for HWI2; +4. the UART input clock is derived from the divisor left by U-Boot instead of + being hardcoded; +5. the linker script keeps `.rti_fn*` and `FSymTab`, otherwise + `--gc-sections` drops `finsh_system_init()` and the msh commands. + +## 7. Hardware validation + +Validated on a 2K0300 Pioneer board (512MB DDR4, U-Boot 2022.04): + +* console output and `msh` work, the timer tick is exactly 1000 per second; +* `ps`, `free`, `list timer` report sane values; +* `reboot` resets the SoC and returns to RT-Thread. + +The architecture layer was also validated under QEMU `loongarch64 virt` +(timer interrupt and round robin scheduling of three threads). + +## 8. References + +| Resource | Link | +| -- | -- | +| Loongson 2K0300 product page | | +| open-loongarch 2K0300 docs | | +| open-loongarch U-Boot | | +| open-loongarch Linux 5.10 | | +| open-loongarch build system | | +| LoongArch architecture docs | | +| RT-Thread | | +| RT-Thread documentation | | + +The vendor board package (`广东龙芯2K300先锋派-v1.0`) contains the schematic, +user manual, chip manual, cross toolchain and a prepared Ubuntu VM; read +`06-用户手册/广东龙芯2K0300先锋派快速使用指南` and +`07-芯片手册/2K0300引脚复用配置与中断分配` first. diff --git a/bsp/loongson/ls2k0300/README_zh.md b/bsp/loongson/ls2k0300/README_zh.md new file mode 100644 index 0000000000000000000000000000000000000000..b185e391b1e1fcf95518dcb2349d9c712b8a411c --- /dev/null +++ b/bsp/loongson/ls2k0300/README_zh.md @@ -0,0 +1,393 @@ +# ls2k0300 板级支持包说明 + +> 龙芯 2K0300 先锋派(LS2K300-PAI)的 RT-Thread BSP,配套 LoongArch64 架构移植层 +> `libcpu/loongarch`。 + +## 目录 + +- [1. 简介](#1-简介) +- [2. 硬件资源](#2-硬件资源) +- [3. 目录结构](#3-目录结构) +- [4. 编译说明](#4-编译说明) +- [5. 运行](#5-运行) +- [6. msh 命令](#6-msh-命令) +- [7. 驱动支持情况](#7-驱动支持情况) +- [8. 实现要点](#8-实现要点) +- [9. 常见问题](#9-常见问题) +- [10. 参考资料](#10-参考资料) +- [11. 联系人信息](#11-联系人信息) + +## 1. 简介 + +龙芯 2K0300 先锋派是面向工业控制、网关、教育实验等场景的低成本开发板, +板卡尺寸与树莓派 4B 兼容,40PIN 排针定义也兼容树莓派。SoC 采用 LoongArch +架构的 LA264 处理器核,**与 2K1000(MIPS64)不二进制兼容**,因此本 BSP 同时 +引入了 `libcpu/loongarch` 架构移植层。 + +> 图片来自「广东龙芯 2K0300 先锋派」随板资料包,版权归广东龙芯中科所有。 + +## 2. 硬件资源 + +| 项目 | 描述 | +| -- | -- | +| SoC | 龙芯 2K0300 | +| CPU | LA264,LoongArch64,单核,双发射,10 级流水,1GHz | +| 一级缓存 | 32KB I-Cache / 32KB D-Cache | +| 二级缓存 | 512KB | +| 内存 | 512MB DDR4-1600 | +| 存储 | 8GB eMMC + 2MB SPI NOR Flash(存放 U-Boot) | +| 网络 | 1 路千兆以太网(YT8511H PHY) | +| 调试串口 | UART0,115200 8N1,Type-C 接口(CH340K) | +| USB | 4 路 USB2.0 HOST + 1 路 OTG | +| 显示 | RGB LCD,24 位色,最大 1080P | +| 音频 | 3.5mm 耳机/录音接口(ES8388) | +| 扩展 | 40PIN(可复用 5 路 UART / 2 路 I2C / 3 路 SPI / 4 路 CAN / 4 路 PWM) | +| 其他 | TF 卡、12 位 ADC(4 通道)、RTC、看门狗、JTAG | +| 供电 | Type-C,5V/2A | +| 尺寸 | 85mm × 56mm | + +### 2.1 功能框图 + +![功能框图](figures/block_diagram.jpg) + +### 2.2 硬件接口 + +![硬件接口图](figures/board_interfaces.jpg) + +### 2.3 引脚复用 + +![引脚复用图](figures/pin_mux.png) + +完整原理图、引脚复用与中断分配表见随板资料包 `01-原理图`、`07-芯片手册`。 + +## 3. 目录结构 + +``` +ls2k0300 +├── applications # 应用入口 +│ ├── main.c +│ └── SConscript +├── drivers # 板级驱动 +│ ├── board.c # 板级初始化、复位 +│ ├── drv_uart.c # 16550 兼容串口(控制台) +│ ├── interrupt.c # 2K0300 中断控制器(ICU) +│ ├── board.h / drv_uart.h / interrupt.h +│ └── ls2k0300.h # 寄存器定义 +├── docs +│ └── porting.md # 架构/驱动移植说明 +├── figures # 框图、接口图、引脚复用图 +├── Kconfig +├── SConscript +├── SConstruct +├── ls2k0300.lds # 链接脚本 +├── rtconfig.h +├── rtconfig.py +├── README.md +└── README_zh.md +``` + +架构层位于仓库根目录的 `libcpu/loongarch`: + +``` +libcpu/loongarch +├── common # 异常向量、trap、上下文切换、cache、ISR 表 +└── la264 # 启动代码、常量定时器 +``` + +## 4. 编译说明 + +### 4.1 工具链 + +龙芯官方提供的是 **Linux 版交叉工具链**(`loongarch64-linux-gnu-`),本 BSP 用 +`-nostdlib` 方式编译裸机固件,不依赖 glibc 运行时。 + +获取方式: + +1. 随板资料包 `05-交叉工具链/loongson-gnu-toolchain-8.3-x86_64-loongarch64-linux-gnu-rc1.3-1-250701.tar.xz`; +2. 或从 open-loongarch 组织的构建仓库获取(见[参考资料](#10-参考资料))。 + +解压后设置路径(默认值见 `rtconfig.py`): + +```bash +export RTT_EXEC_PATH=/opt/ls_2k0300_env/loongson-gnu-toolchain-8.3-x86_64-loongarch64-linux-gnu-rc1.6/bin +``` + +> 工具链是 glibc 版,和 RT-Thread 自带的 `sys/select.h` 存在头文件冲突,BSP 已在 +> `libcpu/loongarch/common/include/sys/select.h` 提供兼容实现,详见 +> [docs/porting.md](docs/porting.md)。 + +### 4.2 编译 + +在 BSP 目录下执行: + +```bash +cd bsp/loongson/ls2k0300 +scons -j8 +``` + +产物: + +| 文件 | 说明 | +| -- | -- | +| `rtthread.elf` | ELF 固件,可用 U-Boot `bootelf` 加载 | +| `rtthread.bin` | 纯二进制固件,可用 U-Boot `go` 或 XMODEM 加载 | +| `rtthread.map` | 链接映射表 | + +也可以使用 RT-Thread env 工具:在 BSP 目录执行 `scons` 或 `scons --menuconfig` +配置 `BSP_USING_UART0/1`、`BSP_USING_UART_IRQ`、`BSP_USING_ICU` 等选项。 + +镜像链接在 `0x9000000000200000`(U-Boot 建立的 cached 直接映射窗口中的物理 +2MB 处),入口为 `_start`。 + +### 4.3 编译选项说明 + +| 选项 | 默认 | 说明 | +| -- | -- | -- | +| `BSP_USING_UART0` | y | UART0 作为控制台 | +| `BSP_USING_UART1` | n | 可选第二路串口 | +| `BSP_USING_UART_IRQ` | y | 串口接收中断(关闭后只能轮询输出,msh 无输入) | +| `BSP_USING_ICU` | y | 片内中断控制器(关闭后无任何外设中断) | +| `BSP_CONSOLE_BAUD` | 115200 | 编译期定义,用于反推 UART 时钟 | + +## 5. 运行 + +### 5.1 硬件连接 + +1. 用 Type-C 线连接板载调试串口(CH340K),电脑端会出现一个 USB 串口; +2. 串口参数:**115200 8N1,无流控**; +3. 如需网络加载,用网线连接板载千兆网口,保证与 TFTP 服务器同网段; +4. 上电,电源灯亮。 + +### 5.2 进入 U-Boot + +U-Boot 打印: + +``` +************************** Notice ************************** +Press c to enter u-boot console, m to enter boot menu +************************************************************ +Autoboot in 3 seconds +``` + +在倒计时内按 `c` 进入 U-Boot 命令行(`=>`),按 `m` 进入厂家 boot menu。 + +> 出厂 `bootdelay` 是 0,几乎无法人工中断。本 BSP 验证时已把 `bootdelay` 改为 3, +> 如果被改回 0,可在 U-Boot 下执行 `setenv bootdelay 3; saveenv`。 + +### 5.3 方式一:TFTP 加载(推荐有网络时) + +U-Boot 下: + +``` +setenv ipaddr 192.168.1.10 +setenv serverip 192.168.1.100 +tftpboot 0x9000000000200000 rtthread.bin +go 0x9000000000200000 +``` + +也可加载 ELF(U-Boot 支持 `bootelf` 时): + +``` +tftpboot 0x9000000000200000 rtthread.elf +bootelf 0x9000000000200000 +``` + +### 5.4 方式二:XMODEM 串口加载(无网络) + +U-Boot 下: + +``` +loadx 0x9000000000200000 +``` + +然后用串口工具(如 SecureCRT 的 XMODEM 传输)发送 `rtthread.bin`。传输完成后: + +``` +go 0x9000000000200000 +``` + +### 5.5 方式三:固化到 eMMC,开机自动进入 RT-Thread(推荐) + +把固件放到 eMMC 的 `/boot/rtthread.bin`,并修改 U-Boot 启动命令: + +``` +loadx 0x9000000000200000 +ext4write mmc 0:1 0x9000000000200000 /boot/rtthread.bin <字节数> +setenv bootcmd 'ext4load mmc 0:${syspart} 0x9000000000200000 /boot/rtthread.bin; go 0x9000000000200000' +saveenv +reset +``` + +之后每次上电/复位: + +``` +Autoboot in 3 seconds +86888 bytes read in 4 ms (20.7 MiB/s) +## Starting application at 0x9000000000200000 ... + + \ | / +- RT - Thread Operating System + / | \ 5.4.0 build ... +Hello, Loongson 2K0300 Pioneer! +RT-Thread 5.4.0, tick 1000 Hz +msh > +``` + +> `<字节数>` 用 `ls -l rtthread.bin` 查看,十六进制(例如 `0x15368`)。 +> 这个 U-Boot **没有 `run` 命令**,`bootcmd` 必须写完整命令,不能写 `run xxx`。 + +### 5.6 恢复 Linux + +进入 U-Boot 后执行原始启动命令: + +``` +setenv bootargs ${bootargs} root=/dev/mmcblk0p${syspart} mtdparts=${mtdparts} fbcon=rotate:${rotate} panel=${panel};sf probe;sf read ${fdt_addr} 0xF0000 ${fdt_size};ext4load mmc 0:${syspart} ${loadaddr} /boot/uImage;bootm +``` + +或永久改回 Linux: + +``` +setenv bootcmd 'setenv bootargs ${bootargs} root=/dev/mmcblk0p${syspart} mtdparts=${mtdparts} fbcon=rotate:${rotate} panel=${panel};sf probe;sf read ${fdt_addr} 0xF0000 ${fdt_size};ext4load mmc 0:${syspart} ${loadaddr} /boot/uImage;bootm' +saveenv +``` + +## 6. msh 命令 + +启动后串口出现 `msh >`,常用命令: + +| 命令 | 说明 | +| -- | -- | +| `help` | 列出所有命令 | +| `version` | 显示 RT-Thread 版本 | +| `ps` / `list thread` | 查看线程 | +| `free` | 查看堆使用 | +| `list timer` | 查看定时器 | +| `list device` | 查看设备 | +| `reboot` | 复位 CPU(写 PMC 寄存器,重新加载固件) | +| `pin_mode` / `pin_write` / `pin_read` | GPIO 调试 | +| `pin_irq_test ` | GPIO 中断自测(两脚短接) | +| `date` / `date ` | 读取/设置 RTC 时间 | +| `clear` | 清屏 | + +示例输出(实测): + +``` +msh >ps +thread pri status sp stack size max used left tick error +tshell 20 running 0x00000240 0x00002000 18% 0x00000008 OK +tidle0 31 ready 0x00000218 0x00001000 26% 0x00000019 OK + +msh >free +total : 33554272 +used : 11488 +available: 33542784 +``` + +## 7. 驱动支持情况 + +| 驱动 | 支持情况 | 备注 | +| -- | -- | -- | +| UART | 支持 | UART0 控制台,UART1 可选,115200 8N1,已上板验证 | +| 中断控制器 | 支持 | 2K0300 ICU,64 个中断源,级联到 CPU HWI2,已上板验证 | +| 系统节拍 | 支持 | LoongArch 常量定时器,100MHz,实测精确 | +| 复位 | 支持 | PMC `0x16124000` bit0,`msh` 下 `reboot` | +| GPIO / PIN | 支持 | 106 个引脚,16 个一组;输入/输出、边沿/电平中断实测通过;硬件无软件可配上下拉 | +| GMAC | 规划中 | DesignWare 3.70a + YT8511H | +| SPI / I2C / CAN-FD | 规划中 | - | +| RTC | 支持 | 片内 RTC,`date` 命令读写,复位后继续走时(已上板验证) | +| ADC / PWM | 规划中 | - | + +## 8. 实现要点 + +完整说明见 [docs/porting.md](docs/porting.md),这里列出最容易踩坑的几点: + +1. **异常向量表是 128 项**:异常向量号是 `Ecode`(0-63),CPU 中断向量号是 + `0x40 + irq`(0x40-0x4c),所以 `EENTRY` 指向的表需要 8KB; +2. **16550 寄存器按字节访问**:32 位访问 `LSR`(偏移 5)会触发地址非对齐异常; +3. **ICU 路由字节**:`(1 << (line + 4)) | core`,`line = 父中断号 - 2`, + 级联到 CPU 中断 4(HWI2)时为 `0x41`; +4. **UART 时钟不硬编码**:从 U-Boot 留下的分频器反推(`divisor × 16 × 115200`), + 避免不同批次板卡晶振差异导致乱码; +5. **链接脚本必须保留 `.rti_fn*` 和 `FSymTab`**,否则 `--gc-sections` 会回收 + `finsh_system_init()` 和 msh 命令表。 + +## 9. 常见问题 + +### 9.1 `go` 之后串口没有任何输出 + +1. 确认镜像加载地址正确: + + ``` + md.l 0x9000000000200000 4 + ``` + + 前两个字应为 `1c000623 02c00063`(`_start` 的前两条指令)。 + +2. 确认 U-Boot 的 `go` 能正常跳转,可尝试 `bootelf`; +3. 确认使用的是 UART0 调试口(U-Boot 控制台所在串口)。 + +### 9.2 输出乱码 + +波特率不匹配。本 BSP 会从 U-Boot 的分频器反推时钟,正常不会出现;如果乱码: + +- 确认 U-Boot 控制台也是 115200; +- 确认没有在 U-Boot 里手动改过 UART 寄存器(例如打开 DLAB 后继续打印会把 + 分频器写坏,此时只能复位恢复)。 + +### 9.3 `msh >` 出现但键盘无输入 + +说明串口输出和定时器正常,问题在接收中断: + +1. 检查 `BSP_USING_UART_IRQ`、`BSP_USING_ICU` 是否为 y; +2. 检查 ICU 路由字节是否为 `0x41`(见第 8 节); +3. 检查 UART 的 `IER.RDI` 是否使能。 + +### 9.4 tick 变快或变慢 10 倍 + +常量定时器频率不对,修改 `libcpu/loongarch/la264/timer.c` 的 +`LOONGARCH_TIMER_FREQ`: + +- tick 每秒涨约 10000 → 改成 `1000000000UL`; +- tick 每秒涨约 100 → 改成 `10000000UL`。 + +### 9.5 复位后还是进 Linux + +U-Boot 的 `bootcmd` 仍是启动 Linux。按 5.5 节修改;`bootdelay` 为 0 时先在 +U-Boot 里改回 3。 + +## 10. 参考资料 + +### 10.1 官方资料 + +| 资料 | 链接 | +| -- | -- | +| 龙芯 2K0300 产品页 | | +| open-loongarch 2K0300 文档仓库 | | +| open-loongarch U-Boot | | +| open-loongarch Linux 5.10 | | +| open-loongarch 构建工程 | | +| LoongArch 架构文档 | | +| RT-Thread 官网 | | +| RT-Thread 文档中心 | | + +### 10.2 随板资料包 + +广东龙芯 2K0300 先锋派资料包(`广东龙芯2K300先锋派-v1.0`)包含: + +| 目录 | 内容 | +| -- | -- | +| `01-原理图` | 原理图 PDF、DXF、功能框图、接口图、引脚复用图 | +| `03-内核` | Linux 5.10 内核源码与镜像 | +| `05-交叉工具链` | `loongson-gnu-toolchain-8.3` LoongArch64 工具链 | +| `06-用户手册` | 快速使用指南、用户手册、编译指南 | +| `07-芯片手册` | 2K0300 数据手册、用户手册、引脚复用与中断分配 | +| `09-虚拟机环境` | 预装好的 Ubuntu 开发虚拟机 | + +建议优先阅读 `06-用户手册/广东龙芯2K0300先锋派快速使用指南` 和 +`07-芯片手册/2K0300引脚复用配置与中断分配`。 + +## 11. 联系人信息 + +维护人:待补充 + +欢迎提交 issue / PR 补充 GMAC、SPI、I2C 等驱动。 diff --git a/bsp/loongson/ls2k0300/SConscript b/bsp/loongson/ls2k0300/SConscript new file mode 100644 index 0000000000000000000000000000000000000000..97d22a09686b44202496b90feeb4f13845c354f6 --- /dev/null +++ b/bsp/loongson/ls2k0300/SConscript @@ -0,0 +1,13 @@ +import os +from building import * + +cwd = GetCurrentDir() +objs = [] +list = os.listdir(cwd) + +for d in list: + path = os.path.join(cwd, d) + if os.path.isfile(os.path.join(path, 'SConscript')): + objs = objs + SConscript(os.path.join(d, 'SConscript')) + +Return('objs') diff --git a/bsp/loongson/ls2k0300/SConstruct b/bsp/loongson/ls2k0300/SConstruct new file mode 100644 index 0000000000000000000000000000000000000000..6acd1167d0fe83340509ac48309394b35d077c59 --- /dev/null +++ b/bsp/loongson/ls2k0300/SConstruct @@ -0,0 +1,33 @@ +import os +import sys +import rtconfig + +from rtconfig import RTT_ROOT + +# set RTT_ROOT +if not os.getenv("RTT_ROOT"): + RTT_ROOT = os.path.normpath(os.path.join(os.getcwd(), '../../..')) + +sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')] +from building import * + +TARGET = 'rtthread.' + rtconfig.TARGET_EXT + +DefaultEnvironment(tools=[]) +env = Environment(tools = ['mingw'], + AS = rtconfig.AS, ASFLAGS = rtconfig.AFLAGS, + CC = rtconfig.CC, CFLAGS = rtconfig.CFLAGS, + CXX = rtconfig.CXX, CXXFLAGS = rtconfig.CXXFLAGS, + AR = rtconfig.AR, ARFLAGS = '-rc', + LINK = rtconfig.LINK, LINKFLAGS = rtconfig.LFLAGS) +env.PrependENVPath('PATH', rtconfig.EXEC_PATH) +env['ASCOM'] = env['ASPPCOM'] + +Export('RTT_ROOT') +Export('rtconfig') + +# prepare building environment +objs = PrepareBuilding(env, RTT_ROOT) + +# make a building +DoBuilding(TARGET, objs) diff --git a/bsp/loongson/ls2k0300/applications/SConscript b/bsp/loongson/ls2k0300/applications/SConscript new file mode 100644 index 0000000000000000000000000000000000000000..7769758df368669b4a6149299cc5c7cd2f73e06e --- /dev/null +++ b/bsp/loongson/ls2k0300/applications/SConscript @@ -0,0 +1,10 @@ +import os +from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') +CPPPATH = [cwd] + +group = DefineGroup('Applications', src, depend = [''], CPPPATH = CPPPATH) + +Return('group') diff --git a/bsp/loongson/ls2k0300/applications/main.c b/bsp/loongson/ls2k0300/applications/main.c new file mode 100644 index 0000000000000000000000000000000000000000..dc82420ba78c19cf4efcc40f8c1ebdaf38c5ef18 --- /dev/null +++ b/bsp/loongson/ls2k0300/applications/main.c @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +#include + +int main(void) +{ + rt_kprintf("\nHello, Loongson 2K0300 Pioneer!\n"); + rt_kprintf("RT-Thread %d.%d.%d, tick %d Hz\n", + RT_VERSION_MAJOR, RT_VERSION_MINOR, RT_VERSION_PATCH, + RT_TICK_PER_SECOND); + + return 0; +} diff --git a/bsp/loongson/ls2k0300/docs/porting.md b/bsp/loongson/ls2k0300/docs/porting.md new file mode 100644 index 0000000000000000000000000000000000000000..45436f6b14b4e9772a6e029a1f5d1e0ba9ce57a2 --- /dev/null +++ b/bsp/loongson/ls2k0300/docs/porting.md @@ -0,0 +1,192 @@ +# LoongArch64 移植说明(ls2k0300) + +## 1. 总体结构 + +``` +libcpu/loongarch +├── SConscript +├── common +│ ├── asm.h # CSR 号、栈帧偏移 +│ ├── loongarch.h # C 侧 CSR 访问、栈帧结构 +│ ├── context_gcc.S # 异常入口、上下文切换 +│ ├── interrupt.c # 中断开关、ISR 表、trap 分发 +│ ├── cpuport.c # 栈初始化、cache 操作、异常打印 +│ ├── cpuport.h # 内存屏障 +│ └── include/sys/select.h # glibc 工具链兼容头 +└── la264 + ├── start_gcc.S # 启动代码 + └── timer.c # 常量定时器 +``` + +## 2. 启动流程 + +U-Boot(2K0300 板载 U-Boot 2022.04)先把固件加载到 `0x9000000000200000`, +然后跳转执行 `_start`: + +1. 设置系统栈; +2. 重新写入 DMW0(uncached)/ DMW1(cached)直接映射窗口; +3. 对映像范围做 D-Cache 回写无效和 I-Cache 无效,保证指令可见; +4. 清零 `.bss`; +5. 写 `CSR.EENTRY` 指向 `_exc_vectors`; +6. 使能 `ECFG.IM` 中的定时器中断(bit 11)与 HWI2(bit 4); +7. 跳转到 `rtthread_startup()`。 + +## 3. 异常与中断 + +LoongArch 的异常入口由 `CSR.EENTRY` 指定,要求 4KB 对齐。硬件按 +`Ecode * 0x40` 计算向量偏移,向量间距由 `ECFG.VS` 控制,`VS = log2(0x40/4) = 4`。 + +LoongArch 的向量号不是只有 0-63:异常向量是 `Ecode`(0-63),CPU 的 13 个中断 +向量是 `0x40 + irq`(0x40-0x4c)。所以 `_exc_vectors` 是 **128 项**、每项 0x40 +字节(共 8KB)的表,所有项都跳转到 `trap_entry`。 +`trap_entry` 使用 `CSR.SAVE0/SAVE1` 暂存 `$r12/$r13`,然后在当前栈上保存: + +| 偏移 | 内容 | +| -- | -- | +| 0x000 - 0x0f8 | `$r0` - `$r31` | +| 0x100 | `ERA` | +| 0x108 | `PRMD` | +| 0x110 | `ESTAT` | +| 0x118 | 对齐填充 | + +之后调用 `rt_hw_trap_entry(struct rt_hw_stack_frame *)`: + +- `ESTAT.Ecode == 0`:中断,按 `ESTAT.IS` 分发 + - bit 11:常量定时器,清除 `TICLR.TI` 后调用 `rt_tick_increase()` + - bit 4:HWI2,调用 BSP 的 `rt_hw_hwi_dispatch()` 读取 ICU 的 64 位中断状态 +- 其它 Ecode:异常,打印现场后停机 + +## 4. 上下文切换 + +自愿切换(`rt_hw_context_switch`)和中断内切换使用同一份完整栈帧: + +- `rt_hw_context_switch`:构造完整栈帧,`ERA = $ra`,`PRMD.PIE` 取当前 + `CRMD.IE`,保存 `sp` 到 `from`,从 `to` 取出新 `sp`,然后走统一恢复路径; +- 中断内切换:`rt_hw_trap_entry` 返回后检查 + `rt_thread_switch_interrupt_flag`,把当前 `sp` 存入 `from`,从 `to` 取新 `sp`; +- 统一恢复路径从栈帧恢复全部寄存器、`ERA`、`PRMD`,最后执行 `ertn`。 + +由于两条路径的栈帧布局完全一致,被中断抢占的线程和主动让出的线程可以互相恢复。 + +### 浮点 + +BSP 使用 `-mabi=lp64s -msoft-float` 编译,内核不使用 FPU/向量寄存器,因此上下文 +切换不保存浮点现场。若后续需要硬浮点,需要在栈帧中增加 FPR/ FCC 的保存。 + +## 5. 中断控制器(ICU) + +| 项目 | 值 | +| -- | -- | +| 基地址 | `0x16001400` | +| 中断源数量 | 64(0-31 在 `+0x00` 组,32-63 在 `+0x40` 组) | +| 状态 | `+0x20` / `+0x60` | +| 使能 | `+0x24` / `+0x64` | +| 使能置位 | `+0x28` / `+0x68` | +| 使能清除 | `+0x2c` / `+0x6c` | +| 触发方式 | `+0x34` / `+0x74`(1 = 边沿,0 = 电平) | +| 极性 | `+0x30` / `+0x70`(1 = 低有效/下降沿) | +| 路由 | `+0x00` / `+0x40`,每个中断源一个字节 | + +路由字节格式:`(1 << (line + 4)) | core_mask`,其中 `line = CPU 中断号 - 2`。 +ICU 级联到 CPU 中断 4(HWI2),所以 `line = 4 - 2 = 2`,路由值为 +`(1 << 6) | 1 = 0x41`。 + +> 注意:不能直接用父中断号 4 计算,否则得到 `0x101`,中断不会送到 HWI2, +> 表现为 msh 能启动但键盘无输入。该问题已在上板调试中修正。 + +## 5.1 链接脚本要求 + +`--gc-sections` 会回收没有显式引用的段,因此链接脚本必须保留: + +``` +.rodata : { + __fsymtab_start = .; + KEEP(*(FSymTab)) /* msh 命令表 */ + __fsymtab_end = .; + + __rt_init_start = .; + KEEP(*(SORT(.rti_fn*))) /* INIT_BOARD/DEVICE/COMPONENT/APP_EXPORT */ + __rt_init_end = .; +} +``` + +缺少 `.rti_fn` 时 `finsh_system_init()` 不会被调用,msh 不会出现;缺少 +`FSymTab` 时 msh 能进但没有任何命令。这两个段都必须写在输出段的花括号内。 + +## 5.2 GPIO + +2K0300 只有一个 GPIO 控制器(`0x16104000`),共 106 个引脚,每 16 个一组: + +| 寄存器 | 偏移 | 说明 | +| -- | -- | -- | +| DIR | `0x800 + pin` | 1 = 输入,0 = 输出 | +| OUT | `0x900 + pin` | 输出电平 | +| IN | `0xA00 + pin` | 输入电平 | + +pinmux 在 `0x16000490`,每组一个 32 位寄存器(`+ (pin / 16) * 4`),每个引脚占 2 bit, +`0` 表示 GPIO 功能。 + +中断寄存器(同样是每引脚一个字节): + +| 寄存器 | 偏移 | 说明 | +| -- | -- | -- | +| IRQ_EN | `0xB00 + pin` | 中断使能 | +| IRQ_POL | `0xC00 + pin` | 1 = 上升沿/高电平 | +| IRQ_EDGE | `0xD00 + pin` | 1 = 边沿,0 = 电平 | +| IRQ_CLR | `0xE00 + pin` | 写 1 清中断 | +| IRQ_STS | `0xF00 + pin` | 中断状态 | +| IRQ_DUAL | `0xF80 + pin` | 1 = 双边沿 | + +7 组引脚分别级联到 ICU 的 53-59 号线,组内任意引脚有中断时进入组处理函数, +读状态、清标志、回调用户 handler。 + +引脚编号 `0-105`,例如板载 LED 是 GPIO 54(低电平点亮)。驱动见 +`drivers/drv_gpio.c`,导出 `pin_mode`、`pin_write`、`pin_read`、`pin_irq_test` +四个 msh 命令方便调试。 + +> 该控制器没有软件可配置的上拉/下拉寄存器(厂商内核的 pinctrl 驱动也未实现 +> bias),因此 `PIN_MODE_INPUT_PULLUP/PULLDOWN` 等同普通输入。 + +## 5.3 RTC + +片内 RTC 位于 `0x16128000`,日历压缩在两个 32 位寄存器里: + +| 寄存器 | 偏移 | 内容 | +| -- | -- | -- | +| TOY_READ0 | `0x2c` | `[31:26]` 月 `[25:21]` 日 `[20:16]` 时 `[15:10]` 分 `[9:4]` 秒 | +| TOY_READ1 | `0x30` | 年(从 1900 起算) | +| TOY_WRITE0 | `0x24` | 同 READ0 | +| TOY_WRITE1 | `0x28` | 同 READ1 | +| RTC_CTRL | `0x40` | bit11 TOY 使能、bit8 振荡器使能 | + +使用前必须把 `TOY_TRIM(0x20)` 和 `RTC_TRIM(0x60)` 清零,否则计数器不走; +然后置位 CTRL 的 TOY/OSC 使能位。驱动把压缩日历和 Unix 时间戳互转, +不依赖 libc。刚出厂的 RTC 读出全 0,驱动会按 1900-01-01 处理,方便用 +`date` 命令设置一次。 + +## 6. 定时器 + +使用 LoongArch 常量定时器: + +- `CSR.TCFG`:`(ticks << 2) | PERIOD | EN` +- `CSR.TICLR`:写 bit0 清除定时器中断 +- 时钟频率默认 100MHz,可在 `libcpu/loongarch/la264/timer.c` 中通过 + `LOONGARCH_TIMER_FREQ` 宏调整 + +## 7. 工具链兼容性 + +龙芯官方工具链是 glibc 版,直接包含 glibc 头文件会和 RT-Thread 自带的 +`sys/select.h` 冲突(glibc 的 `sys/types.h` 在定义 `suseconds_t` 之前又会包含 +`sys/select.h`)。为此 `libcpu/loongarch/common/include/sys/select.h` 提供了一个 +不依赖 `suseconds_t` 的最小实现,并补充了 glibc 在非 `_XOPEN_SOURCE` 模式下不 +提供的 `suseconds_t` / `useconds_t` 定义。 + +## 8. 待办 + +已上板验证:常量定时器(1000Hz)、ICU(含 GPIO 组中断 53-59)、GPIO、 +RTC(复位后继续走时)。 + +- GMAC(DesignWare 3.70a)+ LwIP +- SPI、I2C、CAN-FD +- ADC、PWM、看门狗 +- DFS 文件系统 diff --git a/bsp/loongson/ls2k0300/drivers/SConscript b/bsp/loongson/ls2k0300/drivers/SConscript new file mode 100644 index 0000000000000000000000000000000000000000..2b288cd968041c3dd9b9fd4c63ef4a3f8aaaecfc --- /dev/null +++ b/bsp/loongson/ls2k0300/drivers/SConscript @@ -0,0 +1,10 @@ +import os +from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') + Glob('*.S') +CPPPATH = [cwd] + +group = DefineGroup('Drivers', src, depend = [''], CPPPATH = CPPPATH) + +Return('group') diff --git a/bsp/loongson/ls2k0300/drivers/board.c b/bsp/loongson/ls2k0300/drivers/board.c new file mode 100644 index 0000000000000000000000000000000000000000..66d8a62e6e8c13c3fb1c152b4909f25e6ee757c3 --- /dev/null +++ b/bsp/loongson/ls2k0300/drivers/board.c @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +#include +#include + +#include "board.h" +#include "interrupt.h" +#include "drv_uart.h" +#include "drv_gpio.h" +#include "drv_rtc.h" +#include "ls2k0300.h" + +void rt_hw_cpu_reset(void) +{ + rt_ubase_t base = LS2K_PHYS_TO_UNCACHED(LS2K_PMC_BASE); + + LS2K_REG32(base, 0) |= LS2K_PMC_RESET; + + for (;;) + { + } +} +MSH_CMD_EXPORT_ALIAS(rt_hw_cpu_reset, reboot, reset cpu); + +void rt_hw_board_init(void) +{ +#ifdef RT_USING_HEAP + rt_system_heap_init(RT_HW_HEAP_BEGIN, RT_HW_HEAP_END); +#endif + + rt_hw_interrupt_init(); +#ifdef BSP_USING_ICU + rt_hw_icu_init(); +#endif + +#ifdef BSP_USING_GPIO + rt_hw_gpio_init(); +#endif + +#ifdef BSP_USING_RTC + rt_hw_rtc_init(); +#endif + +#ifdef RT_USING_DEVICE + rt_hw_uart_init(); +#ifdef RT_USING_CONSOLE + rt_console_set_device(RT_CONSOLE_DEVICE_NAME); +#endif +#endif + + rt_hw_timer_init(); + +#ifdef RT_USING_COMPONENTS_INIT + rt_components_board_init(); +#endif +} diff --git a/bsp/loongson/ls2k0300/drivers/board.h b/bsp/loongson/ls2k0300/drivers/board.h new file mode 100644 index 0000000000000000000000000000000000000000..db6426e21ec9d07e305f10cd1f461466cae29b27 --- /dev/null +++ b/bsp/loongson/ls2k0300/drivers/board.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +#ifndef __BOARD_H__ +#define __BOARD_H__ + +#include + +/* defined in ls2k0300.lds */ +extern char __heap_start; +extern char __heap_end; +extern char _system_stack_top; + +#define RT_HW_HEAP_BEGIN ((void *)&__heap_start) +#define RT_HW_HEAP_END ((void *)&__heap_end) + +void rt_hw_board_init(void); +void rt_hw_timer_init(void); + +#endif /* __BOARD_H__ */ diff --git a/bsp/loongson/ls2k0300/drivers/drv_gpio.c b/bsp/loongson/ls2k0300/drivers/drv_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..5de51782904706a691111f240092e84dd9d7ccc4 --- /dev/null +++ b/bsp/loongson/ls2k0300/drivers/drv_gpio.c @@ -0,0 +1,454 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +#include +#include +#include + +#include "drv_gpio.h" +#include "ls2k0300.h" + +/* + * LS2K0300 GPIO controller: + * - 106 pins, 16 pins per group, 7 groups + * - every pin owns one byte in each register block: + * dir (1 = input, 0 = output), out, in, irq enable, polarity, + * edge/level, clear (write 1), status, dual edge + * - pin multiplexing: 2 bits per pin, 16 pins per 32bit register + * - group 0..6 are cascaded to ICU line 53..59 + * + * The vendor kernel does not expose any pull-up/pull-down register for + * this controller, so PIN_MODE_INPUT_PULLUP/PULLDOWN behave like a plain + * input. + */ +#define GPIO_PINS 106 +#define GPIO_IRQ_GROUPS 7 +#define GPIO_IRQ_BASE 53 + +#define GPIO_REG_DIR 0x800 +#define GPIO_REG_OUT 0x900 +#define GPIO_REG_IN 0xA00 +#define GPIO_REG_IRQ_EN 0xB00 +#define GPIO_REG_IRQ_POL 0xC00 +#define GPIO_REG_IRQ_EDGE 0xD00 +#define GPIO_REG_IRQ_CLR 0xE00 +#define GPIO_REG_IRQ_STS 0xF00 +#define GPIO_REG_IRQ_DUAL 0xF80 + +#define GPIO_MUX_BASE 0x16000490UL +#define GPIO_MUX_PINS_PER_REG 16 +#define GPIO_MUX_STRIDE 4 + +struct _gpio_irq +{ + void (*hdr)(void *args); + void *args; +}; + +static struct _gpio_irq _gpio_irq[GPIO_PINS]; +static rt_uint8_t _gpio_irq_ref[GPIO_IRQ_GROUPS]; + +static rt_ubase_t _gpio_base(void) +{ + return LS2K_PHYS_TO_UNCACHED(LS2K_GPIO_BASE); +} + +static rt_bool_t _pin_is_valid(rt_base_t pin) +{ + return (pin >= 0 && pin < GPIO_PINS) ? RT_TRUE : RT_FALSE; +} + +static rt_base_t _group_last_pin(rt_base_t group) +{ + rt_base_t last = (group + 1) * GPIO_MUX_PINS_PER_REG - 1; + + return (last < GPIO_PINS) ? last : (GPIO_PINS - 1); +} + +/* select the GPIO function of a pin */ +static void _pin_mux_gpio(rt_base_t pin) +{ + rt_ubase_t reg = LS2K_PHYS_TO_UNCACHED(GPIO_MUX_BASE) + + (pin / GPIO_MUX_PINS_PER_REG) * GPIO_MUX_STRIDE; + rt_uint32_t shift = (pin % GPIO_MUX_PINS_PER_REG) * 2; + rt_base_t level; + rt_uint32_t value; + + level = rt_hw_interrupt_disable(); + value = LS2K_REG32(reg, 0); + value &= ~(0x3UL << shift); + LS2K_REG32(reg, 0) = value; + rt_hw_interrupt_enable(level); +} + +static void _pin_irq_mode(rt_base_t pin, rt_uint8_t mode) +{ + rt_uint8_t pol = 0; + rt_uint8_t edge = 0; + rt_uint8_t dual = 0; + + switch (mode) + { + case PIN_IRQ_MODE_RISING: + pol = 1; + edge = 1; + break; + + case PIN_IRQ_MODE_FALLING: + pol = 0; + edge = 1; + break; + + case PIN_IRQ_MODE_RISING_FALLING: + dual = 1; + edge = 1; + break; + + case PIN_IRQ_MODE_HIGH_LEVEL: + pol = 1; + edge = 0; + break; + + case PIN_IRQ_MODE_LOW_LEVEL: + pol = 0; + edge = 0; + break; + + default: + return; + } + + LS2K_REG8(_gpio_base(), GPIO_REG_IRQ_DUAL + pin) = dual; + LS2K_REG8(_gpio_base(), GPIO_REG_IRQ_POL + pin) = pol; + LS2K_REG8(_gpio_base(), GPIO_REG_IRQ_EDGE + pin) = edge; +} + +static void _pin_mode(struct rt_device *device, rt_base_t pin, rt_uint8_t mode) +{ + rt_uint8_t direction; + + RT_UNUSED(device); + + if (!_pin_is_valid(pin)) + { + return; + } + + switch (mode) + { + case PIN_MODE_OUTPUT: + direction = 0; + break; + + case PIN_MODE_INPUT: + case PIN_MODE_INPUT_PULLUP: + case PIN_MODE_INPUT_PULLDOWN: + /* no software controllable pull resistor on this controller */ + direction = 1; + break; + + default: + return; + } + + _pin_mux_gpio(pin); + LS2K_REG8(_gpio_base(), GPIO_REG_DIR + pin) = direction; +} + +static void _pin_write(struct rt_device *device, rt_base_t pin, rt_uint8_t value) +{ + RT_UNUSED(device); + + if (!_pin_is_valid(pin)) + { + return; + } + + LS2K_REG8(_gpio_base(), GPIO_REG_OUT + pin) = value ? 1 : 0; +} + +static rt_ssize_t _pin_read(struct rt_device *device, rt_base_t pin) +{ + RT_UNUSED(device); + + if (!_pin_is_valid(pin)) + { + return -RT_EINVAL; + } + + return (rt_ssize_t)(LS2K_REG8(_gpio_base(), GPIO_REG_IN + pin) & 0x1); +} + +static void _gpio_irq_handler(int vector, void *param) +{ + rt_base_t group = (rt_base_t)(rt_ubase_t)param; + rt_base_t pin; + rt_base_t last = _group_last_pin(group); + + RT_UNUSED(vector); + + for (pin = group * GPIO_MUX_PINS_PER_REG; pin <= last; pin++) + { + if (LS2K_REG8(_gpio_base(), GPIO_REG_IRQ_STS + pin) & 0x1) + { + /* write 1 to clear the pending flag */ + LS2K_REG8(_gpio_base(), GPIO_REG_IRQ_CLR + pin) = 1; + + if (_gpio_irq[pin].hdr != RT_NULL) + { + _gpio_irq[pin].hdr(_gpio_irq[pin].args); + } + } + } +} + +static rt_err_t _pin_attach_irq(struct rt_device *device, rt_base_t pin, + rt_uint8_t mode, void (*hdr)(void *args), void *args) +{ + RT_UNUSED(device); + + if (!_pin_is_valid(pin)) + { + return -RT_EINVAL; + } + + _pin_mux_gpio(pin); + LS2K_REG8(_gpio_base(), GPIO_REG_DIR + pin) = 1; + _pin_irq_mode(pin, mode); + + _gpio_irq[pin].hdr = hdr; + _gpio_irq[pin].args = args; + + return RT_EOK; +} + +static rt_err_t _pin_detach_irq(struct rt_device *device, rt_base_t pin) +{ + RT_UNUSED(device); + + if (!_pin_is_valid(pin)) + { + return -RT_EINVAL; + } + + LS2K_REG8(_gpio_base(), GPIO_REG_IRQ_EN + pin) = 0; + _gpio_irq[pin].hdr = RT_NULL; + _gpio_irq[pin].args = RT_NULL; + + return RT_EOK; +} + +static rt_err_t _pin_irq_enable(struct rt_device *device, rt_base_t pin, rt_uint8_t enabled) +{ + rt_base_t group; + rt_base_t level; + + RT_UNUSED(device); + + if (!_pin_is_valid(pin)) + { + return -RT_EINVAL; + } + + group = pin / GPIO_MUX_PINS_PER_REG; + + level = rt_hw_interrupt_disable(); + + if (enabled) + { + LS2K_REG8(_gpio_base(), GPIO_REG_IRQ_CLR + pin) = 1; + + if (_gpio_irq_ref[group] == 0) + { + rt_hw_interrupt_umask(GPIO_IRQ_BASE + group); + } + if (_gpio_irq_ref[group] < 0xff) + { + _gpio_irq_ref[group]++; + } + + LS2K_REG8(_gpio_base(), GPIO_REG_IRQ_EN + pin) = 1; + } + else + { + LS2K_REG8(_gpio_base(), GPIO_REG_IRQ_EN + pin) = 0; + + if (_gpio_irq_ref[group] > 0) + { + _gpio_irq_ref[group]--; + } + if (_gpio_irq_ref[group] == 0) + { + rt_hw_interrupt_mask(GPIO_IRQ_BASE + group); + } + } + + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +static const struct rt_pin_ops _pin_ops = { + .pin_mode = _pin_mode, + .pin_write = _pin_write, + .pin_read = _pin_read, + .pin_attach_irq = _pin_attach_irq, + .pin_detach_irq = _pin_detach_irq, + .pin_irq_enable = _pin_irq_enable, +}; + +int rt_hw_gpio_init(void) +{ + rt_base_t group; + + for (group = 0; group < GPIO_IRQ_GROUPS; group++) + { + rt_hw_interrupt_install(GPIO_IRQ_BASE + group, _gpio_irq_handler, + (void *)(rt_ubase_t)group, "gpio"); + rt_hw_interrupt_mask(GPIO_IRQ_BASE + group); + } + + return rt_device_pin_register("pin", &_pin_ops, RT_NULL); +} + +#ifdef RT_USING_FINSH +static int _pin_parse(rt_base_t *pin, const char *str) +{ + rt_base_t value = 0; + + if (str == RT_NULL || *str == '\0') + { + return -1; + } + + while (*str >= '0' && *str <= '9') + { + value = value * 10 + (*str - '0'); + str++; + } + + if (*str != '\0') + { + return -1; + } + + *pin = value; + return 0; +} + +static void pin_mode(int argc, char **argv) +{ + rt_base_t pin; + + if (argc != 3 || _pin_parse(&pin, argv[1]) != 0) + { + rt_kprintf("usage: pin_mode \n"); + return; + } + + if (rt_strcmp(argv[2], "out") == 0) + { + rt_pin_mode(pin, PIN_MODE_OUTPUT); + } + else if (rt_strcmp(argv[2], "in") == 0) + { + rt_pin_mode(pin, PIN_MODE_INPUT); + } + else + { + rt_kprintf("usage: pin_mode \n"); + return; + } + + rt_kprintf("pin %d mode -> %s\n", (int)pin, argv[2]); +} +MSH_CMD_EXPORT(pin_mode, set gpio mode : pin_mode); + +static void pin_write(int argc, char **argv) +{ + rt_base_t pin; + rt_base_t value; + + if (argc != 3 || _pin_parse(&pin, argv[1]) != 0 || + _pin_parse(&value, argv[2]) != 0) + { + rt_kprintf("usage: pin_write <0|1>\n"); + return; + } + + rt_pin_write(pin, value ? PIN_HIGH : PIN_LOW); + rt_kprintf("pin %d write %d\n", (int)pin, (int)(value ? 1 : 0)); +} +MSH_CMD_EXPORT(pin_write, write gpio : pin_write<0 | 1>); + +static void pin_read(int argc, char **argv) +{ + rt_base_t pin; + + if (argc != 2 || _pin_parse(&pin, argv[1]) != 0) + { + rt_kprintf("usage: pin_read \n"); + return; + } + + rt_kprintf("pin %d = %d\n", (int)pin, (int)rt_pin_read(pin)); +} +MSH_CMD_EXPORT(pin_read, read gpio : pin_read); + +static volatile rt_uint32_t _irq_test_count; + +static void _irq_test_cb(void *args) +{ + RT_UNUSED(args); + + _irq_test_count++; +} + +/* + * connect a jumper between and , then run: + * pin_irq_test + */ +static void pin_irq_test(int argc, char **argv) +{ + rt_base_t in_pin; + rt_base_t out_pin; + rt_base_t times; + rt_base_t i; + + if (argc != 4 || _pin_parse(&in_pin, argv[1]) != 0 || + _pin_parse(&out_pin, argv[2]) != 0 || + _pin_parse(×, argv[3]) != 0) + { + rt_kprintf("usage: pin_irq_test \n"); + return; + } + + _irq_test_count = 0; + + rt_pin_mode(out_pin, PIN_MODE_OUTPUT); + rt_pin_mode(in_pin, PIN_MODE_INPUT); + rt_pin_write(out_pin, PIN_LOW); + + rt_pin_attach_irq(in_pin, PIN_IRQ_MODE_RISING_FALLING, _irq_test_cb, RT_NULL); + rt_pin_irq_enable(in_pin, PIN_IRQ_ENABLE); + + for (i = 0; i < times; i++) + { + rt_pin_write(out_pin, (i & 1) ? PIN_HIGH : PIN_LOW); + rt_thread_mdelay(50); + } + + rt_pin_irq_enable(in_pin, PIN_IRQ_DISABLE); + rt_pin_detach_irq(in_pin); + + rt_kprintf("toggle %d times, irq count = %d\n", (int)times, (int)_irq_test_count); +} +MSH_CMD_EXPORT(pin_irq_test, gpio irq self test : pin_irq_test); +#endif /* RT_USING_FINSH */ diff --git a/bsp/loongson/ls2k0300/drivers/drv_gpio.h b/bsp/loongson/ls2k0300/drivers/drv_gpio.h new file mode 100644 index 0000000000000000000000000000000000000000..54723f5ef730e85727f14c5b27c363a76ae07673 --- /dev/null +++ b/bsp/loongson/ls2k0300/drivers/drv_gpio.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +#ifndef __DRV_GPIO_H__ +#define __DRV_GPIO_H__ + +#include + +int rt_hw_gpio_init(void); + +#endif /* __DRV_GPIO_H__ */ diff --git a/bsp/loongson/ls2k0300/drivers/drv_rtc.c b/bsp/loongson/ls2k0300/drivers/drv_rtc.c new file mode 100644 index 0000000000000000000000000000000000000000..d31f84d612b7b8eaf14be8ce84a565bc82a0c7f5 --- /dev/null +++ b/bsp/loongson/ls2k0300/drivers/drv_rtc.c @@ -0,0 +1,213 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +#include +#include +#include +#include + +#include "drv_rtc.h" +#include "ls2k0300.h" + +/* + * LS2K0300 RTC (0x16128000), the calendar is packed into two registers: + * + * TOY_READ0 0x2c / TOY_WRITE0 0x24: + * [31:26] month [25:21] day [20:16] hour [15:10] minute [9:4] second + * TOY_READ1 0x30 / TOY_WRITE1 0x28: + * year, counted from 1900 + * + * The trim registers must be cleared, otherwise the counter does not run. + */ +#define RTC_TOY_TRIM 0x20 +#define RTC_TOY_WRITE0 0x24 +#define RTC_TOY_WRITE1 0x28 +#define RTC_TOY_READ0 0x2c +#define RTC_TOY_READ1 0x30 +#define RTC_CTRL 0x40 +#define RTC_TRIM 0x60 + +#define RTC_CTRL_TOY_EN (1u << 11) +#define RTC_CTRL_OSC_EN (1u << 8) + +static rt_ubase_t _rtc_base(void) +{ + return LS2K_PHYS_TO_UNCACHED(LS2K_RTC_BASE); +} + +/* days since 1970-01-01 of a civil date */ +static rt_int32_t _days_from_civil(rt_int32_t y, rt_uint32_t m, rt_uint32_t d) +{ + rt_int32_t era; + rt_uint32_t yoe; + rt_uint32_t doy; + rt_uint32_t doe; + + y -= (m <= 2); + era = (y >= 0 ? y : y - 399) / 400; + yoe = (rt_uint32_t)(y - era * 400); + doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; + doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + + return era * 146097 + (rt_int32_t)doe - 719468; +} + +static void _civil_from_days(rt_int32_t z, rt_int32_t *y, rt_uint32_t *m, rt_uint32_t *d) +{ + rt_int32_t era; + rt_uint32_t doe; + rt_uint32_t yoe; + rt_int32_t year; + rt_uint32_t doy; + rt_uint32_t mp; + + z += 719468; + era = (z >= 0 ? z : z - 146096) / 146097; + doe = (rt_uint32_t)(z - era * 146097); + yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + year = (rt_int32_t)yoe + era * 400; + doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + mp = (5 * doy + 2) / 153; + + *d = doy - (153 * mp + 2) / 5 + 1; + *m = mp + (mp < 10 ? 3 : -9); + *y = year + (*m <= 2); +} + +static void _rtc_hw_enable(void) +{ + rt_ubase_t base = _rtc_base(); + rt_uint32_t value; + + LS2K_REG32(base, RTC_TOY_TRIM) = 0; + LS2K_REG32(base, RTC_TRIM) = 0; + + value = LS2K_REG32(base, RTC_CTRL); + value |= (RTC_CTRL_TOY_EN | RTC_CTRL_OSC_EN); + LS2K_REG32(base, RTC_CTRL) = value; +} + +static rt_err_t _rtc_init(void) +{ + _rtc_hw_enable(); + + return RT_EOK; +} + +static rt_err_t _rtc_get_secs(time_t *sec) +{ + rt_ubase_t base = _rtc_base(); + rt_base_t level; + rt_uint32_t year_reg; + rt_uint32_t value; + rt_int32_t year; + rt_uint32_t mon; + rt_uint32_t day; + rt_uint32_t hour; + rt_uint32_t min; + rt_uint32_t second; + + level = rt_hw_interrupt_disable(); + year_reg = LS2K_REG32(base, RTC_TOY_READ1); + value = LS2K_REG32(base, RTC_TOY_READ0); + rt_hw_interrupt_enable(level); + + year = 1900 + (rt_int32_t)year_reg; + mon = (value >> 26) & 0x3f; + day = (value >> 21) & 0x1f; + hour = (value >> 16) & 0x1f; + min = (value >> 10) & 0x3f; + second = (value >> 4) & 0x3f; + + /* a brand new RTC reads all zero, clamp it to 1900-01-01 00:00:00 + * instead of failing, otherwise the time can never be set */ + if (mon < 1 || mon > 12) + { + mon = 1; + } + if (day < 1 || day > 31) + { + day = 1; + } + if (hour > 23) + { + hour = 0; + } + if (min > 59) + { + min = 0; + } + if (second > 59) + { + second = 0; + } + + *sec = (time_t)_days_from_civil(year, mon, day) * 86400 + + (time_t)hour * 3600 + (time_t)min * 60 + (time_t)second; + + return RT_EOK; +} + +static rt_err_t _rtc_set_secs(time_t *sec) +{ + rt_ubase_t base = _rtc_base(); + rt_int32_t days = (rt_int32_t)(*sec / 86400); + rt_int32_t rem = (rt_int32_t)(*sec % 86400); + rt_int32_t year; + rt_uint32_t mon; + rt_uint32_t day; + rt_uint32_t hour; + rt_uint32_t min; + rt_uint32_t second; + rt_base_t level; + rt_uint32_t value; + + if (rem < 0) + { + rem += 86400; + days--; + } + + _civil_from_days(days, &year, &mon, &day); + if (year < 1900) + { + return -RT_EINVAL; + } + + hour = (rt_uint32_t)rem / 3600; + min = ((rt_uint32_t)rem % 3600) / 60; + second = (rt_uint32_t)rem % 60; + + value = (mon << 26) | (day << 21) | (hour << 16) | (min << 10) | (second << 4); + + level = rt_hw_interrupt_disable(); + LS2K_REG32(base, RTC_TOY_WRITE0) = value; + LS2K_REG32(base, RTC_TOY_WRITE1) = (rt_uint32_t)(year - 1900); + rt_hw_interrupt_enable(level); + + return RT_EOK; +} + +static const struct rt_rtc_ops _rtc_ops = { + .init = _rtc_init, + .get_secs = _rtc_get_secs, + .set_secs = _rtc_set_secs, +}; + +static rt_rtc_dev_t _rtc_dev; + +int rt_hw_rtc_init(void) +{ + _rtc_hw_enable(); + + _rtc_dev.ops = &_rtc_ops; + + return rt_hw_rtc_register(&_rtc_dev, "rtc", RT_DEVICE_FLAG_RDWR, RT_NULL); +} diff --git a/bsp/loongson/ls2k0300/drivers/drv_rtc.h b/bsp/loongson/ls2k0300/drivers/drv_rtc.h new file mode 100644 index 0000000000000000000000000000000000000000..3e4b2d637659629f0503e8d286ccac2e5b9dd3f9 --- /dev/null +++ b/bsp/loongson/ls2k0300/drivers/drv_rtc.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +#ifndef __DRV_RTC_H__ +#define __DRV_RTC_H__ + +#include + +int rt_hw_rtc_init(void); + +#endif /* __DRV_RTC_H__ */ diff --git a/bsp/loongson/ls2k0300/drivers/drv_uart.c b/bsp/loongson/ls2k0300/drivers/drv_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..8065fe15c39c5f58f08f208739c0f98227007efa --- /dev/null +++ b/bsp/loongson/ls2k0300/drivers/drv_uart.c @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +#include +#include + +#include "board.h" +#include "drv_uart.h" +#include "interrupt.h" +#include "ls2k0300.h" + +#define UART_RX_BUFSZ 256 + +/* baud rate U-Boot uses for the console */ +#ifndef BSP_CONSOLE_BAUD +#define BSP_CONSOLE_BAUD 115200 +#endif + +struct ls2k_uart +{ + struct rt_device parent; + rt_ubase_t base; + rt_uint32_t irq; + rt_uint16_t rx_head; + rt_uint16_t rx_tail; + rt_uint8_t rx_buf[UART_RX_BUFSZ]; +}; + +static struct ls2k_uart uart0 = { + .base = LS2K_PHYS_TO_UNCACHED(LS2K_UART0_BASE), + .irq = 0, +}; + +#ifdef BSP_USING_UART1 +static struct ls2k_uart uart1 = { + .base = LS2K_PHYS_TO_UNCACHED(LS2K_UART1_BASE), + .irq = 1, +}; +#endif + +/* + * The UART input clock is not documented consistently between the SoC + * manuals and the board DTS files (100MHz vs 50MHz). U-Boot has already + * programmed the console UART at BSP_CONSOLE_BAUD, so derive the real + * input clock from the divisor it left behind instead of assuming one. + */ +static rt_uint32_t _uart_get_clock(struct ls2k_uart *uart) +{ + rt_uint8_t lcr = LS2K_REG8(uart->base, LS2K_UART_LCR); + rt_uint32_t divisor; + + LS2K_REG8(uart->base, LS2K_UART_LCR) = lcr | LS2K_UART_LCR_DLAB; + divisor = LS2K_REG8(uart->base, LS2K_UART_DLL) | + ((rt_uint32_t)LS2K_REG8(uart->base, LS2K_UART_DLM) << 8); + LS2K_REG8(uart->base, LS2K_UART_LCR) = lcr & ~LS2K_UART_LCR_DLAB; + + if (divisor == 0 || divisor == 0xffff) + { + return LS2K_UART_CLK; + } + + return divisor * 16 * BSP_CONSOLE_BAUD; +} + +static void _uart_set_baud(struct ls2k_uart *uart, rt_uint32_t baud) +{ + rt_uint32_t clock = _uart_get_clock(uart); + rt_uint32_t divisor = (clock + baud / 2) / (16 * baud); + + LS2K_REG8(uart->base, LS2K_UART_LCR) = LS2K_UART_LCR_DLAB | LS2K_UART_LCR_8N1; + LS2K_REG8(uart->base, LS2K_UART_DLL) = divisor & 0xff; + LS2K_REG8(uart->base, LS2K_UART_DLM) = (divisor >> 8) & 0xff; + LS2K_REG8(uart->base, LS2K_UART_LCR) = LS2K_UART_LCR_8N1; + + /* enable and reset the FIFOs */ + LS2K_REG8(uart->base, LS2K_UART_FCR) = + LS2K_UART_FCR_ENABLE | LS2K_UART_FCR_CLEAR; +} + +static void _uart_putc(struct ls2k_uart *uart, char ch) +{ + while ((LS2K_REG8(uart->base, LS2K_UART_LSR) & LS2K_UART_LSR_THRE) == 0) + { + } + + LS2K_REG8(uart->base, LS2K_UART_THR) = (rt_uint8_t)ch; +} + +void rt_hw_uart_console_output(const char *str) +{ + while (*str) + { + if (*str == '\n') + { + _uart_putc(&uart0, '\r'); + } + _uart_putc(&uart0, *str++); + } +} + +void rt_hw_console_output(const char *str) +{ + rt_hw_uart_console_output(str); +} + +static void _uart_isr(int vector, void *param) +{ + struct ls2k_uart *uart = (struct ls2k_uart *)param; + rt_uint32_t received = 0; + rt_base_t level; + + RT_UNUSED(vector); + + while (LS2K_REG8(uart->base, LS2K_UART_LSR) & LS2K_UART_LSR_DR) + { + rt_uint8_t ch = (rt_uint8_t)LS2K_REG8(uart->base, LS2K_UART_RBR); + rt_uint16_t next; + + level = rt_hw_interrupt_disable(); + next = (rt_uint16_t)((uart->rx_head + 1) % UART_RX_BUFSZ); + if (next != uart->rx_tail) + { + uart->rx_buf[uart->rx_head] = ch; + uart->rx_head = next; + received++; + } + rt_hw_interrupt_enable(level); + } + + if (received && uart->parent.rx_indicate != RT_NULL) + { + uart->parent.rx_indicate(&uart->parent, received); + } +} + +static rt_err_t _uart_open(rt_device_t dev, rt_uint16_t oflag) +{ + struct ls2k_uart *uart = (struct ls2k_uart *)dev; + + RT_UNUSED(oflag); + +#ifdef BSP_USING_UART_IRQ + LS2K_REG8(uart->base, LS2K_UART_IER) |= LS2K_UART_IER_RDI; + rt_hw_interrupt_umask(uart->irq); +#endif + + return RT_EOK; +} + +static rt_err_t _uart_close(rt_device_t dev) +{ + struct ls2k_uart *uart = (struct ls2k_uart *)dev; + + LS2K_REG8(uart->base, LS2K_UART_IER) &= ~LS2K_UART_IER_RDI; +#ifdef BSP_USING_UART_IRQ + rt_hw_interrupt_mask(uart->irq); +#endif + + return RT_EOK; +} + +static rt_ssize_t _uart_read(rt_device_t dev, rt_off_t pos, + void *buffer, rt_size_t size) +{ + struct ls2k_uart *uart = (struct ls2k_uart *)dev; + rt_uint8_t *pbuf = (rt_uint8_t *)buffer; + rt_size_t count = 0; + rt_base_t level; + + RT_UNUSED(pos); + + level = rt_hw_interrupt_disable(); + while (count < size && uart->rx_tail != uart->rx_head) + { + pbuf[count++] = uart->rx_buf[uart->rx_tail]; + uart->rx_tail = (rt_uint16_t)((uart->rx_tail + 1) % UART_RX_BUFSZ); + } + rt_hw_interrupt_enable(level); + + return (rt_ssize_t)count; +} + +static rt_ssize_t _uart_write(rt_device_t dev, rt_off_t pos, + const void *buffer, rt_size_t size) +{ + struct ls2k_uart *uart = (struct ls2k_uart *)dev; + const char *pstr = (const char *)buffer; + rt_size_t i; + + RT_UNUSED(pos); + + for (i = 0; i < size; i++) + { + if (pstr[i] == '\n') + { + _uart_putc(uart, '\r'); + } + _uart_putc(uart, pstr[i]); + } + + return (rt_ssize_t)size; +} + +static rt_err_t _uart_control(rt_device_t dev, int cmd, void *args) +{ + struct ls2k_uart *uart = (struct ls2k_uart *)dev; + + RT_UNUSED(args); + + switch (cmd) + { + case RT_DEVICE_CTRL_SET_INT: +#ifdef BSP_USING_UART_IRQ + LS2K_REG8(uart->base, LS2K_UART_IER) |= LS2K_UART_IER_RDI; + rt_hw_interrupt_umask(uart->irq); +#endif + break; + + case RT_DEVICE_CTRL_CLR_INT: + LS2K_REG8(uart->base, LS2K_UART_IER) &= ~LS2K_UART_IER_RDI; +#ifdef BSP_USING_UART_IRQ + rt_hw_interrupt_mask(uart->irq); +#endif + break; + + default: + return RT_ENOSYS; + } + + return RT_EOK; +} + +static int _uart_device_init(struct ls2k_uart *uart, const char *name) +{ + rt_err_t result; + + _uart_set_baud(uart, 115200); + + uart->parent.type = RT_Device_Class_Char; + uart->parent.rx_indicate = RT_NULL; + uart->parent.tx_complete = RT_NULL; + uart->parent.init = RT_NULL; + uart->parent.open = _uart_open; + uart->parent.close = _uart_close; + uart->parent.read = _uart_read; + uart->parent.write = _uart_write; + uart->parent.control = _uart_control; + uart->parent.user_data = RT_NULL; + + result = rt_device_register(&uart->parent, name, + RT_DEVICE_FLAG_RDWR | + RT_DEVICE_FLAG_INT_RX | + RT_DEVICE_FLAG_STREAM); + if (result != RT_EOK) + { + return -1; + } + + rt_hw_interrupt_install((int)uart->irq, _uart_isr, uart, name); + + return 0; +} + +int rt_hw_uart_init(void) +{ + _uart_device_init(&uart0, "uart0"); + +#ifdef BSP_USING_UART1 + _uart_device_init(&uart1, "uart1"); +#endif + + return 0; +} diff --git a/bsp/loongson/ls2k0300/drivers/drv_uart.h b/bsp/loongson/ls2k0300/drivers/drv_uart.h new file mode 100644 index 0000000000000000000000000000000000000000..2145a0ba0fc05aafafd40e3e14a0458ab1831f2e --- /dev/null +++ b/bsp/loongson/ls2k0300/drivers/drv_uart.h @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +#ifndef __DRV_UART_H__ +#define __DRV_UART_H__ + +#include + +int rt_hw_uart_init(void); +void rt_hw_uart_console_output(const char *str); + +#endif /* __DRV_UART_H__ */ diff --git a/bsp/loongson/ls2k0300/drivers/interrupt.c b/bsp/loongson/ls2k0300/drivers/interrupt.c new file mode 100644 index 0000000000000000000000000000000000000000..e019f800fc886c15ab0a414b34f22b673b0e3c85 --- /dev/null +++ b/bsp/loongson/ls2k0300/drivers/interrupt.c @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +#include +#include + +#include "interrupt.h" +#include "ls2k0300.h" + +void rt_hw_icu_init(void) +{ + rt_uint32_t i; + rt_ubase_t base = LS2K_PHYS_TO_UNCACHED(LS2K_ICU_BASE); + + /* route all 64 sources to CPU interrupt HWI2 (interrupt line 4) */ + for (i = 0; i < LS2K_IRQ_NUM; i++) + { + rt_uint32_t reg = (i > 31) ? 0x40 : 0x00; + + LS2K_REG8(base, reg + (i & 0x1f)) = + (rt_uint8_t)((1 << (LS2K_ICU_CASCADE_LINE + 4)) | 0x1); + } + + /* mask everything, level triggered, active high by default */ + LS2K_REG32(base, LS2K_ICU_INTENCLR0) = 0xffffffff; + LS2K_REG32(base, LS2K_ICU_INTENCLR1) = 0xffffffff; + LS2K_REG32(base, LS2K_ICU_INTEDGE0) = 0x00000000; + LS2K_REG32(base, LS2K_ICU_INTEDGE1) = 0x00000000; + LS2K_REG32(base, LS2K_ICU_INTPOL0) = 0x00000000; + LS2K_REG32(base, LS2K_ICU_INTPOL1) = 0x00000000; +} + +void rt_hw_hwi_dispatch(rt_uint32_t hwi) +{ + rt_uint32_t pending; + rt_uint32_t i; + rt_ubase_t base = LS2K_PHYS_TO_UNCACHED(LS2K_ICU_BASE); + + RT_UNUSED(hwi); + + pending = LS2K_REG32(base, LS2K_ICU_ISR0); + for (i = 0; i < 32; i++) + { + if (pending & (1u << i)) + { + rt_hw_interrupt_handler((int)i); + } + } + + pending = LS2K_REG32(base, LS2K_ICU_ISR1); + for (i = 0; i < 32; i++) + { + if (pending & (1u << i)) + { + rt_hw_interrupt_handler((int)(32 + i)); + } + } +} + +void rt_hw_interrupt_mask(int vector) +{ + rt_ubase_t base = LS2K_PHYS_TO_UNCACHED(LS2K_ICU_BASE); + + if (vector < 0 || vector >= LS2K_IRQ_NUM) + { + return; + } + + LS2K_REG32(base, (vector > 31) ? LS2K_ICU_INTENCLR1 : LS2K_ICU_INTENCLR0) = + 1u << (vector & 0x1f); +} + +void rt_hw_interrupt_umask(int vector) +{ + rt_ubase_t base = LS2K_PHYS_TO_UNCACHED(LS2K_ICU_BASE); + + if (vector < 0 || vector >= LS2K_IRQ_NUM) + { + return; + } + + LS2K_REG32(base, (vector > 31) ? LS2K_ICU_INTENSET1 : LS2K_ICU_INTENSET0) = + 1u << (vector & 0x1f); +} diff --git a/bsp/loongson/ls2k0300/drivers/interrupt.h b/bsp/loongson/ls2k0300/drivers/interrupt.h new file mode 100644 index 0000000000000000000000000000000000000000..666aef4b716e57ad5a8da2ce91c49356e7cad627 --- /dev/null +++ b/bsp/loongson/ls2k0300/drivers/interrupt.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +#ifndef __INTERRUPT_H__ +#define __INTERRUPT_H__ + +#include + +/* LS2K0300 has 64 interrupt sources connected to the on-chip ICU */ +#define LS2K_IRQ_NUM 64 + +/* the ICU is cascaded on CPU interrupt HWI2 (interrupt line 4) */ +#define LS2K_ICU_CASCADE_IRQ 4 +/* the ICU routes to (parent irq - 2) */ +#define LS2K_ICU_CASCADE_LINE (LS2K_ICU_CASCADE_IRQ - 2) + +void rt_hw_icu_init(void); +void rt_hw_interrupt_handler(int vector); + +#endif /* __INTERRUPT_H__ */ diff --git a/bsp/loongson/ls2k0300/drivers/ls2k0300.h b/bsp/loongson/ls2k0300/drivers/ls2k0300.h new file mode 100644 index 0000000000000000000000000000000000000000..0b5f2a4e597394e3c63ce129443ce3c589ab0e96 --- /dev/null +++ b/bsp/loongson/ls2k0300/drivers/ls2k0300.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +#ifndef __LS2K0300_H__ +#define __LS2K0300_H__ + +#include + +/* Direct mapping windows installed by U-Boot */ +#define LS2K_CACHED_BASE 0x9000000000000000UL +#define LS2K_UNCACHED_BASE 0x8000000000000000UL + +#define LS2K_PHYS_TO_UNCACHED(addr) (LS2K_UNCACHED_BASE | (rt_ubase_t)(addr)) + +/* On-chip peripheral base addresses */ +#define LS2K_UART0_BASE 0x16100000UL +#define LS2K_UART1_BASE 0x16100400UL +#define LS2K_UART_CLK 100000000UL + +#define LS2K_ICU_BASE 0x16001400UL + +#define LS2K_GPIO_BASE 0x16104000UL +#define LS2K_GPIO_BANK_STRIDE 0x10UL +#define LS2K_GPIO_BANKS 7 + +#define LS2K_RTC_BASE 0x16128000UL + +/* power management / reset controller (Linux syscon-reboot uses offset 0 bit0) */ +#define LS2K_PMC_BASE 0x16124000UL +#define LS2K_PMC_RESET 0x1 + +/* Interrupt controller registers */ +#define LS2K_ICU_ISR0 0x20 +#define LS2K_ICU_ISR1 0x60 +#define LS2K_ICU_INTEN0 0x24 +#define LS2K_ICU_INTEN1 0x64 +#define LS2K_ICU_INTENSET0 0x28 +#define LS2K_ICU_INTENSET1 0x68 +#define LS2K_ICU_INTENCLR0 0x2c +#define LS2K_ICU_INTENCLR1 0x6c +#define LS2K_ICU_INTPOL0 0x30 +#define LS2K_ICU_INTPOL1 0x70 +#define LS2K_ICU_INTEDGE0 0x34 +#define LS2K_ICU_INTEDGE1 0x74 +#define LS2K_ICU_INTAUTO0 0x3c +#define LS2K_ICU_INTAUTO1 0x7c + +/* 16550 compatible UART registers */ +#define LS2K_UART_RBR 0x00 +#define LS2K_UART_THR 0x00 +#define LS2K_UART_DLL 0x00 +#define LS2K_UART_IER 0x01 +#define LS2K_UART_DLM 0x01 +#define LS2K_UART_IIR 0x02 +#define LS2K_UART_FCR 0x02 +#define LS2K_UART_LCR 0x03 +#define LS2K_UART_MCR 0x04 +#define LS2K_UART_LSR 0x05 +#define LS2K_UART_MSR 0x06 + +#define LS2K_UART_LSR_DR 0x01 +#define LS2K_UART_LSR_THRE 0x20 +#define LS2K_UART_IER_RDI 0x01 +#define LS2K_UART_LCR_DLAB 0x80 +#define LS2K_UART_LCR_8N1 0x03 +#define LS2K_UART_FCR_ENABLE 0x01 +#define LS2K_UART_FCR_CLEAR 0x06 + +#define LS2K_REG32(base, off) \ + (*(volatile rt_uint32_t *)((rt_ubase_t)(base) + (rt_uint32_t)(off))) +#define LS2K_REG8(base, off) \ + (*(volatile rt_uint8_t *)((rt_ubase_t)(base) + (rt_uint32_t)(off))) + +#endif /* __LS2K0300_H__ */ diff --git a/bsp/loongson/ls2k0300/figures/block_diagram.jpg b/bsp/loongson/ls2k0300/figures/block_diagram.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e13475fbcec02704ff8bf23137638d080de6c276 Binary files /dev/null and b/bsp/loongson/ls2k0300/figures/block_diagram.jpg differ diff --git a/bsp/loongson/ls2k0300/figures/board_interfaces.jpg b/bsp/loongson/ls2k0300/figures/board_interfaces.jpg new file mode 100644 index 0000000000000000000000000000000000000000..896ee72b706b4b2732121d756694a5da705dc661 Binary files /dev/null and b/bsp/loongson/ls2k0300/figures/board_interfaces.jpg differ diff --git a/bsp/loongson/ls2k0300/figures/pin_mux.png b/bsp/loongson/ls2k0300/figures/pin_mux.png new file mode 100644 index 0000000000000000000000000000000000000000..174ea16fd3cc6af864c92b1bcbe11527ea1fbaca Binary files /dev/null and b/bsp/loongson/ls2k0300/figures/pin_mux.png differ diff --git a/bsp/loongson/ls2k0300/ls2k0300.lds b/bsp/loongson/ls2k0300/ls2k0300.lds new file mode 100644 index 0000000000000000000000000000000000000000..6b2977899c7fbab20354768645e9624f30cc47e9 --- /dev/null +++ b/bsp/loongson/ls2k0300/ls2k0300.lds @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LS2K0300 + */ + +OUTPUT_ARCH(loongarch) +ENTRY(_start) + +/* U-Boot loads the image into the cached direct mapping window, + * physical address 0x00200000 (2MB), which is the same region used + * by the vendor U-Boot for the Linux kernel. + */ +BASE_ADDR = 0x9000000000200000; + +SECTIONS +{ + . = BASE_ADDR; + + .text : { + *(.text.start) + } + + /* the exception entry must be 4KB aligned */ + . = ALIGN(4096); + .exc_vectors : { + *(.exc_vectors) + } + + .text.main : { + *(.text) *(.text.*) + } + + .rodata : { + *(.rodata) *(.rodata.*) + *(.srodata) *(.srodata.*) + + /* msh command table */ + . = ALIGN(8); + __fsymtab_start = .; + KEEP(*(FSymTab)) + __fsymtab_end = .; + + . = ALIGN(8); + __vsymtab_start = .; + KEEP(*(VSymTab)) + __vsymtab_end = .; + + /* component/board/app init table, sorted by init level */ + . = ALIGN(8); + __rt_init_start = .; + KEEP(*(SORT(.rti_fn*))) + __rt_init_end = .; + } + + .data : { + *(.data) *(.data.*) + *(.sdata) *(.sdata.*) + } + + . = ALIGN(8); + __bss_start = .; + .bss : { + *(.bss) *(.bss.*) + *(.sbss) *(.sbss.*) + *(COMMON) + } + . = ALIGN(8); + __bss_end = .; + + /* system stack, used before the scheduler starts */ + . = ALIGN(4096); + _system_stack = .; + . += 0x20000; + _system_stack_top = .; + + /* RT-Thread heap */ + . = ALIGN(4096); + __heap_start = .; + . += 0x2000000; + __heap_end = .; + + /DISCARD/ : { + *(.eh_frame) *(.comment) *(.note*) + *(.MIPS.*) + } +} diff --git a/bsp/loongson/ls2k0300/rtconfig.h b/bsp/loongson/ls2k0300/rtconfig.h new file mode 100644 index 0000000000000000000000000000000000000000..14181a7f66772fce8d01aeb637238997bc75df0b --- /dev/null +++ b/bsp/loongson/ls2k0300/rtconfig.h @@ -0,0 +1,97 @@ +#ifndef RT_CONFIG_H__ +#define RT_CONFIG_H__ + +/* RT-Thread Kernel */ + +#define RT_NAME_MAX 16 +#define RT_CPUS_NR 1 +#define RT_ALIGN_SIZE 8 +#define RT_THREAD_PRIORITY_32 +#define RT_THREAD_PRIORITY_MAX 32 +#define RT_TICK_PER_SECOND 1000 +#define RT_USING_HOOK +#define RT_HOOK_USING_FUNC_PTR +#define RT_USING_IDLE_HOOK +#define RT_IDLE_HOOK_LIST_SIZE 4 +#define IDLE_THREAD_STACK_SIZE 4096 + +/* kservice options */ + +/* end of kservice options */ +#define RT_USING_DEBUG +#define RT_DEBUGING_ASSERT +#define RT_DEBUGING_CONTEXT + +/* Inter-Thread communication */ + +#define RT_USING_SEMAPHORE +#define RT_USING_MUTEX +#define RT_USING_EVENT +#define RT_USING_MAILBOX +#define RT_USING_MESSAGEQUEUE +/* end of Inter-Thread communication */ + +/* Memory Management */ + +#define RT_USING_MEMPOOL +#define RT_USING_SMALL_MEM +#define RT_USING_SMALL_MEM_AS_HEAP +#define RT_USING_HEAP +/* end of Memory Management */ +#define RT_USING_DEVICE +#define RT_USING_CONSOLE +#define RT_CONSOLEBUF_SIZE 256 +#define RT_CONSOLE_DEVICE_NAME "uart0" +/* end of RT-Thread Kernel */ + +/* Architecture */ + +#define ARCH_CPU_64BIT +#define ARCH_LOONGARCH +#define ARCH_LOONGARCH64 +#define RT_USING_CACHE +#define SOC_LS2K0300 +/* end of Architecture */ + +/* RT-Thread Components */ + +#define RT_USING_COMPONENTS_INIT +#define RT_USING_USER_MAIN +#define RT_MAIN_THREAD_STACK_SIZE 8192 +#define RT_MAIN_THREAD_PRIORITY 10 +#define RT_USING_MSH +#define RT_USING_FINSH +#define FINSH_USING_MSH +#define FINSH_THREAD_NAME "tshell" +#define FINSH_THREAD_PRIORITY 20 +#define FINSH_THREAD_STACK_SIZE 8192 +#define FINSH_USING_HISTORY +#define FINSH_HISTORY_LINES 5 +#define FINSH_USING_SYMTAB +#define FINSH_CMD_SIZE 80 +#define MSH_USING_BUILT_IN_COMMANDS +#define FINSH_USING_DESCRIPTION +#define FINSH_ARG_MAX 10 + +/* Device Drivers */ + +#define RT_USING_DEVICE_IPC +#define RT_UNAMED_PIPE_NUMBER 64 +#define RT_USING_PIN +#define RT_USING_RTC + +/* On-chip peripheral drivers */ + +#define BSP_USING_UART0 +#define BSP_USING_UART_IRQ +#define BSP_USING_ICU +#define BSP_USING_GPIO +#define BSP_USING_RTC +/* end of On-chip peripheral drivers */ + +/* end of Device Drivers */ + +#define RT_VER_NUM 0x50400 +#define RT_BACKTRACE_LEVEL_MAX_NR 32 + +#endif diff --git a/bsp/loongson/ls2k0300/rtconfig.py b/bsp/loongson/ls2k0300/rtconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..778361e786b97673d593def9222c9c6541ad56f4 --- /dev/null +++ b/bsp/loongson/ls2k0300/rtconfig.py @@ -0,0 +1,65 @@ +import os +import sys + +# toolchains options +ARCH = 'loongarch' +CPU = 'la264' +CROSS_TOOL = 'gcc' + +if os.getenv('RTT_ROOT'): + RTT_ROOT = os.getenv('RTT_ROOT') +else: + RTT_ROOT = os.path.normpath(os.path.join(os.getcwd(), '../../..')) + +if os.getenv('RTT_CC'): + CROSS_TOOL = os.getenv('RTT_CC') + +PLATFORM = 'gcc' + +if CROSS_TOOL == 'gcc': + # Loongson LoongArch64 cross toolchain + EXEC_PATH = '/opt/ls_2k0300_env/loongson-gnu-toolchain-8.3-x86_64-loongarch64-linux-gnu-rc1.6/bin' +else: + print('================ERROR===========================') + print('Not support %s yet!' % CROSS_TOOL) + print('=================================================') + exit(0) + +if os.getenv('RTT_EXEC_PATH'): + EXEC_PATH = os.getenv('RTT_EXEC_PATH') + +BUILD = 'debug' + +PREFIX = 'loongarch64-linux-gnu-' +CC = PREFIX + 'gcc' +CXX = PREFIX + 'g++' +AS = PREFIX + 'gcc' +AR = PREFIX + 'ar' +LINK = PREFIX + 'gcc' +TARGET_EXT = 'elf' +SIZE = PREFIX + 'size' +OBJDUMP = PREFIX + 'objdump' +OBJCPY = PREFIX + 'objcopy' +READELF = PREFIX + 'readelf' + +DEVICE = ' -march=loongarch64 -mabi=lp64s -msoft-float' + +CFLAGS = DEVICE + ' -std=gnu99 -fno-pic -fno-plt -fno-builtin' \ + ' -ffunction-sections -fdata-sections -fno-common -fomit-frame-pointer' +AFLAGS = DEVICE + ' -fno-pic -fno-builtin -x assembler-with-cpp' +LFLAGS = DEVICE + ' -nostdlib -nostartfiles -static' \ + ' -Wl,--gc-sections,-Map=rtthread.map,-cref,-u,_start' \ + ' -T ls2k0300.lds -lgcc' +CXXFLAGS = CFLAGS + +CPATH = '' +LPATH = '' + +if BUILD == 'debug': + CFLAGS += ' -O0 -gdwarf-2' + AFLAGS += ' -gdwarf-2' +else: + CFLAGS += ' -O2' + +DUMP_ACTION = OBJDUMP + ' -D -S $TARGET > rtthread.asm\n' +POST_ACTION = OBJCPY + ' -O binary $TARGET rtthread.bin\n' + SIZE + ' $TARGET \n' diff --git a/libcpu/Kconfig b/libcpu/Kconfig index 7f3dfca11f1f632f8b81b6263b70139c0397f485..302824180b19cfc4e0fa82784b0a9bc34a0b0742 100644 --- a/libcpu/Kconfig +++ b/libcpu/Kconfig @@ -233,6 +233,15 @@ config ARCH_MIPS_XBURST bool select ARCH_MIPS +config ARCH_LOONGARCH + bool + +config ARCH_LOONGARCH64 + bool + select ARCH_LOONGARCH + select ARCH_CPU_64BIT + select RT_USING_CACHE + config ARCH_ANDES bool diff --git a/libcpu/loongarch/SConscript b/libcpu/loongarch/SConscript new file mode 100644 index 0000000000000000000000000000000000000000..8b9b90d220dde4cd04bc4cd0ae09dcdaec1af02c --- /dev/null +++ b/libcpu/loongarch/SConscript @@ -0,0 +1,18 @@ +# RT-Thread building script for bridge + +import os +from building import * + +Import('rtconfig') + +cwd = GetCurrentDir() +group = [] + +# add common code files +group = group + SConscript(os.path.join('common', 'SConscript')) + +# cpu porting code files +if rtconfig.CPU != 'common': + group = group + SConscript(os.path.join(rtconfig.CPU, 'SConscript')) + +Return('group') diff --git a/libcpu/loongarch/common/SConscript b/libcpu/loongarch/common/SConscript new file mode 100644 index 0000000000000000000000000000000000000000..9993fcc2b52eb9bf8df959de3435743b9f03c360 --- /dev/null +++ b/libcpu/loongarch/common/SConscript @@ -0,0 +1,11 @@ +# RT-Thread building script for component + +from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') + Glob('*.S') +CPPPATH = [cwd, os.path.join(cwd, 'include')] + +group = DefineGroup('CPU', src, depend = [''], CPPPATH = CPPPATH) + +Return('group') diff --git a/libcpu/loongarch/common/asm.h b/libcpu/loongarch/common/asm.h new file mode 100644 index 0000000000000000000000000000000000000000..4ea405f78db98cfee4869eb28105151e5f8aa076 --- /dev/null +++ b/libcpu/loongarch/common/asm.h @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LoongArch64 + */ + +#ifndef __LOONGARCH_ASM_H__ +#define __LOONGARCH_ASM_H__ + +/* LoongArch control status registers */ +#define LOONGARCH_CSR_CRMD 0x0 +#define LOONGARCH_CSR_PRMD 0x1 +#define LOONGARCH_CSR_EUEN 0x2 +#define LOONGARCH_CSR_MISC 0x3 +#define LOONGARCH_CSR_ECFG 0x4 +#define LOONGARCH_CSR_ESTAT 0x5 +#define LOONGARCH_CSR_ERA 0x6 +#define LOONGARCH_CSR_BADV 0x7 +#define LOONGARCH_CSR_BADI 0x8 +#define LOONGARCH_CSR_EENTRY 0xc +#define LOONGARCH_CSR_CPUID 0x20 +#define LOONGARCH_CSR_SAVE0 0x30 +#define LOONGARCH_CSR_SAVE1 0x31 +#define LOONGARCH_CSR_SAVE2 0x32 +#define LOONGARCH_CSR_SAVE3 0x33 +#define LOONGARCH_CSR_TID 0x40 +#define LOONGARCH_CSR_TCFG 0x41 +#define LOONGARCH_CSR_TVAL 0x42 +#define LOONGARCH_CSR_CNTC 0x43 +#define LOONGARCH_CSR_TICLR 0x44 +#define LOONGARCH_CSR_DMW0 0x180 +#define LOONGARCH_CSR_DMW1 0x181 + +/* CRMD bits */ +#define CSR_CRMD_PLV 0x3 +#define CSR_CRMD_IE 0x4 +#define CSR_CRMD_DA 0x8 +#define CSR_CRMD_PG 0x10 + +/* PRMD bits */ +#define CSR_PRMD_PPLV 0x3 +#define CSR_PRMD_PIE 0x4 + +/* ECFG bits */ +#define CSR_ECFG_VS_SHIFT 16 +#define CSR_ECFG_VS_64 (4 << CSR_ECFG_VS_SHIFT) /* 2^(4+2) = 64 bytes */ +#define CSR_ECFG_IM_SHIFT 0 + +/* ESTAT fields */ +#define CSR_ESTAT_IS_SHIFT 0 +#define CSR_ESTAT_IS_MASK 0x1fff +#define CSR_ESTAT_EXC_SHIFT 16 +#define CSR_ESTAT_EXC_MASK 0x3f + +/* Interrupt sources of the CPU (ECFG.IM / ESTAT.IS) */ +#define LOONGARCH_IRQ_SWI0 0 +#define LOONGARCH_IRQ_SWI1 1 +#define LOONGARCH_IRQ_HWI0 2 +#define LOONGARCH_IRQ_HWI1 3 +#define LOONGARCH_IRQ_HWI2 4 +#define LOONGARCH_IRQ_HWI3 5 +#define LOONGARCH_IRQ_HWI4 6 +#define LOONGARCH_IRQ_HWI5 7 +#define LOONGARCH_IRQ_HWI6 8 +#define LOONGARCH_IRQ_HWI7 9 +#define LOONGARCH_IRQ_TIMER 11 +#define LOONGARCH_IRQ_IPI 12 + +/* TCFG bits */ +#define CSR_TCFG_EN 0x1 +#define CSR_TCFG_PERIOD 0x2 +#define CSR_TCFG_VAL_SHIFT 2 + +/* TICLR bits */ +#define CSR_TICLR_TI 0x1 + +/* DMW bits */ +#define CSR_DMW_PLV0 0x1 +#define CSR_DMW_MAT 0x10 + +/* Direct mapping windows used by U-Boot and this port */ +#define LOONGARCH_DMW0_BASE 0x8000000000000000 /* uncached */ +#define LOONGARCH_DMW1_BASE 0x9000000000000000 /* cached */ + +/* + * Stack frame layout, it must be kept in sync with + * struct rt_hw_stack_frame in loongarch.h + */ +#define TF_R0 0 +#define TF_R1 (1 * 8) +#define TF_R2 (2 * 8) +#define TF_R3 (3 * 8) +#define TF_R4 (4 * 8) +#define TF_R5 (5 * 8) +#define TF_R6 (6 * 8) +#define TF_R7 (7 * 8) +#define TF_R8 (8 * 8) +#define TF_R9 (9 * 8) +#define TF_R10 (10 * 8) +#define TF_R11 (11 * 8) +#define TF_R12 (12 * 8) +#define TF_R13 (13 * 8) +#define TF_R14 (14 * 8) +#define TF_R15 (15 * 8) +#define TF_R16 (16 * 8) +#define TF_R17 (17 * 8) +#define TF_R18 (18 * 8) +#define TF_R19 (19 * 8) +#define TF_R20 (20 * 8) +#define TF_R21 (21 * 8) +#define TF_R22 (22 * 8) +#define TF_R23 (23 * 8) +#define TF_R24 (24 * 8) +#define TF_R25 (25 * 8) +#define TF_R26 (26 * 8) +#define TF_R27 (27 * 8) +#define TF_R28 (28 * 8) +#define TF_R29 (29 * 8) +#define TF_R30 (30 * 8) +#define TF_R31 (31 * 8) +#define TF_ERA 256 +#define TF_PRMD 264 +#define TF_ESTAT 272 +#define TF_SIZE 288 + +#endif /* __LOONGARCH_ASM_H__ */ diff --git a/libcpu/loongarch/common/context_gcc.S b/libcpu/loongarch/common/context_gcc.S new file mode 100644 index 0000000000000000000000000000000000000000..3c2a24e0a5804ed9a59ee0ee3ae2e9555e390004 --- /dev/null +++ b/libcpu/loongarch/common/context_gcc.S @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LoongArch64 + */ + +#ifndef __ASSEMBLY__ +#define __ASSEMBLY__ +#endif + +#include "asm.h" + + /* + * The exception entry (CSR.EENTRY) must be 4KB aligned. Exception + * vectors use EENTRY + Ecode * 0x40, while the 13 CPU interrupts use + * EENTRY + (0x40 + irq) * 0x40, so the table must have 128 entries. + * Every entry jumps to the common trap entry. + */ + .section .exc_vectors, "ax" + .align 12 + .globl _exc_vectors + .type _exc_vectors, @function +_exc_vectors: + .rept 128 + b trap_entry + .fill 15, 4, 0x03400000 /* nop */ + .endr + .size _exc_vectors, . - _exc_vectors + + .text + .align 4 + +/* + * Save the complete interrupted context on the stack. + * $r12/$r13 are used as scratch registers, their original values are + * kept in CSR.SAVE0/SAVE1, which are free outside of an exception. + */ +.macro SAVE_CONTEXT + csrwr $r12, LOONGARCH_CSR_SAVE0 + csrwr $r13, LOONGARCH_CSR_SAVE1 + addi.d $r3, $r3, -TF_SIZE + + st.d $r1, $r3, TF_R1 + st.d $r2, $r3, TF_R2 + addi.d $r12, $r3, TF_SIZE + st.d $r12, $r3, TF_R3 + st.d $r4, $r3, TF_R4 + st.d $r5, $r3, TF_R5 + st.d $r6, $r3, TF_R6 + st.d $r7, $r3, TF_R7 + st.d $r8, $r3, TF_R8 + st.d $r9, $r3, TF_R9 + st.d $r10, $r3, TF_R10 + st.d $r11, $r3, TF_R11 + + csrrd $r12, LOONGARCH_CSR_SAVE0 + st.d $r12, $r3, TF_R12 + csrrd $r12, LOONGARCH_CSR_SAVE1 + st.d $r12, $r3, TF_R13 + + st.d $r14, $r3, TF_R14 + st.d $r15, $r3, TF_R15 + st.d $r16, $r3, TF_R16 + st.d $r17, $r3, TF_R17 + st.d $r18, $r3, TF_R18 + st.d $r19, $r3, TF_R19 + st.d $r20, $r3, TF_R20 + st.d $r21, $r3, TF_R21 + st.d $r22, $r3, TF_R22 + st.d $r23, $r3, TF_R23 + st.d $r24, $r3, TF_R24 + st.d $r25, $r3, TF_R25 + st.d $r26, $r3, TF_R26 + st.d $r27, $r3, TF_R27 + st.d $r28, $r3, TF_R28 + st.d $r29, $r3, TF_R29 + st.d $r30, $r3, TF_R30 + st.d $r31, $r3, TF_R31 + + st.d $zero, $r3, TF_R0 + + csrrd $r12, LOONGARCH_CSR_ERA + st.d $r12, $r3, TF_ERA + csrrd $r12, LOONGARCH_CSR_PRMD + st.d $r12, $r3, TF_PRMD + csrrd $r12, LOONGARCH_CSR_ESTAT + st.d $r12, $r3, TF_ESTAT +.endm + +/* + * Restore the context saved by SAVE_CONTEXT and return from the + * exception with ertn. + */ +.macro RESTORE_CONTEXT + ld.d $r12, $r3, TF_ERA + csrwr $r12, LOONGARCH_CSR_ERA + ld.d $r12, $r3, TF_PRMD + csrwr $r12, LOONGARCH_CSR_PRMD + + ld.d $r12, $r3, TF_R12 + csrwr $r12, LOONGARCH_CSR_SAVE0 + ld.d $r13, $r3, TF_R13 + csrwr $r13, LOONGARCH_CSR_SAVE1 + + ld.d $r1, $r3, TF_R1 + ld.d $r2, $r3, TF_R2 + ld.d $r4, $r3, TF_R4 + ld.d $r5, $r3, TF_R5 + ld.d $r6, $r3, TF_R6 + ld.d $r7, $r3, TF_R7 + ld.d $r8, $r3, TF_R8 + ld.d $r9, $r3, TF_R9 + ld.d $r10, $r3, TF_R10 + ld.d $r11, $r3, TF_R11 + ld.d $r14, $r3, TF_R14 + ld.d $r15, $r3, TF_R15 + ld.d $r16, $r3, TF_R16 + ld.d $r17, $r3, TF_R17 + ld.d $r18, $r3, TF_R18 + ld.d $r19, $r3, TF_R19 + ld.d $r20, $r3, TF_R20 + ld.d $r21, $r3, TF_R21 + ld.d $r22, $r3, TF_R22 + ld.d $r23, $r3, TF_R23 + ld.d $r24, $r3, TF_R24 + ld.d $r25, $r3, TF_R25 + ld.d $r26, $r3, TF_R26 + ld.d $r27, $r3, TF_R27 + ld.d $r28, $r3, TF_R28 + ld.d $r29, $r3, TF_R29 + ld.d $r30, $r3, TF_R30 + ld.d $r31, $r3, TF_R31 + + addi.d $r3, $r3, TF_SIZE + + csrrd $r13, LOONGARCH_CSR_SAVE1 + csrrd $r12, LOONGARCH_CSR_SAVE0 + ertn +.endm + +/* + * Common trap entry, reached from every slot of the exception vector + * table. The trap reason is decoded from CSR.ESTAT by C code. + */ + .align 4 + .globl trap_entry + .type trap_entry, @function +trap_entry: + SAVE_CONTEXT + + move $r4, $r3 + bl rt_hw_trap_entry + + /* switch to another thread if the scheduler requested it */ + la.local $r12, rt_thread_switch_interrupt_flag + ld.d $r13, $r12, 0 + beqz $r13, 1f + + st.d $zero, $r12, 0 + + la.local $r12, rt_interrupt_from_thread + ld.d $r13, $r12, 0 + st.d $r3, $r13, 0 + + la.local $r12, rt_interrupt_to_thread + ld.d $r13, $r12, 0 + ld.d $r3, $r13, 0 +1: + RESTORE_CONTEXT + .size trap_entry, . - trap_entry + +/* + * void rt_hw_context_switch(rt_ubase_t from, rt_ubase_t to) + * a0: address of the "from" thread stack pointer + * a1: address of the "to" thread stack pointer + */ + .align 4 + .globl rt_hw_context_switch + .type rt_hw_context_switch, @function +rt_hw_context_switch: + SAVE_CONTEXT + + /* return to the caller of rt_hw_context_switch */ + st.d $r1, $r3, TF_ERA + csrrd $r12, LOONGARCH_CSR_CRMD + srli.d $r12, $r12, 2 + andi $r12, $r12, CSR_PRMD_PIE + st.d $r12, $r3, TF_PRMD + + st.d $r3, $r4, 0 + ld.d $r3, $r5, 0 + + RESTORE_CONTEXT + .size rt_hw_context_switch, . - rt_hw_context_switch + +/* + * void rt_hw_context_switch_to(rt_ubase_t to) + * a0: address of the "to" thread stack pointer + */ + .align 4 + .globl rt_hw_context_switch_to + .type rt_hw_context_switch_to, @function +rt_hw_context_switch_to: + ld.d $r3, $r4, 0 + RESTORE_CONTEXT + .size rt_hw_context_switch_to, . - rt_hw_context_switch_to diff --git a/libcpu/loongarch/common/cpuport.c b/libcpu/loongarch/common/cpuport.c new file mode 100644 index 0000000000000000000000000000000000000000..5229ea162cff4dfd25f58331d1de24209732e880 --- /dev/null +++ b/libcpu/loongarch/common/cpuport.c @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LoongArch64 + */ + +#include +#include + +#include "loongarch.h" + +#define LOONGARCH_CACHE_LINE_SIZE 64 + +static const char *exception_name[] = { + "Interrupt", + "Page Invalid for Load", + "Page Invalid for Store", + "Page Modify Exception", + "Page Privilege Illegality", + "Address Error", + "Address Alignment Error", + "Bound Check Error", + "System Call", + "Breakpoint", + "Instruction Non-defined", + "Instruction Privilege Error", + "Floating Point Disabled", + "Floating Point Exception", + "TLB Refill for Load", + "TLB Refill for Store", + "TLB Invalid for Instruction Fetch", + "TLB Invalid for Load", + "TLB Invalid for Store", + "TLB Modify Exception", + "TLB Privilege Illegality", + "TLB Read Error", + "TLB Execute Error", + "TLB Page Invalid", +}; + +void rt_hw_exception_dump(struct rt_hw_stack_frame *frame, rt_uint32_t ecode) +{ + const char *name = "Unknown"; + int i; + + if (ecode < sizeof(exception_name) / sizeof(exception_name[0])) + { + name = exception_name[ecode]; + } + + rt_kprintf("\nException: %s (Ecode 0x%02x)\n", name, ecode); + rt_kprintf("ERA: 0x%016lx BADV: 0x%016lx ESTAT: 0x%016lx\n", + (unsigned long)frame->era, + (unsigned long)loongarch_read_csr(LOONGARCH_CSR_BADV), + (unsigned long)frame->estat); + + for (i = 0; i < 32; i++) + { + rt_kprintf("$r%-2d: 0x%016lx%s", i, (unsigned long)frame->regs[i], + ((i % 4) == 3) ? "\n" : " "); + } +} + +rt_uint8_t *rt_hw_stack_init(void *tentry, + void *parameter, + rt_uint8_t *stack_addr, + void *texit) +{ + struct rt_hw_stack_frame *frame; + rt_uint8_t *stk; + + stk = (rt_uint8_t *)RT_ALIGN_DOWN((rt_ubase_t)stack_addr, 16); + stk -= sizeof(struct rt_hw_stack_frame); + + frame = (struct rt_hw_stack_frame *)stk; + rt_memset(frame, 0, sizeof(struct rt_hw_stack_frame)); + + frame->regs[1] = (rt_ubase_t)texit; /* $ra */ + frame->regs[3] = (rt_ubase_t)stk + sizeof(struct rt_hw_stack_frame); + frame->regs[4] = (rt_ubase_t)parameter; /* $a0 */ + frame->era = (rt_ubase_t)tentry; + frame->prmd = CSR_PRMD_PIE; /* return with IE=1 */ + + return stk; +} + +#if defined(RT_USING_CACHE) +static void _loongarch_cache_ops(void *addr, int size, int icache, int flush) +{ + rt_ubase_t start, end; + + if (size <= 0) + { + return; + } + + start = (rt_ubase_t)addr & ~(LOONGARCH_CACHE_LINE_SIZE - 1); + end = (rt_ubase_t)addr + size; + + for (; start < end; start += LOONGARCH_CACHE_LINE_SIZE) + { + if (icache) + { + __asm__ __volatile__("cacop 0x10, %0, 0" : : "r"(start) : "memory"); + } + else + { + __asm__ __volatile__("cacop 0x11, %0, 0" : : "r"(start) : "memory"); + } + } + + __asm__ __volatile__("dbar 0" : : : "memory"); + if (icache) + { + __asm__ __volatile__("ibar 0" : : : "memory"); + } + + RT_UNUSED(flush); +} + +void rt_hw_cpu_icache_ops(int ops, void *addr, int size) +{ + RT_UNUSED(ops); + _loongarch_cache_ops(addr, size, 1, 1); +} + +void rt_hw_cpu_dcache_ops(int ops, void *addr, int size) +{ + RT_UNUSED(ops); + _loongarch_cache_ops(addr, size, 0, 1); +} + +void rt_hw_cpu_icache_enable(void) +{ +} + +void rt_hw_cpu_icache_disable(void) +{ +} + +rt_base_t rt_hw_cpu_icache_status(void) +{ + return 1; +} + +void rt_hw_cpu_dcache_enable(void) +{ +} + +void rt_hw_cpu_dcache_disable(void) +{ +} + +rt_base_t rt_hw_cpu_dcache_status(void) +{ + return 1; +} +#endif /* RT_USING_CACHE */ + +rt_weak void rt_hw_cpu_reset(void) +{ + for (;;) + { + __asm__ __volatile__("idle 0"); + } +} + +rt_weak void rt_hw_cpu_shutdown(void) +{ + rt_kprintf("cpu shutdown...\n"); + + for (;;) + { + __asm__ __volatile__("idle 0"); + } +} + +const char *rt_hw_cpu_arch(void) +{ + return "loongarch64"; +} diff --git a/libcpu/loongarch/common/cpuport.h b/libcpu/loongarch/common/cpuport.h new file mode 100644 index 0000000000000000000000000000000000000000..c3ff39a42dac3bd9da8edfb87966121e4466ccca --- /dev/null +++ b/libcpu/loongarch/common/cpuport.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LoongArch64 + */ + +#ifndef CPUPORT_H__ +#define CPUPORT_H__ + +#include + +#ifndef __ASSEMBLY__ + +#include + +#ifndef RT_CPU_CACHE_LINE_SZ +#define RT_CPU_CACHE_LINE_SZ 64 +#endif + +rt_inline void rt_hw_dsb(void) +{ + __asm__ __volatile__("dbar 0" ::: "memory"); +} + +rt_inline void rt_hw_dmb(void) +{ + __asm__ __volatile__("dbar 0" ::: "memory"); +} + +rt_inline void rt_hw_isb(void) +{ + __asm__ __volatile__("ibar 0" ::: "memory"); +} + +#endif /* __ASSEMBLY__ */ + +#endif /* CPUPORT_H__ */ diff --git a/libcpu/loongarch/common/include/ctype.h b/libcpu/loongarch/common/include/ctype.h new file mode 100644 index 0000000000000000000000000000000000000000..25160d745159b3462e437990da464afa327f2459 --- /dev/null +++ b/libcpu/loongarch/common/include/ctype.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread minimal ASCII ctype for the bare metal LoongArch port + * + * The Loongson toolchain is a Linux (glibc) toolchain. Its expands + * isdigit()/tolower() into __ctype_b_loc() calls which do not exist in a + * freestanding image, so provide a small ASCII implementation here. + */ + +#ifndef __CTYPE_H__ +#define __CTYPE_H__ + +#ifdef __cplusplus +extern "C" +{ +#endif + +static inline int isdigit(int c) +{ + return (c >= '0' && c <= '9'); +} + +static inline int isxdigit(int c) +{ + return ((c >= '0' && c <= '9') || + (c >= 'a' && c <= 'f') || + (c >= 'A' && c <= 'F')); +} + +static inline int islower(int c) +{ + return (c >= 'a' && c <= 'z'); +} + +static inline int isupper(int c) +{ + return (c >= 'A' && c <= 'Z'); +} + +static inline int isalpha(int c) +{ + return islower(c) || isupper(c); +} + +static inline int isalnum(int c) +{ + return isalpha(c) || isdigit(c); +} + +static inline int isspace(int c) +{ + return (c == ' ' || c == '\t' || c == '\n' || + c == '\v' || c == '\f' || c == '\r'); +} + +static inline int isprint(int c) +{ + return (c >= 0x20 && c <= 0x7e); +} + +static inline int isgraph(int c) +{ + return (c > 0x20 && c <= 0x7e); +} + +static inline int iscntrl(int c) +{ + return (c >= 0 && c < 0x20) || c == 0x7f; +} + +static inline int ispunct(int c) +{ + return isgraph(c) && !isalnum(c); +} + +static inline int tolower(int c) +{ + return isupper(c) ? c + ('a' - 'A') : c; +} + +static inline int toupper(int c) +{ + return islower(c) ? c - ('a' - 'A') : c; +} + +#ifdef __cplusplus +} +#endif + +#endif /* __CTYPE_H__ */ diff --git a/libcpu/loongarch/common/include/sys/select.h b/libcpu/loongarch/common/include/sys/select.h new file mode 100644 index 0000000000000000000000000000000000000000..e8ecc5ed0d03a9f089deff105ff99dbb6a6e5c12 --- /dev/null +++ b/libcpu/loongarch/common/include/sys/select.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for the bare metal LoongArch port + * + * Minimal for the bare-metal LoongArch port. + * + * The Loongson toolchain is a Linux (glibc) toolchain. glibc's + * includes while it is still defining its + * own POSIX types, so this header must not depend on suseconds_t or on + * . It only provides the fd_set helpers and the prototype + * of select(). + */ + +#ifndef __SYS_SELECT_H__ +#define __SYS_SELECT_H__ + +#include +#include + +/* + * glibc only defines suseconds_t/useconds_t for _XOPEN_SOURCE builds, + * RT-Thread's and rely on them. + */ +#ifndef __suseconds_t_defined +typedef __suseconds_t suseconds_t; +#define __suseconds_t_defined +#endif + +#ifndef __useconds_t_defined +typedef __useconds_t useconds_t; +#define __useconds_t_defined +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifndef FD_SETSIZE +#define FD_SETSIZE 32 +#endif + +typedef long fd_mask; + +#define NBBY 8 +#define NFDBITS (sizeof(fd_mask) * NBBY) + +#ifndef howmany +#define howmany(x, y) (((x) + ((y) - 1)) / (y)) +#endif + +typedef struct fd_set +{ + fd_mask fds_bits[howmany(FD_SETSIZE, NFDBITS)]; +} fd_set; + +#define FD_SET(n, p) ((p)->fds_bits[(n) / NFDBITS] |= ((fd_mask)1 << ((n) % NFDBITS))) +#define FD_CLR(n, p) ((p)->fds_bits[(n) / NFDBITS] &= ~((fd_mask)1 << ((n) % NFDBITS))) +#define FD_ISSET(n, p) ((p)->fds_bits[(n) / NFDBITS] & ((fd_mask)1 << ((n) % NFDBITS))) +#define FD_ZERO(p) \ + do \ + { \ + memset((p), 0, sizeof(*(p))); \ + } while (0) + +struct timeval; + +int select(int nfds, fd_set *readfds, fd_set *writefds, + fd_set *exceptfds, struct timeval *timeout); + +#ifdef __cplusplus +} +#endif + +#endif /* __SYS_SELECT_H__ */ diff --git a/libcpu/loongarch/common/interrupt.c b/libcpu/loongarch/common/interrupt.c new file mode 100644 index 0000000000000000000000000000000000000000..62e9c65fdf303f5334e67939a7608a2ca83469d0 --- /dev/null +++ b/libcpu/loongarch/common/interrupt.c @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LoongArch64 + */ + +#include +#include + +#include "loongarch.h" + +#define MAX_HANDLERS 64 + +static struct rt_irq_desc irq_desc[MAX_HANDLERS]; + +volatile rt_ubase_t rt_interrupt_from_thread; +volatile rt_ubase_t rt_interrupt_to_thread; +volatile rt_ubase_t rt_thread_switch_interrupt_flag; + +rt_weak void rt_hw_hwi_dispatch(rt_uint32_t hwi) +{ + RT_UNUSED(hwi); +} + +void rt_hw_trap_entry(struct rt_hw_stack_frame *frame) +{ + rt_uint32_t estat = (rt_uint32_t)frame->estat; + rt_uint32_t ecode = (estat >> CSR_ESTAT_EXC_SHIFT) & CSR_ESTAT_EXC_MASK; + + if (ecode == EXCCODE_INT) + { + rt_uint32_t is = estat & CSR_ESTAT_IS_MASK; + + rt_interrupt_enter(); + + if (is & (1u << LOONGARCH_IRQ_TIMER)) + { + loongarch_write_csr(LOONGARCH_CSR_TICLR, CSR_TICLR_TI); + rt_tick_increase(); + } + + if (is & (1u << LOONGARCH_IRQ_HWI2)) + { + /* the SoC interrupt controller is cascaded on HWI2 */ + rt_hw_hwi_dispatch(LOONGARCH_IRQ_HWI2); + } + + if (is & (1u << LOONGARCH_IRQ_SWI0)) + { + loongarch_write_csr(LOONGARCH_CSR_MISC, 0x1); + } + + if (is & (1u << LOONGARCH_IRQ_SWI1)) + { + loongarch_write_csr(LOONGARCH_CSR_MISC, 0x2); + } + + rt_interrupt_leave(); + } + else + { + rt_hw_exception_dump(frame, ecode); + rt_hw_cpu_shutdown(); + } +} + +rt_base_t rt_hw_interrupt_disable(void) +{ + rt_base_t crmd = (rt_base_t)loongarch_read_csr(LOONGARCH_CSR_CRMD); + + loongarch_write_csr(LOONGARCH_CSR_CRMD, crmd & ~CSR_CRMD_IE); + loongarch_dbar(); + + return crmd; +} + +void rt_hw_interrupt_enable(rt_base_t level) +{ + loongarch_write_csr(LOONGARCH_CSR_CRMD, level); + loongarch_dbar(); +} + +rt_bool_t rt_hw_interrupt_is_disabled(void) +{ + return (loongarch_read_csr(LOONGARCH_CSR_CRMD) & CSR_CRMD_IE) ? RT_FALSE : RT_TRUE; +} + +void rt_hw_context_switch_interrupt(rt_ubase_t from, rt_ubase_t to, + rt_thread_t from_thread, rt_thread_t to_thread) +{ + RT_UNUSED(from_thread); + RT_UNUSED(to_thread); + + if (rt_thread_switch_interrupt_flag == 0) + { + rt_thread_switch_interrupt_flag = 1; + rt_interrupt_from_thread = from; + } + rt_interrupt_to_thread = to; +} + +void rt_hw_interrupt_init(void) +{ + rt_memset(irq_desc, 0, sizeof(irq_desc)); +} + +rt_isr_handler_t rt_hw_interrupt_install(int vector, + rt_isr_handler_t handler, + void *param, + const char *name) +{ + rt_isr_handler_t old_handler = RT_NULL; + + if (vector >= 0 && vector < MAX_HANDLERS) + { + old_handler = irq_desc[vector].handler; + + if (handler != RT_NULL) + { + irq_desc[vector].handler = handler; + irq_desc[vector].param = param; +#ifdef RT_USING_INTERRUPT_INFO + rt_snprintf(irq_desc[vector].name, RT_NAME_MAX - 1, "%s", + name ? name : "irq"); + irq_desc[vector].counter = 0; +#endif + } + } + + return old_handler; +} + +void rt_hw_interrupt_uninstall(int vector, + rt_isr_handler_t handler, + void *param) +{ + if (vector >= 0 && vector < MAX_HANDLERS) + { + if (irq_desc[vector].handler == handler && + irq_desc[vector].param == param) + { + irq_desc[vector].handler = RT_NULL; + irq_desc[vector].param = RT_NULL; + } + } +} + +void rt_hw_interrupt_handler(int vector) +{ + struct rt_irq_desc *desc; + rt_isr_handler_t handler; + + if (vector < 0 || vector >= MAX_HANDLERS) + { + return; + } + + desc = &irq_desc[vector]; + handler = desc->handler; + + if (handler != RT_NULL) + { +#ifdef RT_USING_INTERRUPT_INFO + desc->counter++; +#endif + handler(vector, desc->param); + } +} + +rt_weak void rt_hw_interrupt_mask(int vector) +{ + RT_UNUSED(vector); +} + +rt_weak void rt_hw_interrupt_umask(int vector) +{ + RT_UNUSED(vector); +} diff --git a/libcpu/loongarch/common/libc.c b/libcpu/loongarch/common/libc.c new file mode 100644 index 0000000000000000000000000000000000000000..9648d679c4f636c1b08e47c4b881e62af4953064 --- /dev/null +++ b/libcpu/loongarch/common/libc.c @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread minimal libc helpers for the bare metal LoongArch port + * + * The Linux hosted toolchain does not provide a freestanding libc, several + * kernel components (for example the pin device) call atoi(). + */ + +#include + +int atoi(const char *str) +{ + int value = 0; + int sign = 1; + + if (str == RT_NULL) + { + return 0; + } + + while (*str == ' ' || *str == '\t') + { + str++; + } + + if (*str == '-') + { + sign = -1; + str++; + } + else if (*str == '+') + { + str++; + } + + while (*str >= '0' && *str <= '9') + { + value = value * 10 + (*str - '0'); + str++; + } + + return sign * value; +} + +long atol(const char *str) +{ + long value = 0; + int sign = 1; + + if (str == RT_NULL) + { + return 0; + } + + while (*str == ' ' || *str == '\t') + { + str++; + } + + if (*str == '-') + { + sign = -1; + str++; + } + else if (*str == '+') + { + str++; + } + + while (*str >= '0' && *str <= '9') + { + value = value * 10 + (*str - '0'); + str++; + } + + return sign * value; +} diff --git a/libcpu/loongarch/common/loongarch.h b/libcpu/loongarch/common/loongarch.h new file mode 100644 index 0000000000000000000000000000000000000000..09b5c6e4d432c7ecc868e7951a7399214ec141be --- /dev/null +++ b/libcpu/loongarch/common/loongarch.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LoongArch64 + */ + +#ifndef __LOONGARCH_H__ +#define __LOONGARCH_H__ + +#include + +#include "asm.h" + +#ifndef __ASSEMBLY__ + +/* Exception codes (ESTAT.Ecode) */ +#define EXCCODE_INT 0x00 +#define EXCCODE_PIL 0x01 +#define EXCCODE_PIS 0x02 +#define EXCCODE_PME 0x03 +#define EXCCODE_PPI 0x04 +#define EXCCODE_ADE 0x05 +#define EXCCODE_ALE 0x06 +#define EXCCODE_BCE 0x07 +#define EXCCODE_SYS 0x08 +#define EXCCODE_BRK 0x09 +#define EXCCODE_INE 0x0a +#define EXCCODE_IPE 0x0b +#define EXCCODE_FPD 0x0c +#define EXCCODE_FPE 0x0d +#define EXCCODE_TLBL 0x0e +#define EXCCODE_TLBS 0x0f +#define EXCCODE_TLBI 0x10 +#define EXCCODE_TLBM 0x11 +#define EXCCODE_TLBNR 0x12 +#define EXCCODE_TLBNX 0x13 +#define EXCCODE_TLBPE 0x14 +#define EXCCODE_TLBRE 0x3f +#define EXCCODE_TLBR 0x3e + +/* Exception entry vector area: 64 exception + 64 interrupt vectors */ +#define LOONGARCH_VECSIZE 0x40 +#define LOONGARCH_VECNUM 128 + +struct rt_hw_stack_frame +{ + rt_ubase_t regs[32]; /* $r0 - $r31 */ + rt_ubase_t era; /* exception return address */ + rt_ubase_t prmd; /* previous mode */ + rt_ubase_t estat; /* exception status */ + rt_ubase_t pad; /* keep the frame 16B aligned */ +}; + +#define _LOONGARCH_STR(x) #x +#define LOONGARCH_STR(x) _LOONGARCH_STR(x) + +#define loongarch_read_csr(csr) \ + ({ \ + rt_ubase_t __value; \ + __asm__ __volatile__("csrrd %0, " LOONGARCH_STR(csr) \ + : "=r"(__value)); \ + __value; \ + }) + +#define loongarch_write_csr(csr, value) \ + do \ + { \ + rt_ubase_t __value = (rt_ubase_t)(value); \ + __asm__ __volatile__("csrwr %0, " LOONGARCH_STR(csr) \ + : "+r"(__value)); \ + } while (0) + +static inline rt_uint64_t loongarch_read_time(void) +{ + rt_uint64_t value; + + __asm__ __volatile__("rdtime.d %0, $r0" : "=r"(value)); + + return value; +} + +static inline void loongarch_ibar(void) +{ + __asm__ __volatile__("ibar 0" ::: "memory"); +} + +static inline void loongarch_dbar(void) +{ + __asm__ __volatile__("dbar 0" ::: "memory"); +} + +void rt_hw_trap_entry(struct rt_hw_stack_frame *frame); +void rt_hw_exception_dump(struct rt_hw_stack_frame *frame, rt_uint32_t ecode); +void rt_hw_hwi_dispatch(rt_uint32_t hwi); + +#endif /* __ASSEMBLY__ */ + +#endif /* __LOONGARCH_H__ */ diff --git a/libcpu/loongarch/la264/SConscript b/libcpu/loongarch/la264/SConscript new file mode 100644 index 0000000000000000000000000000000000000000..414e0652304bf53b4f46365c45a60603363bf322 --- /dev/null +++ b/libcpu/loongarch/la264/SConscript @@ -0,0 +1,12 @@ +# RT-Thread building script for component + +import os +from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') + Glob('*.S') +CPPPATH = [cwd, os.path.join(cwd, '..', 'common')] + +group = DefineGroup('CPU', src, depend = [''], CPPPATH = CPPPATH) + +Return('group') diff --git a/libcpu/loongarch/la264/start_gcc.S b/libcpu/loongarch/la264/start_gcc.S new file mode 100644 index 0000000000000000000000000000000000000000..69054b6fb3f324e89a2eb06f9aa69fbc46ab1cc6 --- /dev/null +++ b/libcpu/loongarch/la264/start_gcc.S @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LoongArch64 + */ + +#ifndef __ASSEMBLY__ +#define __ASSEMBLY__ +#endif + +#include "asm.h" + + .section .text.start, "ax" + .globl _start + .type _start, @function +_start: + /* set up the system stack */ + la.local $r3, _system_stack_top + + /* + * Keep the direct mapping windows that U-Boot already installed for us: + * 0x9000_0000_0000 -> cached window + * 0x8000_0000_0000 -> uncached window + */ + li.d $r12, 0x9000000000000011 + csrwr $r12, LOONGARCH_CSR_DMW1 + li.d $r12, 0x8000000000000001 + csrwr $r12, LOONGARCH_CSR_DMW0 + dbar 0 + + /* + * U-Boot may have loaded the image through the cached window, make + * sure that it is visible to the instruction fetch before running. + */ + la.local $r12, _start + la.local $r13, __bss_end +1: + bgeu $r12, $r13, 2f + cacop 0x11, $r12, 0 /* hit writeback invalidate D-cache */ + cacop 0x10, $r12, 0 /* hit invalidate I-cache */ + addi.d $r12, $r12, 64 + b 1b +2: + dbar 0 + ibar 0 + + /* clear the .bss section */ + la.local $r12, __bss_start + la.local $r13, __bss_end +3: + bgeu $r12, $r13, 4f + st.d $zero, $r12, 0 + addi.d $r12, $r12, 8 + b 3b +4: + + /* + * Exception entry: 64 vectors, 0x40 bytes each. + * ECFG.VS = log2(0x40 / 4) = 4. + * Enable the timer interrupt and the cascaded SoC interrupt controller. + */ + la.local $r12, _exc_vectors + csrwr $r12, LOONGARCH_CSR_EENTRY + + li.w $r12, CSR_ECFG_VS_64 | (1 << LOONGARCH_IRQ_TIMER) | (1 << LOONGARCH_IRQ_HWI2) + csrwr $r12, LOONGARCH_CSR_ECFG + + dbar 0 + ibar 0 + + bl rtthread_startup + +5: + b 5b + .size _start, . - _start diff --git a/libcpu/loongarch/la264/timer.c b/libcpu/loongarch/la264/timer.c new file mode 100644 index 0000000000000000000000000000000000000000..f9c3737999018f7cfb6bcf0cea3abd3234596fdf --- /dev/null +++ b/libcpu/loongarch/la264/timer.c @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2006-2026, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2026-11-12 RT-Thread first version for LoongArch64 + */ + +#include +#include + +#include "loongarch.h" + +/* + * The LoongArch constant timer runs from the reference clock of the SoC. + * LS2K0300 uses a 100MHz reference clock. + */ +#ifndef LOONGARCH_TIMER_FREQ +#define LOONGARCH_TIMER_FREQ 100000000UL +#endif + +void rt_hw_timer_init(void) +{ + rt_uint64_t ticks; + + /* clear a pending timer interrupt */ + loongarch_write_csr(LOONGARCH_CSR_TICLR, CSR_TICLR_TI); + + ticks = (rt_uint64_t)LOONGARCH_TIMER_FREQ / RT_TICK_PER_SECOND; + loongarch_write_csr(LOONGARCH_CSR_TCFG, + (ticks << CSR_TCFG_VAL_SHIFT) | CSR_TCFG_PERIOD | CSR_TCFG_EN); +} + +void rt_hw_us_delay(rt_uint32_t us) +{ + rt_uint64_t start = loongarch_read_time(); + rt_uint64_t delta = (rt_uint64_t)us * (LOONGARCH_TIMER_FREQ / 1000000UL); + + while ((loongarch_read_time() - start) < delta) + { + /* busy wait */ + } +}